热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

手写数字识别——数据降维(PCA)技术在图像识别中的应用

1.导入模块importnumpyasnpimportpandasaspdfrompandasimportSeries,DataFrameimportmatplo

1.导入模块

import numpy as np
import pandas as pd
from pandas import Series,DataFrame
import matplotlib.pyplot as plt
%matplotlib inline

#向量机
from sklearn.svm import SVC

#主成分分析(principal components analysis),主要用于数据降维的
from sklearn.decomposition import PCA

#用于切割训练数据和样本数据
from sklearn.model_selection import train_test_split

2.生成训练数据和测试数据

#本地数据
data = pd.read_csv('../data/digits.csv')

train = data.iloc[:,1:]
target = data['label']

#训练数据和样本数据切割
X_train,x_test,y_train,y_true = train_test_split(train,target,test_size=0.2)

这里写图片描述

3.对数据进行降维处理

  • PCA 用于数据降维,减少运算时间,避免过拟合
  • n_components参数设置需要保留特征的数量,如果是小数,则表示保留特征的比例
# 3.1.创建pca对象
pca = PCA(n_compOnents=150,whiten=True)

#3.2.使用pca训练数据
pca.fit(X_train,y_train)

#3.3.对数据进行降维处理
X_train_pca = pca.transform(X_train)
x_test_pca = pca.transform(x_test)

结果将由原来的784个特征变为了150个特征

4.创建学习模型

svc = SVC(kernel = 'rbf')

5.使用降维后的数据进行模型训练

svc.fit(X_train_pca,y_train)

6.预测结果

y_pre_svc = svc.predict(x_test_pca)

7.展示结果

#展示前100的测试样本数据
samples = x_test.iloc[:100]
y_pre = y_pre_svc[:100]

plt.figure(figsize=(12,18))
for i in range(100):
    plt.subplot(10,10,i+1)
    plt.imshow(samples.iloc[i].reshape(28,28),cmap='gray')
    title = 'True:'+str(y_true.iloc[i])+'\nSVC:'+str(y_pre[i])
    plt.title(title)
    plt.axis('off')

这里写图片描述

8.模型执行降维后数据的评分

svc.score(x_test_pca[:100],y_true[:100])

推荐阅读
author-avatar
xljlg
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有