Numpy Python:例外:数据必须是一维的

sou*_*rav 3 regression numpy linear-regression python-3.x

获取异常 Exception: Data must be 1-dimensional

在 Python 3.7 中使用 NumPy

相同的代码适用于其他人,但不适用于我的情况。波纹管是我的代码请帮忙

Working_code_in_diff_system

Same_code_not_working_in_my_system

import numpy as np 
from sklearn import linear_model
from sklearn.model_selection import train_test_split
import seaborn as sns
from sklearn import metrics
import matplotlib.pyplot as plt
%matplotlib inline

df = pd.read_csv('./Data/new-data.csv', index_col=False)

x_train, x_test, y_train, y_test = train_test_split(df['Hours'], df['Marks'], test_size=0.2, random_state=42)

sns.jointplot(x=df['Hours'], y=df['Marks'], data=df, kind='reg')

x_train = np.reshape(x_train, (-1,1))
x_test = np.reshape(x_test, (-1,1))
y_train = np.reshape(y_train, (-1,1))
y_test = np.reshape(y_test, (-1,1))



#
print('Train - Predictors shape', x_train.shape)
print('Test - Predictors shape', x_test.shape)
print('Train - Target shape', y_train.shape)
print('Test - Target shape', y_test.shape)

Run Code Online (Sandbox Code Playgroud)

预期输出应该是

训练 - 预测器形状 (80, 1)

测试 - 预测变量形状 (20, 1)

训练 - 目标形状 (80, 1)

测试 - 目标形状 (20, 1)

作为输出获取异常 Exception: Data must be 1-dimensional

the*_*orm 5

我认为你需要调用np.reshape底层的 numpy 数组而不是 Pandas 系列 - 你可以使用.values

x_train = np.reshape(x_train.values, (-1, 1))
Run Code Online (Sandbox Code Playgroud)

对接下来的三行重复相同的想法。

或者,如果您使用的是 Pandas 的最新版本 >= 0.24,to_numpy则首选:

x_train = np.reshape(x_train.to_numpy(), (-1, 1))
Run Code Online (Sandbox Code Playgroud)