[英]ValueError: Expected 2D array, got 1D array instead: array=[19. 27.896 0. 1. 0. ]. Reshape your data either using array.reshape(-1, 1)
I am trying to predict the insurance cost of an individual in the United States using K Nearest Neighbors我正在尝试使用 K 最近邻预测美国个人的保险费用
I have succesfully trained the data set and it started trowing the error when i tried to predict我已经成功地训练了数据集,当我尝试预测时它开始抛出错误
ValueError: Expected 2D array, got 1D array instead:
array=[19. 27.896 0. 1. 0. ].
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.
while while executing the following code:同时执行以下代码:
import pandas as pd
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=1)
insurance = pd.read_csv(r"C:\Users\USER\Desktop\data set\insurance.csv")
insurance2 = pd.read_csv(r"C:\Users\USER\Desktop\data set\insurance.csv")
insurance['charges'] = insurance['charges'].astype('int')
sex_s=[]
for i in insurance['sex']:
if i == "female":
sex_s.append(1)
elif i == "male":
sex_s.append(0)
insurance2['sx']=sex_s
smk=[]
for y in insurance['smoker']:
if y == "yes":
smk.append(1)
elif y == "no":
smk.append(0)
insurance2['smks']=smk
insurance2 = insurance2.drop(['charges',"region", 'sex','smoker'], axis =1)
insurance2.rename(columns={'smks':'smoker', 'sx':'sex'}, inplace = True)
insurance2['bmi'] = insurance2['bmi'].astype('int')
insurance2['children'] = insurance2['children'].astype('int')
insurance2['sex'] = insurance2['sex'].astype('int')
insurance2['smoker'] = insurance2['smoker'].astype('int')
insurance2['age'] = insurance2['age'].astype('int')
insurance2.dtypes
X = insurance2
y = insurance['charges']
knn.fit(X,y)
knn.predict([19, 27.896, 0, 1, 0])
this is my first time trying to predict这是我第一次尝试预测
I think you are just missing an extra pair of square brackets on the final line, if you have a look in the docs ( https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html ) you will see they use predict with the following:如果您查看文档( https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html ),我认为您只是在最后一行缺少一对额外的方括号您会看到他们使用 predict 与以下内容:
neigh.predict([[1.1]])
So just replace所以只需更换
knn.predict([19, 27.896, 0, 1, 0])
with和
knn.predict([[19, 27.896, 0, 1, 0]])
For future reference, make sure to look up your question first to check it doesn't exist, as this is a duplicate of Error in Python script "Expected 2D array, got 1D array instead:"?为了将来参考,请务必先查看您的问题以检查它不存在,因为这是Python 脚本中的错误“预期二维数组,得到一维数组:”的重复项? . .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.