获取异常Exception: Data must be 1-dimensional
在Python 3.7中使用NumPy
相同的代码对其他人有用,但对我而言不起作用。贝娄是我的代码,请帮助
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)
预期输出应为
火车-预测变量的形状(80,1)
测试-预测变量的形状(20,1)
火车-目标形状(80,1)
测试-目标形状(20,1)
输出异常Exception: Data must be 1-dimensional
答案 0 :(得分:1)
我认为您需要在基础的numpy数组上而不是在Pandas系列上调用np.reshape
-您可以使用.values
进行此操作:
x_train = np.reshape(x_train.values, (-1, 1))
在接下来的三行中重复同样的想法。
或者,如果您使用的是Pandas的最新版本> = 0.24,则首选to_numpy
:
x_train = np.reshape(x_train.to_numpy(), (-1, 1))
答案 1 :(得分:1)
numpy.squeeze()
从 NumPy 数组中删除大小为 1 的所有维度。
x_train = numpy.squeeze(x_train)
将 (80,1) 数组转换为 (80,)