使用tensorflow实现多变量线性回归模型,权重有3个,分别为9.0、2.0、8.0,偏置为1.0,无需在控制台输出结果,但是要使用matplotlib输出图像
时间: 2024-05-12 22:20:11 浏览: 44
```python
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# 定义数据集
x_data = np.random.rand(100, 3)
w_real = [9.0, 2.0, 8.0]
b_real = 1.0
y_data = np.matmul(w_real, x_data.T) + b_real
# 定义模型参数
NUM_STEPS = 50
LEARNING_RATE = 0.5
# 定义 tensorflow 计算图
g = tf.Graph()
with g.as_default():
# 定义占位符
x = tf.placeholder(tf.float32, shape=[None, 3])
y_true = tf.placeholder(tf.float32, shape=None)
# 定义模型
with tf.name_scope('inference') as scope:
w = tf.Variable([[0, 0, 0]], dtype=tf.float32, name='weights')
b = tf.Variable(0, dtype=tf.float32, name='bias')
y_pred = tf.matmul(w, tf.transpose(x)) + b
# 定义损失函数
with tf.name_scope('loss') as scope:
loss = tf.reduce_mean(tf.square(y_true - y_pred))
# 定义优化器
with tf.name_scope('train') as scope:
optimizer = tf.train.GradientDescentOptimizer(LEARNING_RATE)
train = optimizer.minimize(loss)
init = tf.global_variables_initializer()
# 训练模型
with tf.Session(graph=g) as sess:
sess.run(init)
for step in range(NUM_STEPS):
_, loss_val, w_val, b_val = sess.run([train, loss, w, b], feed_dict={x: x_data, y_true: y_data})
if (step + 1) % 5 == 0:
print('Step {}: Loss = {}, w = {}, b = {}'.format(step + 1, loss_val, w_val, b_val))
# 绘制图像
w_res = w.eval()
b_res = b.eval()
y_pred_res = np.matmul(w_res, x_data.T) + b_res
plt.plot(y_data, y_pred_res[0], 'ro')
plt.plot([y_data.min(), y_data.max()], [y_data.min(), y_data.max()], 'k--')
plt.xlabel('Actual')
plt.ylabel('Predicted')
plt.show()
```
注:以上代码为 TensorFlow 1.x 版本的实现方式。对于 TensorFlow 2.x 版本,需要进行相应的修改。
阅读全文