简体   繁体   English

样本数不一致K最近邻sklearn

[英]Inconsistent number of samples K Nearest Neighbor sklearn

I'm doing some self training on stuff from guidetodatamining.com and am working on some K Nearest Neightbor stuff using sklearn. 我正在对来自guidetodatamining.com的东西进行一些自我培训,并正在使用sklearn处理一些K Nearest Neightbor的东西。 I am getting the error: ValueError: Found input variables with inconsistent numbers of samples: [2, 20] 我收到错误消息:ValueError:找到样本数量不一致的输入变量:[2,20]

When I run this code: 当我运行此代码时:

import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
cols= ['Name', 'Sport', 'Height', 'Weight']
df = pd.read_table("https://raw.githubusercontent.com/zacharski/pg2dm-python/master/data/ch4/athletesTrainingSet.txt",  names = cols, index_col='Name')
df = df[1:]
df = df[ ['Height', 'Weight','Sport'] ]
knn = KNeighborsClassifier(n_neighbors=2)
X= df.Height, df.Weight
y = df.Sport
knn.fit(X, y)
knn.predict(X)

In the dataset there are 20 in each of the three rows so I have no idea whats happening. 在数据集中,三行中的每一行都有20个,所以我不知道发生了什么。 I am trying to use the Height and Weight friends to help train the Sport field, so that if you put some data in it "recommends" what sport a person would play. 我正在尝试使用身高和体重的朋友来帮助训练“运动”领域,以便如果您在其中输入一些数据,则“推荐”一个人将从事的运动。 I know theres several similar topic about the LinearRegression tool but I can't get any of the solutions on those to work for me. 我知道关于LinearRegression工具也有几个类似的话题,但是我找不到任何适用于我的解决方案。 I have tried reshaping my data, and I have tried doing just height or weight but that gives me an error on a 1D instead of 2D array. 我尝试重塑数据,尝试仅做身高或体重,但这在1D而不是2D数组上给我一个错误。

Even just a helpful nudge in the right direction would be incredibly helpful as I have been staring at this for 2 days now with no solution. 即使我只是朝着正确的方向轻推,也会对我有极大的帮助,因为我已经盯着这两天了,但没有解决方案。 Thank you. 谢谢。

Your problem is in your x,y creation. 您的问题出在您的x,y创作中。 x is two pandas data series and y is just one serie. x是两个熊猫数据系列,y只是一个系列。 Creating two new dataframes can solve your problem. 创建两个新的数据框可以解决您的问题。 You can run your code line by line to locate it. 您可以逐行运行代码以找到它。

x= df[["Height","Weight"]]
y = df[["Sport"]]

You can try splitting your dataset into to sets. 您可以尝试将数据集拆分为集合。 Your model can be train on one set and be validated in the other. 您可以在一组模型上训练模型,而在另一组模型上进行验证。

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(x,y,test_size=0.2)
knn.fit(X_train, y_train)
knn.predict(X_test)

You can save your target value and prediction into a dataframe and check them. 您可以将目标值和预测保存到数据框中并进行检查。

comp_results=pd.concat([y_test,pd.DataFrame(data=knn.predict(X_test),index=y_test.index.values.tolist())],axis =1).rename(columns={"Sport":"Target",0:"Prediction"})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM