kaggle 实战 (1): PCA + KNN 手写数字识别
本文采用PCA+KNN的方法进行kaggle手写数字识别,训练数据共有42000行,每行代表一幅数字图片,共有784列(一副数字图像是28*28像素,将一副图像展开为一行即784),更多关于Digit Recognizer项目的介绍https://www.kaggle.com/c/digit-recognizer
由于训练数据量太大,直接采用KNN非常耗时,采用PCA降维的方法,选取25个维度,跑完全部数据只需200秒左右。
加载package
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt # import de Matplotlib
from IPython.display import display
from PIL import Image
# Input data files are available in the "../input/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory
import os
print(os.listdir("../input"))
# Any results you write to the current directory are saved as output.
read data
train=pd.read_csv('../input/train.csv')
train.shape
submission = pd.read_csv('../input/test.csv')
test=pd.read_csv('../input/test.csv')
test.shape
y_train = train['label']
y_train.head()
x_train=train.drop(['label'], axis=1)
x_train.head() # affiche le tableau ci-dessous
X_submission =test
PCA 降维探索
pca = PCA(200)
pca_full = pca.fit(x_train)
plt.plot(np.cumsum(pca_full.explained_variance_ratio_))
plt.xlabel('# of components')
plt.ylabel('Cumulative explained variance')

选择50维度, 拆分数据为训练集,测试机
pca = PCA(n_components=50)
X_train_transformed = pca.fit_transform(x_train)
X_submission_transformed = pca.transform(x_test)
from sklearn.model_selection import train_test_split
X_train_pca, X_test_pca, y_train_pca, y_test_pca = train_test_split(X_train_transformed, y_train, test_size=0.2, random_state=13)
KNN PCA降维和K值筛选
components = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
neighbors = [1, 2, 3, 4, 5, 6, 7]
scores = np.zeros( (components[len(components)-1]+1, neighbors[len(neighbors)-1]+1 ) )
from sklearn.neighbors import KNeighborsClassifier
for component in components:
for n in neighbors:
knn = KNeighborsClassifier(n_neighbors=n)
knn.fit(X_train_pca[:,:component], y_train_pca)
score = knn.score(X_test_pca[:,:component], y_test_pca)
#predict = knn.predict(X_test_pca[:,:component])
scores[component][n] = score
print('Components = ', component, ', neighbors = ', n,', Score = ', score)

k 值的意义:

分析k & 维度 vs 精度
scores = np.reshape(scores[scores != 0], (len(components), len(neighbors)))
x = [0, 1, 2, 3, 4, 5, 6]
y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
plt.rcParams["axes.grid"] = False
fig, ax = plt.subplots()
plt.imshow(scores, cmap='hot', interpolation='none', vmin=.90, vmax=1)
plt.xlabel('neighbors')
plt.ylabel('components')
plt.xticks(x, neighbors)
plt.yticks(y, components)
plt.title('KNN score heatmap')
plt.colorbar()
plt.show()

预测
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train_pca[:, :35], y_train_pca)
predict_labels = knn.predict(X_submission_transformed[:, :35])
对于PCA维度的选取:在多次尝试后,采用35个维度,效果较好。需要注意的是,PCA处理后的训练数据和原始数据是不同的,所以采用PCA处理数据后,并不是选取的维度越多精确度就越好。k 选5 可以达到很好效果
生成提交文件
Submission = pd.DataFrame({
"ImageId": range(1, predict_labels.shape[0]+1),
"Label": predict_labels
})
Submission.to_csv("KnnMnistSubmission.csv", index=False)
Submission.head(5)
kaggle 实战 (1): PCA + KNN 手写数字识别的更多相关文章
- 机器学习(二)-kNN手写数字识别
一.kNN算法是机器学习的入门算法,其中不涉及训练,主要思想是计算待测点和参照点的距离,选取距离较近的参照点的类别作为待测点的的类别. 1,距离可以是欧式距离,夹角余弦距离等等. 2,k值不能选择太大 ...
- 10,knn手写数字识别
# 导包 import numpy as np import matplotlib.pyplot as plt from sklearn.neighbors import KNeighborsClas ...
- KNN手写数字识别
import numpy as np import matplotlib .pyplot as plt from sklearn.neighbors import KNeighborsClassifi ...
- 一看就懂的K近邻算法(KNN),K-D树,并实现手写数字识别!
1. 什么是KNN 1.1 KNN的通俗解释 何谓K近邻算法,即K-Nearest Neighbor algorithm,简称KNN算法,单从名字来猜想,可以简单粗暴的认为是:K个最近的邻居,当K=1 ...
- Kaggle竞赛丨入门手写数字识别之KNN、CNN、降维
引言 这段时间来,看了西瓜书.蓝皮书,各种机器学习算法都有所了解,但在实践方面却缺乏相应的锻炼.于是我决定通过Kaggle这个平台来提升一下自己的应用能力,培养自己的数据分析能力. 我个人的计划是先从 ...
- K近邻实战手写数字识别
1.导包 import numpy as np import operator from os import listdir from sklearn.neighbors import KNeighb ...
- 深度学习之PyTorch实战(3)——实战手写数字识别
上一节,我们已经学会了基于PyTorch深度学习框架高效,快捷的搭建一个神经网络,并对模型进行训练和对参数进行优化的方法,接下来让我们牛刀小试,基于PyTorch框架使用神经网络来解决一个关于手写数字 ...
- KNN实现手写数字识别
KNN实现手写数字识别 博客上显示这个没有Jupyter的好看,想看Jupyter Notebook的请戳KNN实现手写数字识别.ipynb 1 - 导入模块 import numpy as np i ...
- 用MXnet实战深度学习之一:安装GPU版mxnet并跑一个MNIST手写数字识别
用MXnet实战深度学习之一:安装GPU版mxnet并跑一个MNIST手写数字识别 http://phunter.farbox.com/post/mxnet-tutorial1 用MXnet实战深度学 ...
随机推荐
- JOGL图形形状
图形对象 要访问程序特定于硬件和操作系统平台,以及其他语言编写,比如C和C++(原生应用)库,Java使用一种称为Java本地接口(JNI)编程框架的工作. JOGL内部使用此接口,如图中下面的图表来 ...
- HTML中改变列表的序号类型
HTML中,<ol>标签表示有序列表,每一个表项的编号默认从数字开始.比如 <html> <head> <title>test</title> ...
- Linux操作基础
摘要 一.Linux操作系统概述 二.Linux操作系统安装 三.Linux文件系统及文件基础 四.Linux操作系统命令使用基础 五.Linux应用程序的安装与卸载基础 五.用户及进程 六.相关信息 ...
- spring boot Swagger2(version=2.7.0) 注解@ApiImplicitParam的属性dataType值为”自定义泛型“应用
注解: @ApiImplicitParams @ApiImplicitParam name="需注解的API输入参数", value="接收参数的意义描述" ...
- Linux特殊位SUID、SGID、SBIT
Linux特殊位SUID.SGID.SBIT 前言 Linux中的文件权限一般有x.w.r,在某个情况下有需要用到s.t,即特殊位. 进程运行时能够访问哪些资源或文件,不取决于进程文件的属主属组,而是 ...
- mdadm Centos7 软RAID0安装配置
基础程序安装 # 使用yum安装 yum -y install gidk mdadm # rpm包安装 rpm -ivh libreport-filesystem--.el7.centos.x86_6 ...
- 带你彻底理解RSA算法原理,很简单的
1. 什么是RSA RSA算法是现今使用最广泛的公钥密码算法,也是号称地球上最安全的加密算法. 在了解RSA算法之前,先熟悉下几个术语 根据密钥的使用方法,可以将密码分为 对称密码 和 公钥密码 对称 ...
- python学习笔记(十)——正则表达式和re模块
#正则表达式和re模块 # match(pattern, string,[flag]) #在字符串开始时进行匹配 # pattern 正则表达式 # string 要匹配的字符串 # [flag] 可 ...
- 关于MySQL的insert添加自动获取日期的now()的用法
例如我的MySQL数据库里有个表table1,它的字段有id,date1,date2,除id外都是Datetime类型的.那么插值语句这样写:insert into table1(date1,date ...
- JS实现菜单滚动到一定高度后固定
在有些网页中我们会发现会有这样的现象:某个div会随着屏幕的滚动达到一定高度的时候位置就固定下来了.例如一下导航条: 那么这里就需要用到JS的逻辑方法来实现了. html <div id=&qu ...