首页 > 解决方案 > 在张量流中使用梯度 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 描述,但无法理解。

请解释

标签: pythontensorflowmachine-learning

解决方案


推荐阅读