为什么在使用 TensorFlow 进行多元线性回归时会得到不同的权重?

Why do I get different weights when using TensorFlow for multiple linear regression?

我有两种多元线性回归的实现,一种使用 tensorflow,另一种仅使用 numpy。我生成了一组虚拟数据并尝试恢复我使用的权重,但是尽管 numpy 一个 returns 初始权重,tensorflow 一个总是 returns 不同的权重(这也是一种工作)

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]

两者学习rates/epochs参数相同,并且都运行domly初始化权重。我没有对任何一个实现的数据进行标准化,而且我已经 运行 它们多次。

为什么结果不同?我还尝试使用 w = tf.Variable(np.random.rand(n_features).reshape(n_features,1).astype(np.float32)) 在 TF 版本中初始化权重,但这也没有解决它。 TF实现有问题吗?

问题似乎与广播有关。上面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))

虽然,也就是说,当我运行这个的时候,它实际上仍然没有收敛到你想要的答案,但至少它实际上能够最小化损失函数。