我正在研究 Aurelien Geron 的“机器学习实践”一书中的 Tensorflow 示例。但是,我无法复制 this supporting notebook 中的简单线性回归示例。 .为什么 Tensorflow 不匹配 Numpy/SciKit-Learn 结果?
据我所知,没有优化(我们使用的是正规方程,所以它只是矩阵计算),答案似乎差异太大,不可能是精度错误。
import numpy as np
import tensorflow as tf
from sklearn.datasets import fetch_california_housing
housing = fetch_california_housing()
m, n = housing.data.shape
housing_data_plus_bias = np.c_[np.ones((m, 1)), housing.data]
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")
XT = tf.transpose(X)
theta = tf.matmul(tf.matmul(tf.matrix_inverse(tf.matmul(XT, X)), XT), y)
with tf.Session() as sess:
theta_value = theta.eval()
theta_value
回答:
array([[ -3.74651413e+01],
[ 4.35734153e-01],
[ 9.33829229e-03],
[ -1.06622010e-01],
[ 6.44106984e-01],
[ -4.25131839e-06],
[ -3.77322501e-03],
[ -4.26648885e-01],
[ -4.40514028e-01]], dtype=float32)
###### 与纯 NumPy 比较
X = housing_data_plus_bias
y = housing.target.reshape(-1, 1)
theta_numpy = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y)
print(theta_numpy)
回答:
[[ -3.69419202e+01]
[ 4.36693293e-01]
[ 9.43577803e-03]
[ -1.07322041e-01]
[ 6.45065694e-01]
[ -3.97638942e-06]
[ -3.78654265e-03]
[ -4.21314378e-01]
[ -4.34513755e-01]]
###### 与 Scikit-Learn 比较
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(housing.data, housing.target.reshape(-1, 1))
print(np.r_[lin_reg.intercept_.reshape(-1, 1), lin_reg.coef_.T])
回答:
[[ -3.69419202e+01]
[ 4.36693293e-01]
[ 9.43577803e-03]
[ -1.07322041e-01]
[ 6.45065694e-01]
[ -3.97638942e-06]
[ -3.78654265e-03]
[ -4.21314378e-01]
[ -4.34513755e-01]]
更新:我的问题听起来类似于 this one ,但遵循建议并没有解决问题。
最佳答案
我只是比较了tensorflow
和numpy
的结果。由于您对 X
和 y
使用了 dtype=tf.float32
,因此我将使用 np.float32
作为 numpy
示例如下:
X_numpy = housing_data_plus_bias.astype(np.float32)
y_numpy = housing.target.reshape(-1, 1).astype(np.float32)
现在让我们尝试比较 tf.matmul(XT, X)
(tensorflow
) 和 X.T.dot(X)
( numpy
):
with tf.Session() as sess:
XTX_value = tf.matmul(XT, X).eval()
XTX_numpy = X_numpy.T.dot(X_numpy)
np.allclose(XTX_value, XTX_numpy, rtol=1e-06) # True
np.allclose(XTX_value, XTX_numpy, rtol=1e-07) # False
所以这就是float
的精度问题。如果将精度更改为 tf.float64
和 np.float64
,则 theta
的结果相同。
关于python - Tensorflow 线性回归结果与 Numpy/SciKit-Learn 不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48614321/