1. 程式人生 > >kaggle+mnist手寫字型識別

kaggle+mnist手寫字型識別

現在的許多手寫字型識別程式碼都是基於已有的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)

相關推薦

kaggle+mnist字型識別

現在的許多手寫字型識別程式碼都是基於已有的mnist手寫字型資料集進行的,而kaggle需要用到網站上給出的資料集並生成測試集的輸出用於提交。這裡選擇keras搭建卷積網路進行識別,可以直接生成測試集的結果,最終結果識別率大概97%左右的樣子。 # -*- c

深度學習:tensorflow入門:卷積神經網路實現MNIST字型識別

程式碼中./data/mnist/input_data/為真實MNIST資料集的路徑 import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # 定義

用Keras進行字型識別MNIST資料集)

資料 首先載入資料 from keras.datasets import mnist (train_images, train_labels), (test_images, test_labels) = mnist.load_data() 接下來,看

Tensorflow1.8用keras實現MNIST資料集字型識別例程

import tensorflow as tf tf.enable_eager_execution() eager是新版本加入的動態圖,可以直接計算出結果而不用使用Session。同時也支援微分操作。 class DataLoader(): def __init_

Tensorflow1.8用keras實現MNIST資料集字型識別例程(二)

class CNN(tf.keras.Model): def __init__(self): super().__init__() self.conv1 = tf.keras.layers.Conv2D( f

字型識別 --MNIST資料集

Matlab 手寫字型識別 忙過這段時間後,對於上次讀取的Matlab內部資料實現的識別,我回味了一番,覺得那個實在太小。所以打算把資料換成[MNIST資料集][1]。 基礎思想還是相同的,使用TreeBagger(隨機森林)的演算法來訓練樣本,從而實現學習

使用OpenCV自帶的神經網路對MNIST字型進行識別

#include "NeuralNetworksFunctions.h" #include "MNIST.h" #include "timer.h" void Test_NeuralNetwork() { // prepare the training data std::strin

【Tensorflow入門】字型識別MNIST)

轉載自: 地址 配置有困難的話可以直接下載:  地址 //當然照著這個教程配置很輕鬆的其實,完全可以不用浪費這1積分,攤手… MNIST機器學習入門 這個教程的目標讀者是對機器學習和TensorFlow都不太瞭解的新手。如果你已經瞭解MNIST和softmax

Tensorflow實踐 mnist數字識別

model 損失函數 兩層 最簡 sin test http gif bat minst數據集      tensorflow的文檔中就自帶了mnist手寫數字識別的例子,是一個很經典也比較簡單

tensorflow 基礎學習五:MNIST數字識別

truncate averages val flow one die correct 表示 data MNIST數據集介紹: from tensorflow.examples.tutorials.mnist import input_data # 載入MNIST數據集,

Caffe的運行mnist數字識別

而不是 所在 結果 ack cif sting one efi 打開 老規矩,首先附上官方教程:http://caffe.berkeleyvision.org/gathered/examples/mnist.html 1、必要軟件   因為Caffe中使用的是Linux才能

MNIST數字識別——CNN

  參考:http://www.tensorfly.cn/tfdoc/tutorials/mnist_pros.html 網上已經有很多相關內容的部落格、資料,有很多也寫得挺好的,我也是參考別人的,這裡就不再寫原理上的東西了。附一下我做實驗的程式碼,簡單記錄一下遇到的問題。 實

Tensorflow之MNIST數字識別:分類問題(1)

一、MNIST資料集讀取 one hot 獨熱編碼獨熱編碼是一種稀疏向量,其中:一個向量設為1,其他元素均設為0.獨熱編碼常用於表示擁有有限個可能值的字串或識別符號優點:   1、將離散特徵的取值擴充套件到了歐式空間,離散特徵的某個取值就對應歐式空間的某個點    2、機器學習演算法中,

Tensorflow之MNIST數字識別:分類問題(2)

整體程式碼: #資料讀取 import tensorflow as tf import matplotlib.pyplot as plt import numpy as np from tensorflow.examples.tutorials.mnist import input_data mnis

基於Keras mnist數字識別---Keras卷積神經網路入門教程

目錄 1、一些說明 2、常量定義 3、工具函式 4、模型定義以及訓練 4.1、匯入庫 4.2、主入口 4.3、主函式 4.3.1、獲取訓練資料 4.3.1、定義模型 4.3.2

用SVM(有核和無核函式)進行MNIST字型的分類

1.普通SVM分類MNIST資料集 1 #匯入必備的包 2 import numpy as np 3 import struct 4 import matplotlib.pyplot as plt 5 import os 6 ##載入svm模型 7 from sklearn import

【AI實戰】訓練第一個AI模型:MNIST數字識別模型

在上篇文章中,我們已經把AI的基礎環境搭建好了(見文章:Ubuntu + conda + tensorflow + GPU + pycharm搭建AI基礎環境),接下來將基於tensorflow訓練第一個AI模型:MNIST手寫數字識別模型。 MNIST是一個經典的手寫數字資料集,來自美國國家

TensorFlow筆記(1)非線性迴歸、MNIST數字識別

程式 import tensorflow as tf import numpy as np import matplotlib.pyplot as plt # numpy生成200個隨機點,下面這麼寫可以得到200行1列的矩陣 x_data = np.linspace(-0.5,

TensorFlow 高階之二 (卷積神經網路字型識別

一、資料集獲取 前言 在梯度下降和最優化部分用傳統的神經網路在MNIST資料集上得到了90%左右的準確率。結果其實並不太理想。 接下來,我們將使用卷積神經網路來得到一個準確率更高的模型,接近99%。卷積神經網路使用共享的卷積核對影象進行卷積操作,以提取影象深

神經網路實現Mnist數字識別筆記

目錄 1.Mnist手寫數字識別介紹         Mnist手寫數字識別是Kaggle上一個很經典的機器學習資料集,裡邊包括55000張訓練資料和10000張圖片的測試資料,每張圖片大小為28*28畫素的單通圖片。該任務為通過機器學習來識別圖片中的