python - 在张量流中使用梯度 API
问题描述
我正在阅读张量流中的线性回归。下面是示例代码。
n_epochs = 1000
learning_rate = 0.01
X = tf.constant(scaled_housing_data_plus_bias, dtype=tf.float32, name="X")
y = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name="y")
theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0, seed=42), name="theta")
y_pred = tf.matmul(X, theta, name="predictions")
error = y_pred - y
mse = tf.reduce_mean(tf.square(error), name="mse")
gradients = tf.gradients(mse, [theta])[0]
training_op = tf.assign(theta, theta - learning_rate * gradients)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for epoch in range(n_epochs):
if epoch % 100 == 0:
print("Epoch", epoch, "MSE =", mse.eval())
sess.run(training_op)
best_theta = theta.eval()
print("Best theta:")
print(best_theta)
据我了解
dc_w, dc_b = tf.gradients(cost, [w,b])
上面[w,b]
是一个列表,但在 theta 下面是大小矩阵,例如带有偏差的形状(9, 1)
假设第一个是偏差项,然后是 w1,---w8。
但是作者将 theta 传递为[theta]
,并没有得到计算的输出以及输出的外观。
我的问题是为什么作者[0]
在下面的行中使用
gradients = tf.gradients(mse, [theta])[0]
我不明白上面的线路试图做什么。我查看了张量流的 API 描述,但无法理解。
请解释
解决方案
推荐阅读
- rust - 在 Rust 中模仿 Python 输入函数的惯用方式
- c# - Angular8 应用程序 http 页面刷新错误 405
- angular - ngx-pagination 不适用于过滤表
- python - 给定一组数据点拟合积分函数
- php - 查询执行没有错误,但数据库中没有数据
- python - 删除图像“分类”中的 argsort 函数?
- ios - 在模拟器中测试 IAP - react-native?
- c# - 参数字典包含不可为空类型“System.Int32”的参数“parameter_name”的空条目
- python - 如何在 Mac 上将 Python3 设置为默认的 Python 版本?
- python - 爬取 0 页(以 0 页/分钟),抓取 0 项(以 0 项/分钟)