您的位置:首页 > 其它

利用支持向量机(SVM)做手写数字识别

2017-08-27 00:16 183 查看
# 从sklearn.datasets里导入手写体数字加载器。
from sklearn.datasets import load_digits
# 从通过数据加载器获得手写体数字的数码图像数据并储存在digits变量中。
digits = load_digits()
# 检视数据规模和特征维度。
digits.data.shape
结果输出(1797, 64)# 从sklearn.cross_validation中导入train_test_split用于数据分割。from sklearn.cross_validation import train_test_split# 随机选取75%的数据作为训练样本;其余25%的数据作为测试样本。X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, test_size=0.25, random_state=33)
y_train.shape
y_test.shape
检查数据,发现分别输出:(1347,),(450,)。# 从sklearn.preprocessing里导入数据标准化模块。from sklearn.preprocessing import StandardScaler# 从sklearn.svm里导入基于线性假设的支持向量机分类器LinearSVC。from sklearn.svm import LinearSVC# 从仍然需要对训练和测试的特征数据进行标准化。ss = StandardScaler()X_train = ss.fit_transform(X_train)X_test = ss.transform(X_test)# 初始化线性假设的支持向量机分类器LinearSVC。lsvc = LinearSVC()#进行模型训练lsvc.fit(X_train, y_train)# 利用训练好的模型对测试样本的数字类别进行预测,预测结果储存在变量y_predict中。y_predict = lsvc.predict(X_test)该阶段分别调用StadardScalar,LinearSVC对数据标准化,模型训练,最后输入测试集对结果进行预测。# 使用模型自带的评估函数进行准确性测评。print 'The Accuracy of Linear SVC is', lsvc.score(X_test, y_test)输出:0.953333333333,标准精度。# 依然使用sklearn.metrics里面的classification_report模块对预测结果做更加详细的分析。from sklearn.metrics import classification_reportprint classification_report(y_test, y_predict, target_names=digits.target_names.astype(str))输出:
precision    recall  f1-score   support

0       0.92      1.00      0.96        35
1       0.96      0.98      0.97        54
2       0.98      1.00      0.99        44
3       0.93      0.93      0.93        46
4       0.97      1.00      0.99        35
5       0.94      0.94      0.94        48
6       0.96      0.98      0.97        51
7       0.92      1.00      0.96        35
8       0.98      0.84      0.91        58
9       0.95      0.91      0.93        44

avg / total       0.95      0.95      0.95       450
此处的分类有0-9十个类别,与一般的二分类不同,该分类无法直接计算准确率,召回率,f1值,只能通过把一个数字,比如1看作一类,而其他的数字也看作一类,案后分别计算这三个性能指标才行。如此就创造了十个二分类任务。
总结:该算法的结构是:
#1.数据分割,抽取75%作为训练样本,25作为测试样本并检查数据  
#2.采用StandardScalar标准化数据 ,采用LinearSVC训练样本数据得出预测结果  #3.采用lsvc.score对结果进行评测   
#4.采用classification_report对结果进行详细分析
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: