写一个简单的线性回归模型,在生成1维的W矩阵,取值是[-1,1]之间的随机数之后,该W不能顺利使得sess.run(W)运行。
下面是相关代码,相关模块已经安装调试:
# 生成1维的W矩阵,取值是[-1,1]之间的随机数
W= tf.Variable(tf.random.uniform([1],-1.0,1.0), name='W')
# 构造session
sess = tf.compat.v1.Session()
# 全局变量初始化
tf.compat.v1.disable_eager_execution()
init = tf.compat.v1.global_variables_initializer()
# 执行
sess.run(init)
# 初始化的w是多少
print("W = ", sess.run(W))
报错如下
Traceback (most recent call last):
File "D:\pythonProject\main.py", line 44, in <module>
print("W = ", sess.run(W), "b = ", sess.run(b), "lossesss = ", sess.run(loss))
File "D:\pythonProject\venv\lib\site-packages\tensorflow\python\client\session.py", line 970, in run
result = self._run(None, fetches, feed_dict, options_ptr,
File "D:\pythonProject\venv\lib\site-packages\tensorflow\python\client\session.py", line 1178, in _run
fetch_handler = _FetchHandler(
File "D:\pythonProject\venv\lib\site-packages\tensorflow\python\client\session.py", line 488, in __init__
self._fetch_mapper = _FetchMapper.for_fetch(fetches)
File "D:\pythonProject\venv\lib\site-packages\tensorflow\python\client\session.py", line 279, in for_fetch
return _ElementFetchMapper(fetches, contraction_fn)
File "D:\pythonProject\venv\lib\site-packages\tensorflow\python\client\session.py", line 310, in __init__
raise TypeError(f'Argument `fetch` = {fetch} has invalid type '
TypeError: Argument `fetch` = <tf.Variable 'W:0' shape=(1,) dtype=float32> has invalid type "ResourceVariable" must be a string or Tensor. (Can not convert a ResourceVariable into a Tensor or Operation.)
Process finished with exit code 1
请问该如何修改代码呢?