Scikit-learn SVM:重塑 X 导致不兼容的形状

Scikit-learn SVM: Reshaping X leads to incompatible shapes

我尝试使用 scikit-learn SVM 来预测 S&P500 中的股票是否跑赢指​​数。 我有 'sample' 文件,我从中提取特征 X 和标签(打败索引或不打败它)Y。

当我第一次尝试时(没有重塑 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的整形。 但是现在我得到以下值错误,即 X 和 Y 的形状不同。

ValueError: X and y have incompatible shapes.
X has 4337 samples, but y has 393.

下面你可以看到整形前的X和Y的形状:

('Shape of X = ', (493, 9))
('Shape of Y = ', (493,))

重塑后:

('Shape of X = ', (4437, 1))
('Shape of Y = ', (493,))

我也尝试重塑形状以获得 (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']])

SVM 测试:

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)

如果您对如何解决这个问题有任何意见,那就太好了。

您不应该将 X 重塑为 (-1, 1)。事实上,错误是在您调用 predict 方法时出现的。

改变

clf.predict(X[-x])[0]

clf.predict(X[-x].reshape((-1, 9)))[0]