这个问题之前似乎有人问过,但我似乎无法评论以进一步澄清已接受的答案,而且我无法弄清楚所提供的解决方案。
我正在尝试学习如何使用 sklearn 处理我自己的数据。我基本上只是得到了过去 100 年中两个不同国家 GDP 的年度百分比变化。我现在只是想学习使用单个变量。我基本上想做的是使用 sklearn 来预测国家 A 的 GDP 百分比变化将给定国家 B 的 GDP 的百分比变化。
问题是我收到一条错误消息:
ValueError: Found arrays with inconsistent numbers of samples: [ 1 107]
这是我的代码:
import sklearn.linear_model as lm
import numpy as np
import scipy.stats as st
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
def bytespdate2num(fmt, encoding='utf-8'):#function to convert bytes to string for the dates.
strconverter = mdates.strpdate2num(fmt)
def bytesconverter(b):
s = b.decode(encoding)
return strconverter(s)
return bytesconverter
dataCSV = open('combined_data.csv')
comb_data = []
for line in dataCSV:
comb_data.append(line)
date, chngdpchange, ausgdpchange = np.loadtxt(comb_data, delimiter=',', unpack=True, converters={0: bytespdate2num('%d/%m/%Y')})
chntrain = chngdpchange[:-1]
chntest = chngdpchange[-1:]
austrain = ausgdpchange[:-1]
austest = ausgdpchange[-1:]
regr = lm.LinearRegression()
regr.fit(chntrain, austrain)
print('Coefficients: \n', regr.coef_)
print("Residual sum of squares: %.2f"
% np.mean((regr.predict(chntest) - austest) ** 2))
print('Variance score: %.2f' % regr.score(chntest, austest))
plt.scatter(chntest, austest, color='black')
plt.plot(chntest, regr.predict(chntest), color='blue')
plt.xticks(())
plt.yticks(())
plt.show()
我做错了什么?我基本上尝试将 sklearn 教程(他们使用了一些糖尿病数据集)应用于我自己的简单数据。我的数据只包含日期、国家 A 在该特定年份的 GDP 变化百分比,以及国家 B 在同一年的 GDP 变化百分比。
我尝试了解决方案 here和 here (basically trying to find more out about the solution in the first link) , 但只是收到完全相同的错误。
如果您想查看,这里是完整的回溯:
Traceback (most recent call last):
File "D:\My Stuff\Dropbox\Python\Python projects\test regression\tester.py", line 34, in <module>
regr.fit(chntrain, austrain)
File "D:\Programs\Installed\Python34\lib\site-packages\sklearn\linear_model\base.py", line 376, in fit
y_numeric=True, multi_output=True)
File "D:\Programs\Installed\Python34\lib\site-packages\sklearn\utils\validation.py", line 454, in check_X_y
check_consistent_length(X, y)
File "D:\Programs\Installed\Python34\lib\site-packages\sklearn\utils\validation.py", line 174, in check_consistent_length
"%s" % str(uniques))
ValueError: Found arrays with inconsistent numbers of samples: [ 1 107]
最佳答案
在 fit(X,y) 中,输入参数 X 应该是一个二维数组。但是如果你的数据中的 X 只是一维的,你可以像这样将它 reshape 成一个二维数组:regr.fit(chntrain_X.reshape(len(chntrain_X), 1), chntrain_Y)
关于python - sklearn 问题 : Found arrays with inconsistent numbers of samples when doing regression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32097392/