预期的二维数组,改为标量数组

数据挖掘 机器学习 Python
2021-09-18 03:33:54

谁能帮我解决这个错误。我做了以下代码,但它不起作用,我收到以下错误:

ValueError: Expected 2D array, got scalar array instead:
array=6.5. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample. 

我的代码:

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

import pandas
dataset = pandas.read_excel('PEG RATIOS.xlsx')

X = dataset.iloc[:, 2].values
X =X.reshape(-1,1)
y = dataset.iloc[:, 3].values
y = y.reshape (-1,1)


from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X, y)

from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree = 4)
X_poly = poly_reg.fit_transform(X)
poly_reg.fit(X_poly, y)
lin_reg_2 = LinearRegression()
lin_reg_2.fit(X_poly, y)

X_grid = np.arange(min(X), max(X), 0.1)
X_grid = X_grid.reshape((len(X_grid), 1))
plt.scatter(X, y, color = 'red')
plt.plot(X_grid, lin_reg_2.predict(poly_reg.fit_transform(X_grid)), color = 'blue')
plt.title('PEG Ratios verrus Exoected Growth: Semiconductor Firms')
plt.xlabel('Expected Growth rate')
plt.ylabel('PEGH Ratio')
plt.show()
lin_reg_2.predict(poly_reg.fit_transform(6.5))
1个回答

错误本身可以解决您的问题。只要按照它说的去做。predict()方法采用您要预测的二维值数组。数组中的每个项目都是您希望模型预测的“点”。所以试试,

lin_reg_2.predict(poly_reg.fit_transform([[6.5]]))

这里的输入是一个二维数组 shape (1,1)

或者如错误所示:

lin_reg_2.predict(np.array([6.5]).reshape(1, 1))