【发布时间】:2020-08-20 21:02:55
【问题描述】:
我正在运行来自 Aurélien Géron 使用 Scikit-Learn 和 TensorFlow 的动手机器学习的 first chapter 的代码。
我要运行的代码是:
# Code example
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sklearn.linear_model
# Load the data
oecd_bli = pd.read_csv(datapath + "oecd_bli_2015.csv", thousands=',')
gdp_per_capita = pd.read_csv(datapath + "gdp_per_capita.csv",thousands=',',delimiter='\t',
encoding='latin1', na_values="n/a")
# Prepare the data
country_stats = prepare_country_stats(oecd_bli, gdp_per_capita)
X = np.c_[country_stats["GDP per capita"]]
y = np.c_[country_stats["Life satisfaction"]]
# Visualize the data
country_stats.plot(kind='scatter', x="GDP per capita", y='Life satisfaction')
plt.show()
# Select a linear model
model = sklearn.linear_model.LinearRegression()
# Train the model
model.fit(X, y)
它在步骤model.fit(X, y) 失败,并带有以下回溯:
ValueError Traceback (most recent call last)
in
23
24 # # Train the model
---> 25 model.fit(X, y)
26
27 # # Make a prediction for Cyprus
~\AppData\Local\Programs\Python\venv\ds\lib\site-packages\sklearn\linear_model\_base.py in fit(self, X, y, sample_weight)
531 else:
532 self.coef_, self._residues, self.rank_, self.singular_ = \
--> 533 linalg.lstsq(X, y)
534 self.coef_ = self.coef_.T
535
~\AppData\Local\Programs\Python\venv\ds\lib\site-packages\scipy\linalg\basic.py in lstsq(a, b, cond, overwrite_a, overwrite_b, check_finite, lapack_driver)
1223 raise LinAlgError("SVD did not converge in Linear Least Squares")
1224 if info < 0:
-> 1225 raise ValueError('illegal value in %d-th argument of internal %s'
1226 % (-info, lapack_driver))
1227 resids = np.asarray([], dtype=x.dtype)
ValueError: illegal value in 4-th argument of internal None
但是,当我在没有 plt.show() 命令的情况下重新运行 fit 函数时,它可以正常工作:
country_stats.plot(kind='scatter', x="GDP per capita", y='Life satisfaction')
model.fit(X, y) # works OK
# # Make a prediction for Cyprus
X_new = [[22587]] # Cyprus' GDP per capita
print(model.predict(X_new)) # outputs [[ 5.96242338]]
这种行为非常奇怪。不知道是不是因为我的包版本。这是我当前的软件包版本:
pip freeze | grep -E "numpy|pandas|scipy|matplotlib|sci"
matplotlib==3.2.1
numpy==1.18.4
pandas==0.25.3
scikit-image==0.16.2
scikit-learn==0.22
scipy==1.4.1
【问题讨论】:
-
您的第二个 sn-p 中确实缺少
plt.show()(与第一个相反),还是您刚刚忘记包含它? -
你是对的。 plt.show() 在我的第二个 sn-p 中丢失,当我包含它时,它再次中断。看起来 plt.show() 导致了这个问题。我会相应地更新我的案例描述。
-
另一个潜在问题可能是 scipy (linalg) 安装损坏。 Sklearn 使用
scipy.sparse.linalg.LinearOperator。 -
所以,我从您发布的链接运行代码,一切似乎都很好。即使代码中有
plt.show()。我运行代码 10 次。 10 次成功的试验。尝试仔细检查X、ydata 并重新安装numpy和scipy -
制作一个完整的新内核并再次运行它,它应该可以工作,错误表明一个空数组不知何故
标签: python matplotlib scikit-learn