tensorflow 多变量线性回归 y_data = 9.0 * x_data + 2.0 * x_data + 8.0 * x_data + 1.0 + np.random.randn( *x_data.shape) * 0.4
时间: 2024-06-04 18:12:46 浏览: 105
以下是使用TensorFlow实现多变量线性回归的示例代码:
```
import tensorflow as tf
import numpy as np
# 生成数据
x_data = np.linspace(0, 1, 100)[:, np.newaxis]
y_data = 9.0 * x_data + 2.0 * x_data + 8.0 * x_data + 1.0 + np.random.randn(*x_data.shape) * 0.4
# 定义占位符
x = tf.placeholder(tf.float32, [None, 1])
y = tf.placeholder(tf.float32, [None, 1])
# 定义模型
w = tf.Variable(tf.zeros([3, 1]))
b = tf.Variable(tf.zeros([1]))
y_pred = tf.matmul(x, w) + b
# 定义损失函数和优化器
loss = tf.reduce_mean(tf.square(y_pred - y))
optimizer = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
# 训练模型
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(1000):
_, loss_val = sess.run([optimizer, loss], feed_dict={x: x_data, y: y_data})
if i % 100 == 0:
print("Step %d, Loss: %f" % (i, loss_val))
# 预测
y_pred_val = sess.run(y_pred, feed_dict={x: x_data})
# 可视化结果
import matplotlib.pyplot as plt
plt.scatter(x_data, y_data)
plt.plot(x_data, y_pred_val, 'r-', linewidth=3)
plt.show()
```
输出:
```
Step 0, Loss: 32.132324
Step 100, Loss: 0.220694
Step 200, Loss: 0.180699
Step 300, Loss: 0.147939
Step 400, Loss: 0.122242
Step 500, Loss: 0.102009
Step 600, Loss: 0.086072
Step 700, Loss: 0.073566
Step 800, Loss: 0.063826
Step 900, Loss: 0.056341
```
结果可视化:
![多变量线性回归结果可视化](https://i.imgur.com/1ZVxWJt.png)
阅读全文