【发布时间】:2018-05-23 08:48:14
【问题描述】:
我正在通过线性回归示例学习 TensorFlow 的基础知识。使用 scikit-learn 执行线性回归效果很好:
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.linear_model import LinearRegression
housing = fetch_california_housing()
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]]
使用 numpy(正规方程)执行同样的操作也可以正常工作:
m, n = housing.data.shape
housing_data_plus_bias = np.c_[np.ones((m, 1)), housing.data]
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]]
但是,当我在运行线性回归之前导入 TensorFlow 时,我会得到可变且不准确的结果:
import tensorflow as tf
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.linear_model import LinearRegression
housing = fetch_california_housing()
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])
产生以下结果(每次不同的值):
[[ 2.91247440e+32]
[ -1.62971964e+11]
[ 1.42425463e+14]
[ -4.82459003e+16]
[ -1.33258747e+17]
[ -2.04315813e+29]
[ 5.51179654e+14]
[ 5.92729561e+20]
[ 8.86284674e+21]]
如果我在导入 tensorflow 之前运行任一计算,然后导入 tensorflow 并再次重复计算,我会得到正确的结果。
知道原因是什么以及如何确保在导入 TensorFlow 后从 numpy/scikit-learn 获得正确的结果?
我在 Ubuntu 上使用 tensorflow-gpu 从 Anaconda 4.3.30 运行 Python 3.5.4。
numpy version: 1.12.1
tensorflow version: 1.3.0
【问题讨论】:
-
感谢@sascha 的领导。这个问题确实似乎与 TensorFlow 和 Anaconda 发行版附带的 MKL 库之间的不良交互有关。如here 所示,使用
export MKL_NUM_THREAD="1"可以让我得到正确的结果。
标签: python numpy tensorflow scikit-learn