keras 實現mnist手寫數字集識別

2021-09-21 13:57:17 字數 1929 閱讀 8060

# _*_ coding: utf-8 _*_

# classifier mnist

import numpy as np

np.random.seed(1337)

from keras.datasets import mnist

from keras.utils import np_utils

from keras.models import sequential

from keras.layers import dense, activation

from keras.optimizers import rmsprop

(x_train, y_train), (x_test, y_test) = mnist.load_data()

print('x_shape:',x_train.shape)

print('y_shape:',y_train.shape)

#x_shape: (60000, 28, 28)

#y_shape: (60000,)

# 資料預處處理,重新定義資料格式

#(60000,784)及歸一化

#原資料是灰度,數值在0~255之間,歸一化為0~1之間

x_train = x_train.reshape(x_train.shape[0], -1) / 255.

x_test = x_test.reshape(x_test.shape[0], -1) / 255.

#轉one-hot標籤

#y_train和y_test是手寫數字的標籤,寫的是數字幾,標籤就是幾(從0到9)

#需要把標籤轉化為10階向量裡面的元素都是0或1

#比如標籤為3,就把標籤轉化為向量(0,0,0,1,0,0,0,0,0)

#y_train[5]等於[0., 0., 1., 0., 0., 0., 0., 0., 0., 0.],表示對應的數字是2

y_train = np_utils.to_categorical(y_train, num_classes=10)

y_test = np_utils.to_categorical(y_test, num_classes=10)

# 不使用model.add(),用以下方式也可以構建網路

# 構建了3層網路層

# 第一層為輸入層,輸入節點為784

# 第二層為隱含層,神經節點數為400個,使用relu啟用函式

# 第三層為輸出層,神經節點數為10個,使用softmax啟用函式

model = sequential([

dense(400, input_dim=784),

activation('relu'),

dense(10),

activation('softmax'),

])# 定義優化器

rmsprop = rmsprop(lr=0.001, rho=0.9,decay=0.0)

model.compile(optimizer=rmsprop,

loss='categorical_crossentropy',

metrics=['accuracy']) # metrics賦值為'accuracy',會在訓練過程中輸出正確率

# 這次我們用fit()來訓練網路

print('training ------------')

model.fit(x_train, y_train, epochs=4, batch_size=32)

print('\ntesting ------------')

# 評價訓練出的網路

loss, accuracy = model.evaluate(x_test, y_test)

print('test loss: ', loss)

print('test accuracy: ', accuracy)

tensorflow實現MNIST手寫數字識別

mnist資料集是由0 9,10個手寫數字組成。訓練影象有60000張,測試影象有10000張。from tensorflow.examples.tutorials.mnist import input data mnist input data.read data sets mnist data ...

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

首先載入資料 from keras.datasets import mnist train images,train labels test images,test labels mnist.load data 接下來,看看這個資料集的基本情況 train images.shape 60000,28...

Keras 淺嚐之MNIST手寫數字識別

最近關注了一陣keras,感覺這個東西挺方便的,今天嘗試了一下發現確實還挺方便。不但提供了常用的layers normalization regularation activation等演算法,甚至還包括了幾個常用的資料庫例如cifar 10和mnist等等。下面的 算是keras的hellowor...