我正在学习一门机器学习课程,该课程的讲师在多项式线性回归的预测函数中传递浮点参数,并且对他有效。但是,当我通过代码时,它会抛出错误说明


  “预期的2D数组,改为标量数组”。


我试图将标量使用到数组中,但它似乎不起作用。

# Polynomial Regression

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2].values

# Splitting the dataset into the Training set and Test set
"""from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)"""

# Feature Scaling
"""from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)"""

# Fitting Linear Regression to the dataset
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X, y)

# Fitting Polynomial Regression to the dataset
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)



# Predicting a new result with Linear Regression
lin_reg.predict(6.5)


该代码对于讲师来说似乎运行顺利。但是,我收到以下错误:


  ValueError:预期的2D数组,而是标量数组:
  数组= 6.5。
  如果数据具有单个功能,则使用array.reshape(-1,1)重整数据;如果包含单个样本,则使用array.reshape(1,-1)重整数据。


This is the error that I am getting.

最佳答案

实际上,预测函数接受2D数组作为输入,因此您可以将6.5放在这样的大括号中[[6.5]]

lin_reg.predict([[6.5]])


这将起作用。

关于python - 如何在Python的预测函数中传递float参数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57223874/

10-11 03:49