本文介绍了打印预测ValueError:预期的2D数组,取而代之的是1D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该错误显示在我的最后两个代码中.

The error shows in my last two codes.


import numpy as np

import pandas as pd

from sklearn.model_selection import ShuffleSplit

%matplotlib inline

df = pd.read_csv('.......csv')
df.drop(['Company'], 1, inplace=True)

x = pd.DataFrame(df.drop(['R&D Expense'],1))
y = pd.DataFrame(df['R&D Expense'])

X_test = x.index[[0,1]]
y_test = y.index[[0,1]]

X_train = x.drop(x.index[[0,1]])
y_train = y.drop(y.index[[0,1]])

from sklearn.metrics import r2_score
def performance_metric(y_true, y_predict):
    score = r2_score(y_true, y_predict)
    return score

from sklearn.metrics import make_scorer
from sklearn.neighbors import KNeighborsRegressor
from sklearn.model_selection import GridSearchCV

def fit_model_shuffle(x, y):

  cv_sets = ShuffleSplit(n_splits = 10, test_size = 0.20, random_state = 0)

  regressor = KNeighborsRegressor()
    params = {'n_neighbors':range(3,10)}

       scoring_fnc = make_scorer(performance_metric)
     grid = GridSearchCV(regressor, param_grid=params,scoring=scoring_fnc,cv=cv_sets)
    grid = grid.fit(x, y)
    return grid.best_estimator_

reg = fit_model_shuffle(X_train, y_train)

> for i, y_predict in enumerate(reg.predict(X_test),1):
    print(i, y_predict)

推荐答案

错误消息是不言自明的.您的库希望输入为2D矩阵,每行一个模式.因此,如果您仅使用一个输入进行回归,则在将其传递给回归器之前,先做

The error message is self-explanatory. Your library expects the input to be a 2D matrix, with one pattern per row. So, if you are doing regression with just one input, before passing it to the regressor, do

my_data = my_data.reshape(-1, 1)

制作一个 2X1 形状的矩阵

另一方面(不太可能),如果您有一个向量 [0,1]

On the other hand (unlikely), if you have a single vector [0, 1]

my_data = my_data.reshape(1, -1)

制作一个 1X2 矩阵

这篇关于打印预测ValueError:预期的2D数组,取而代之的是1D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 03:09