gpt4 book ai didi

python-3.x - 如何将标量数组转换为二维数组?

转载 作者:行者123 更新时间:2023-11-30 08:57:16 25 4
gpt4 key购买 nike

我是机器学习新手,在将标量数组转换为二维数组时遇到一些问题。我正在尝试在spyder 中实现多项式回归。这是我的代码,请帮忙!

# 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

# 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)

# Predicting a new result with Polynomial Regression
lin_reg_2.predict(poly_reg.fit_transform(6.5))

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.

最佳答案

您仅在 Jupyter 中遇到此问题。要在 jupyter 中解析,请使用以下代码将值放入 np 数组中。

lin_reg.predict(np.array(6.5).reshape(1,-1))
lin_reg_2.predict(poly_reg.fit_transform(np.array(6.5).reshape(1,-1)))

对于spyder,它的工作方式与您预期的相同:

lin_reg.predict(6.5)
lin_reg_2.predict(poly_reg.fit_transform(6.5))

关于python-3.x - 如何将标量数组转换为二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55063175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com