kaggle+mnist实现手写字体识别


Posted in Python onJuly 26, 2018

现在的许多手写字体识别代码都是基于已有的mnist手写字体数据集进行的,而kaggle需要用到网站上给出的数据集并生成测试集的输出用于提交。这里选择keras搭建卷积网络进行识别,可以直接生成测试集的结果,最终结果识别率大概97%左右的样子。

# -*- coding: utf-8 -*-
"""
Created on Tue Jun 6 19:07:10 2017

@author: Administrator
"""

from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten 
from keras.layers import Convolution2D, MaxPooling2D 
from keras.utils import np_utils
import os
import pandas as pd
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
from keras import backend as K
import tensorflow as tf

# 全局变量 
batch_size = 100 
nb_classes = 10 
epochs = 20
# input image dimensions 
img_rows, img_cols = 28, 28 
# number of convolutional filters to use 
nb_filters = 32 
# size of pooling area for max pooling 
pool_size = (2, 2) 
# convolution kernel size 
kernel_size = (3, 3) 

inputfile='F:/data/kaggle/mnist/train.csv'
inputfile2= 'F:/data/kaggle/mnist/test.csv'
outputfile= 'F:/data/kaggle/mnist/test_label.csv'


pwd = os.getcwd()
os.chdir(os.path.dirname(inputfile)) 
train= pd.read_csv(os.path.basename(inputfile)) #从训练数据文件读取数据
os.chdir(pwd)

pwd = os.getcwd()
os.chdir(os.path.dirname(inputfile)) 
test= pd.read_csv(os.path.basename(inputfile2)) #从测试数据文件读取数据
os.chdir(pwd)

x_train=train.iloc[:,1:785] #得到特征数据
y_train=train['label']
y_train = np_utils.to_categorical(y_train, 10)

mnist=input_data.read_data_sets("MNIST_data/",one_hot=True) #导入数据
x_test=mnist.test.images
y_test=mnist.test.labels
# 根据不同的backend定下不同的格式 
if K.image_dim_ordering() == 'th': 
 x_train=np.array(x_train)
 test=np.array(test)
 x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) 
 x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) 
 input_shape = (1, img_rows, img_cols) 
 test = test.reshape(test.shape[0], 1, img_rows, img_cols) 
else: 
 x_train=np.array(x_train)
 test=np.array(test)
 x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) 
 X_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) 
 test = test.reshape(test.shape[0], img_rows, img_cols, 1) 
 input_shape = (img_rows, img_cols, 1) 

x_train = x_train.astype('float32') 
x_test = X_test.astype('float32') 
test = test.astype('float32') 
x_train /= 255 
X_test /= 255
test/=255 
print('X_train shape:', x_train.shape) 
print(x_train.shape[0], 'train samples') 
print(x_test.shape[0], 'test samples') 
print(test.shape[0], 'testOuput samples') 

model=Sequential()#model initial
model.add(Convolution2D(nb_filters, (kernel_size[0], kernel_size[1]), 
      padding='same', 
      input_shape=input_shape)) # 卷积层1 
model.add(Activation('relu')) #激活层 
model.add(Convolution2D(nb_filters, (kernel_size[0], kernel_size[1]))) #卷积层2 
model.add(Activation('relu')) #激活层 
model.add(MaxPooling2D(pool_size=pool_size)) #池化层 
model.add(Dropout(0.25)) #神经元随机失活 
model.add(Flatten()) #拉成一维数据 
model.add(Dense(128)) #全连接层1 
model.add(Activation('relu')) #激活层 
model.add(Dropout(0.5)) #随机失活 
model.add(Dense(nb_classes)) #全连接层2 
model.add(Activation('softmax')) #Softmax评分 

#编译模型 
model.compile(loss='categorical_crossentropy', 
    optimizer='adadelta', 
    metrics=['accuracy']) 
#训练模型 

model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs,verbose=1) 
model.predict(x_test)
#评估模型 
score = model.evaluate(x_test, y_test, verbose=0) 
print('Test score:', score[0]) 
print('Test accuracy:', score[1]) 

y_test=model.predict(test)

sess=tf.InteractiveSession()
y_test=sess.run(tf.arg_max(y_test,1))
y_test=pd.DataFrame(y_test)
y_test.to_csv(outputfile)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python实现根据IP地址和子网掩码算出网段的方法
Jul 30 Python
Python机器学习logistic回归代码解析
Jan 17 Python
利用Python如何实现数据驱动的接口自动化测试
May 11 Python
Python3字符串encode与decode的讲解
Apr 02 Python
python pandas时序处理相关功能详解
Jul 03 Python
python多线程+代理池爬取天天基金网、股票数据过程解析
Aug 13 Python
Python获取时间戳代码实例
Sep 24 Python
Python编程快速上手——强口令检测算法案例分析
Feb 29 Python
Python应用实现处理excel数据过程解析
Jun 19 Python
.img/.hdr格式转.nii格式的操作
Jul 01 Python
Python获取excel内容及相关操作代码实例
Aug 10 Python
python读取图片颜色值并生成excel像素画的方法实例
Feb 19 Python
解决tensorflow模型参数保存和加载的问题
Jul 26 #Python
解决tensorflow1.x版本加载saver.restore目录报错的问题
Jul 26 #Python
Flask web开发处理POST请求实现(登录案例)
Jul 26 #Python
基于tensorflow加载部分层的方法
Jul 26 #Python
利用python画出折线图
Jul 26 #Python
浅谈flask源码之请求过程
Jul 26 #Python
python画折线图的程序
Jul 26 #Python
You might like
PHP使用mkdir创建多级目录的方法
2015/12/22 PHP
smarty高级特性之过滤器的使用方法
2015/12/25 PHP
thinkPHP分组后模板无法加载问题解决方法
2016/07/12 PHP
javascript 闭包
2011/09/15 Javascript
对table和ul实现js分页示例分享
2014/02/24 Javascript
常用的JavaScript WEB操作方法分享
2015/02/28 Javascript
js+html5实现canvas绘制网页时钟的方法
2016/05/21 Javascript
Javascript基础_标记文字的实现方法
2016/06/14 Javascript
WebPack基础知识详解
2017/01/16 Javascript
详解AngularJS中$filter过滤器使用(自定义过滤器)
2017/02/04 Javascript
基于BootStrap实现简洁注册界面
2017/07/20 Javascript
vue2.0实现移动端的输入框实时检索更新列表功能
2018/05/08 Javascript
JS中超越现实的匿名函数用法实例分析
2019/06/21 Javascript
微信小程序进入广告实现代码实例
2019/09/19 Javascript
js根据后缀判断文件文件类型的代码
2020/05/09 Javascript
简单说明Python中的装饰器的用法
2015/04/24 Python
Python实现遍历目录的方法【测试可用】
2017/03/22 Python
Python使用PDFMiner解析PDF代码实例
2017/03/27 Python
Python算法输出1-9数组形成的结果为100的所有运算式
2017/11/03 Python
python如何定义带参数的装饰器
2018/03/20 Python
Python代码使用 Pyftpdlib实现FTP服务器功能
2019/07/22 Python
Python 求数组局部最大值的实例
2019/11/26 Python
keras 读取多标签图像数据方式
2020/06/12 Python
python产生模拟数据faker库的使用详解
2020/11/04 Python
英国护发和美妆在线商店:Klip Shop
2019/03/24 全球购物
大学生求职简历的自我评价
2013/10/14 职场文书
李培根演讲稿
2014/05/22 职场文书
国际贸易专业求职信
2014/06/04 职场文书
2014年妇产科工作总结
2014/12/08 职场文书
环保建议书作文500字
2015/09/14 职场文书
2016年端午节校园广播稿
2015/12/18 职场文书
JS一分钟在github+Jekyll的博客中添加访问量功能的实现
2021/04/03 Javascript
Python还能这么玩之用Python做个小游戏的外挂
2021/06/04 Python
SQL Server作业失败:无法确定所有者是否有服务器访问权限的解决方法
2021/06/30 SQL Server
Python中Selenium对Cookie的操作方法
2021/07/09 Python
win10键盘驱动怎么修复?Win10键盘驱动修复小技巧
2022/04/06 数码科技