在张量流中写回归,但为什么MSE不会逐渐减少?

时间:2018-01-30 03:56:45

标签: python tensorflow

我正在tensorflow中编写回归渐变更新过程。使用" tf.assign"随机初始化theta并计算梯度以进行更新。此外,我每100次迭代打印出MSE值。但是,我没有看到迭代后MSE数量减少。请让我知道为什么它不会逐渐减少?我的以下代码有什么问题吗?

import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.preprocessing import StandardScaler

housing = fetch_california_housing()
m, n = housing.data.shape
scaler = StandardScaler()
scaler.fit(housing.data)
scaled_data = scaler.transform(housing.data)
housing_data_plus_bias = np.c_[np.ones((m,1)), scaled_data]


n_epochs = 1000
learning_rate = 0.01

# [1] Construction Phrase
x = tf.constant(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), name="theta") # initialize randomly n+1 X 1 array for thetas
y_pred = tf.matmul(x, theta, name="predicitions")

error = y_pred - y
mse = tf.reduce_mean(tf.square(error), name="mse")

gradients = 2/m * tf.matmul(tf.transpose(x), error)
update_op = tf.assign(theta, theta - learning_rate * gradients)


# [2] Execution Phrase
init = tf.global_variables_initializer()

with tf.Session() as sess:
   sess.run(init)

   for epoch in range(n_epochs):

       if epoch % 100 == 0:
           print(mse.eval())
       sess.run(update_op)


   best_theta = theta.eval()

输出:

9.366995
9.366995
9.366995
9.366995
9.366995
9.366995
9.366995
9.366995
9.366995
9.366995

1 个答案:

答案 0 :(得分:0)

我认为你的问题是整数除法。在Python 2中,标准除法运算符计算整数而不是浮点除法。在gradients = 2/m * tf.matmul(tf.transpose(x), error)行中,2/m评估为0,因此您没有渐变。将from __future__ import division添加到您的脚本顶部,您应该很高兴。