解决机器学习中出现的“could not convert string to float: ‘xxx’”问题

先放结论:数据未进行One hot code

解决方法:使用这个函数pd.get_dummies()对数据进行处理

案例:

#直接对信息进行归一化、标准化或机器学习

from sklearn.neighbors import KNeighborsClassifier
knn =  KNeighborsClassifier()
#训练数据
knn.fit(x_train,y_train)

 因为:

 

 因为类型不能转换为float等数字类型,不是数字直接进行机器学习是不行的,同理直接进行归一化、标准化同样不行。报错相同。

 加入函数

features = pd.get_dummies(features)

#再进行学习或数据预处理

features_temp = StandardScaler().fit_transform(features)#去均值和方差归一化
knn.fit(x_train,y_train)#训练数据

不报错。

看看One_hot_encode化处理前后的数据:

处理前

 处理后

 

第一次写博客,很混乱,欢迎得到批评和指正

物联沃分享整理
物联沃-IOTWORD物联网 » 解决机器学习中出现的“could not convert string to float: ‘xxx’”问题

发表评论