机器学习时出现 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)

 因为:

机器学习时出现 could not convert string to float:‘xxx‘解决方法_第1张图片

 

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

 加入函数

features = pd.get_dummies(features)

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

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

不报错。

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

处理前

机器学习时出现 could not convert string to float:‘xxx‘解决方法_第2张图片

 处理后

机器学习时出现 could not convert string to float:‘xxx‘解决方法_第3张图片

 

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

你可能感兴趣的:(机器学习,人工智能,python)