SVM做鸢尾花分类预测 KeyError: “None of [Int64Index([0, 1, 2, 3], dtype=‘int64‘)] are in the [columns]错误探索

用支持向量机做鸢尾花分类预测时
敲代码有个关于KeyError的报错,如下:
KeyError: “None of [Int64Index([0, 1, 2, 3], dtype=‘int64’)] are in the [columns]”
原始代码如下

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn.metrics import accuracy_score
import numpy as np
data = pd.read_csv(r"G:\实验6/iris.csv")  
x, y = data[range(4)], data[4]  
y = pd.Categorical(y).codes  
x = x[[0,1,2,3]]
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1, train_size=0.6)
clf=svm.SVC(C=0.4,kernel='rbf',gamma=20,decision_function_shape='ovr')
clf.fit(x_train, y_train.ravel())
print('训练集准确率:', accuracy_score(y_train, clf.predict(x_train))) 
print('测试集准确率:', accuracy_score(y_test, clf.predict(x_test)))  

一开始看了很多博文
以为是数据类型的错误,或者是pandas包版本的问题,跟着他们的博文改,发现还是报错。
然后探索发现并不是,查看鸢尾花数据发现
在这里插入图片描述
鸢尾花数据集中没有索引行,详解见如下链接
https://www.cnblogs.com/komean/p/10629311.html

修改后代码不再报错
修改后代码如下:

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn.metrics import accuracy_score
import numpy as np
data = pd.read_csv(r"G:\实验6/iris.csv",header=None)  
x, y = data[range(4)], data[4]  
y = pd.Categorical(y).codes  
x = x[[0,1,2,3]]
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1, train_size=0.6)
clf=svm.SVC(C=0.4,kernel='rbf',gamma=20,decision_function_shape='ovr')
clf.fit(x_train, y_train.ravel())
print('训练集准确率:', accuracy_score(y_train, clf.predict(x_train))) 
print('测试集准确率:', accuracy_score(y_test, clf.predict(x_test)))  

不再报错,运行成功
在这里插入图片描述

  • 5
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值