我尝试使用 scikit-learn SVM 来预测标准普尔 500 指数的股票是否优于指数。
我有“样本”文件,从中提取特征 X 和标签(超过索引或不超过索引)Y。
当我第一次尝试时(没有 reshape X),我得到了以下折旧错误:
DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17
and will raise ValueError in 0.19. Reshape your data either using
X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1)
if it contains a single sample.
因此,我尝试根据建议以及一些论坛帖子对 X 进行 reshape 。
但是,现在我得到以下值错误,即 X 和 Y 的形状不同。
ValueError: X and y have incompatible shapes.
X has 4337 samples, but y has 393.
下面你可以看到 reshape 前 X 和 Y 的形状:
('Shape of X = ', (493, 9))
('Shape of Y = ', (493,))
并在 reshape 后:
('Shape of X = ', (4437, 1))
('Shape of Y = ', (493,))
我还尝试 reshape 形状以获得 (493,9) 形状,但这也不起作用,因为我收到以下错误。
ValueError: total size of new array must be unchanged.
我在代码下方发布了从 pandas DataFrame 和 SVM 分析中提取特征和标签的代码:
功能和标签选择:
X = np.array(sample[features].values)
X = preprocessing.scale(X)
X = np.array(X)
X = X.reshape(-1,1)
Y = sample['status'].values.tolist()
Y = np.array(Y)
Z = np.array(sample[['changemktvalue', 'benchmark']])
支持向量机测试:
test_size = 50
invest_amount = 1000
total_invests = 0
if_market = 0
if_strat = 0
clf = svm.SVC(kernel="linear", C= 1.0)
clf.fit(X[:-test_size],Y[:-test_size])
correct_count = 0
for x in range(1, test_size+1):
if clf.predict(X[-x])[0] == Y[-x]:
correct_count += 1
if clf.predict(X[-x])[0] == 1:
invest_return = invest_amount + (invest_amount * (Z[-x][0]/100)) #zeroth element of z
market_return = invest_amount + (invest_amount * (Z[-x][1]/100)) #marketsp500 is at pos 1
total_invests += 1
if_market += market_return
if_strat += invest_return
print("Accuracy:", (float(correct_count)/test_size) * 100.00)
如果您对如何解决这个问题有任何意见,那就太好了。
最佳答案
你不应该 reshape X
至(-1, 1)
.事实上,错误在于您对 predict
的调用。方法。
改变
clf.predict(X[-x])[0]
到
clf.predict(X[-x].reshape((-1, 9)))[0]
关于python - Scikit-learn SVM : Reshaping X leads to incompatible shapes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38829135/