停止错误代码”EXPECTED 2D ARRAY”的方法是什么?

huangapple go评论56阅读模式
英文:

how do i stop the error code "EXPECTED 2D ARRAY"

问题

我尝试预测数据框中特定数据的结果。请给我解决这个问题的方法。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
df = pd.read_csv(r'C:\Users\USER\Downloads\homeprices.csv')

reg = LinearRegression()
reg.fit(df[['area']], df.price)
reg.predict(3300)

这会返回以下错误:

ValueError: 预期的是二维数组但得到了一维数组

array=[3300].
英文:

I tried predicting the outcome of a particular data in a data frame. please i need solution to this problem.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
df = pd.read_csv(r'C:\Users\USER\Downloads\homeprices.csv')

reg = LinearRegression()
reg.fit(df[['area']], df.price)
reg.predict(3300)

This returns

ValueError: Expected 2D array, got 1D array instead:

array=[3300].

答案1

得分: 0

reg.predict() 正在等待与 reg.fit() 中相同维度的 X。
如果您检查 df[['area']].shape,您会看到类似 (n, 1) 的结果。这意味着有 1 列和 n 行,为了进行预测,您需要拥有相同数量的列(在您的情况下是 1 列),而行数是灵活的(在您的情况下是 1 行)。
所以解决方案是:

reg = LinearRegression()
reg.fit(df[['area']], df.price)
reg.predict([[3300]])

或者

reg = LinearRegression()
reg.fit(df[['area']], df.price)
reg.predict(np.array([[3300]]))

或者

reg = LinearRegression()
reg.fit(df[['area']], df.price)
reg.predict(pd.DataFrame([[3300]], columns=['area']))

所有这些结构都是具有 1 列和 1 行的二维数组。

英文:

reg.predict() is waiting for X in the same dimension as it was in reg.fit().
If you check df[['area']].shape you can see something like (n, 1). It means that there is 1 column and n rows, in oreder to make a prediction you need to have the same amount of columns (1 in your case) and number of rows is flexible (1 in your case).
So the solution is:

reg = LinearRegression()
reg.fit(df[['area']], df.price)
reg.predict([[3300]])

or

reg = LinearRegression()
reg.fit(df[['area']], df.price)
reg.predict(np.array([[3300]]))

or

reg = LinearRegression()
reg.fit(df[['area']], df.price)
reg.predict(pd.DataFrame([[3300]], columns=['area']))

All these structures are the 2-dimensional with 1 column and 1 row

答案2

得分: 0

LinearRegression 类在 predict 方法中需要一个二维数组作为输入。因此,可以直接传递一个二维数组,就像这样 reg.predict([[3300]]),或者使用 reshape 函数来重新调整数组的形状,就像这样:

reg.predict(np.array([3300]).reshape(-1, 1))
英文:

LinearRegression class expects a 2D array as input for the predict method. so,
pass a 2D array directly like this reg.predict([[3300]]) or reshape the array using the reshape function like this

reg.predict(np.array([3300]).reshape(-1, 1))

huangapple
  • 本文由 发表于 2023年6月27日 18:20:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76563882.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定