英文:
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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论