【问题标题】:Why do I get different weights when using TensorFlow for multiple linear regression?为什么在使用 TensorFlow 进行多元线性回归时会得到不同的权重?
【发布时间】: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


    【解决方案1】:

    问题似乎与广播有关。上面y_hat的形状是(100,1),而y的形状是(100,)。因此,当您执行tf.sub(y, y_hat) 时,您最终会得到一个(100,100) 矩阵,这是两个向量之间减法的所有可能组合。我不知道,但我猜你设法在 numpy 代码中避免了这种情况。

    修复代码的两种方法:

    y = np.array([[i * 0.4 + j * 0.9 + 1 for i, j in x]]).astype(np.float32).T
    

    y_hat = tf.squeeze(tf.matmul(x, w))
    

    尽管如此,当我运行它时,它实际上仍然不能收敛到你想要的答案,但至少它实际上能够最小化损失函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-10
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      • 2016-09-06
      • 1970-01-01
      • 2018-08-11
      • 2013-07-14
      相关资源
      最近更新 更多