【发布时间】:2023-03-15 07:12:01
【问题描述】:
这个问题似乎以前被问过,但我似乎无法评论以进一步澄清接受的答案,我无法弄清楚所提供的解决方案。
我正在尝试学习如何将 sklearn 与我自己的数据一起使用。我基本上只是得到了过去 100 年来 2 个不同国家的 GDP 年变化百分比。我现在只是想学习使用单个变量。我实际上要做的是使用 sklearn 来预测 A 国的 GDP 百分比变化将根据 B 国 GDP 的百分比变化。
问题是我收到一条错误消息:
ValueError:发现样本数量不一致的数组:[ 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]
【问题讨论】:
-
在分成训练集/测试集之前检查
chntrain和austrain的形状。它们应该具有相同的形状;该错误似乎表明尺寸不同 -
我该怎么做?我一直在谷歌搜索,但每一个让我重塑或找到形状的解决方案都会给出错误:IndexError: too many indices for array
-
例如
print chngdpchange.shape, ausgdpchange.shape
标签: python arrays numpy machine-learning scikit-learn