使用tensorflow完成线性回归报错
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
def linear_regression_demo():
# 1)准备真实值,随机生成100行1列
X = tf.compat.v1.random_normal(shape=[100, 1])
y_true = tf.matmul(X, [[0.8]]) + 0.7
# 2)构造模型,定义模型参数用变量
weights = tf.Variable(initial_value=tf.compat.v1.random_normal(shape=[1, 1]))
bias = tf.Variable(initial_value=tf.compat.v1.random_normal(shape=[1, 1]))
y_predict = tf.matmul(X, weights) + bias
# 3)损失函数
error = tf.reduce_mean(tf.square(y_predict - y_true))
# 4)优化损失
optimizer = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=0.01).minimize(error)
# 2_收集变量
tf.summary.scalar('error', error)
tf.summary.histogram("weights", weights)
tf.summary.histogram("bias", bias)
# 3_合并变量
merged = tf.compat.v1.summary.merge_all()
# 开启会话
init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
# 初始化变量
sess.run(init)
# 1_创建事件文件
file_writer = tf.compat.v1.summary.FileWriter("./venv/Linear", graph=sess.graph)
# 查看初始化后模型参数的值
print("训练前模型参数为:权重%f,偏执%f,损失为%f" % (weights.eval(), bias.eval(), error.eval()))
# 开始训练
for i in range(100):
sess.run(optimizer)
print("第%d次训练后模型参数为:权重%f,偏执%f,损失为%f" % (i+1, weights.eval(), bias.eval(), error.eval()))
# 合并变量操作
summary = sess.run(merged)
# 写入事件文件
file_writer.add_summary(summary, i)
# 若下面的print在循环体中,则可以看到每次迭代后的值,即看到训练的过程
return None
if __name__ == "__main__":
# 实现线性回归
linear_regression_demo()
运行结果及报错内容
训练前模型参数为:权重1.473141,偏执-0.302616,损失为1.375756
第1次训练后模型参数为:权重1.458058,偏执-0.283769,损失为1.439239
Traceback (most recent call last):
File "E:/pycharm2022/pythonproject/Linear_regression.py", line 50, in <module>
linear_regression_demo()
File "E:/pycharm2022/pythonproject/Linear_regression.py", line 41, in linear_regression_demo
summary = sess.run(merged)
File "E:\pycharm2022\pythonproject\venv\lib\site-packages\tensorflow\python\client\session.py", line 968, in run
result = self._run(None, fetches, feed_dict, options_ptr,
File "E:\pycharm2022\pythonproject\venv\lib\site-packages\tensorflow\python\client\session.py", line 1176, in _run
fetch_handler = _FetchHandler(
File "E:\pycharm2022\pythonproject\venv\lib\site-packages\tensorflow\python\client\session.py", line 485, in __init__
self._fetch_mapper = _FetchMapper.for_fetch(fetches)
File "E:\pycharm2022\pythonproject\venv\lib\site-packages\tensorflow\python\client\session.py", line 262, in for_fetch
raise TypeError(f'Argument `fetch` = {fetch} has invalid type '
TypeError: Argument `fetch` = None has invalid type "NoneType". Cannot be None
Process finished with exit code 1
我的解答思路和尝试过的方法
还不知道为什么出错,求解