【发布时间】:2017-01-23 17:45:50
【问题描述】:
我有两种多重线性回归的实现,一种使用tensorflow,另一种仅使用numpy。我生成了一组虚拟数据并尝试恢复我使用的权重,但尽管 numpy 返回初始权重,tensorflow 总是返回不同的权重(这也是一种工作)
numpy 的实现是here,这是 TF 的实现:
import numpy as np
import tensorflow as tf
x = np.array([[i, i + 10] for i in range(100)]).astype(np.float32)
y = np.array([i * 0.4 + j * 0.9 + 1 for i, j in x]).astype(np.float32)
# Add bias
x = np.hstack((x, np.ones((x.shape[0], 1)))).astype(np.float32)
# Create variable for weights
n_features = x.shape[1]
np.random.rand(n_features)
w = tf.Variable(tf.random_normal([n_features, 1]))
w = tf.Print(w, [w])
# Loss function
y_hat = tf.matmul(x, w)
loss = tf.reduce_mean(tf.square(tf.sub(y, y_hat)))
operation = tf.train.GradientDescentOptimizer(learning_rate=0.000001).minimize(loss)
with tf.Session() as session:
session.run(tf.initialize_all_variables())
for iteration in range(5000):
session.run(operation)
weights = w.eval()
print(weights)
运行脚本让我得到大约[-0.481, 1.403, 0.701] 的权重,而运行numpy 版本得到大约[0.392, 0.907, 0.9288] 的权重,这更接近我用来生成数据的权重:[0.4, 0.9, 1]
两个学习率/历元参数相同,并且都随机初始化权重。我没有对任何一个实现的数据进行规范化,我已经多次运行它们。
为什么结果不同?我还尝试使用w = tf.Variable(np.random.rand(n_features).reshape(n_features,1).astype(np.float32)) 在 TF 版本中初始化权重,但这也没有解决它。 TF 实现有问题吗?
【问题讨论】:
标签: python numpy machine-learning tensorflow regression