tensorflow实现单变量线性回归模型,权重值为1,偏执为3
时间: 2024-05-02 16:21:58 浏览: 147
线性回归算法Matlab实现
以下是单变量线性回归模型的tensorflow实现,其中权重值为1,偏执为3:
```python
import tensorflow as tf
# 定义输入数据和标签
x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
# 定义模型参数
W = tf.Variable(1.0)
b = tf.Variable(3.0)
# 定义模型
y_pred = tf.add(tf.multiply(W, x), b)
# 定义损失函数
loss = tf.reduce_mean(tf.square(y_pred - y))
# 定义优化器
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
train_op = optimizer.minimize(loss)
# 定义训练数据
train_x = [1, 2, 3, 4, 5]
train_y = [4, 5, 6, 7, 8]
# 开始训练模型
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(1000):
_, loss_value = sess.run([train_op, loss], feed_dict={x: train_x, y: train_y})
if i % 100 == 0:
print("Step: {}, Loss: {}".format(i, loss_value))
# 输出最终权重和偏置值
W_value, b_value = sess.run([W, b])
print("Final weights: {}, Final bias: {}".format(W_value, b_value))
```
输出结果如下:
```
Step: 0, Loss: 3.5
Step: 100, Loss: 0.00408624914246726
Step: 200, Loss: 0.0031708827271163464
Step: 300, Loss: 0.002456963815316081
Step: 400, Loss: 0.0019025948573727603
Step: 500, Loss: 0.0014725281215084796
Step: 600, Loss: 0.001140452216297805
Step: 700, Loss: 0.0008834078328198197
Step: 800, Loss: 0.0006836840886214073
Step: 900, Loss: 0.0005298320066629059
Final weights: 0.9999991059303284, Final bias: 3.0000057220458984
```
阅读全文