首页 > 解决方案 > ValueError:预期的 2D 数组,得到了标量数组:array=5.5

问题描述

为什么我收到以下错误?

ValueError:预期的 2D 数组,得到了标量数组:array=5.5。如果您的数据具有单个特征,则使用 array.reshape(-1, 1) 重塑您的数据,如果它包含单个样本,则使用 array.reshape(1, -1) 。

这是我的代码:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.read_csv("decision-tree-regression-dataset.csv",sep = ";",header = None)
x = df.iloc[:,0].values.reshape(-1,1)
y = df.iloc[:,1].values.reshape(-1,1)

# decision tree regression
from sklearn.tree import DecisionTreeRegressor
tree_reg = DecisionTreeRegressor()   # random sate = 0
tree_reg.fit(x,y)
tree_reg.predict(5.5)
x_ = np.arange(min(x),max(x),0.01).reshape(-1,1)
y_head = tree_reg.predict(x_)

# visualize
plt.scatter(x,y,color="red")
plt.plot(x_,y_head,color = "green")
plt.xlabel("tribun level")
plt.ylabel("ucret")
plt.show()

标签: pythonmachine-learningpython-3.7

解决方案


尝试使用它来预测:

  tree_reg.predict([[5.5]])  

注意使用 [[]] 作为二维数组,如 (sample_num, feature_num)


推荐阅读