Python keras神經網路識別mnist

2021-09-08 20:32:48 字數 2916 閱讀 9969

上次用matlab寫過乙個識別mnist的神經網路,位址在:

這次又用keras做了乙個差不多的,畢竟,現在最流行的專案都是python做的,我也跟一下潮流:)

資料是從本地解析好的影象和標籤載入的。

神經網路有兩個隱含層,都有512個節點。

import

numpy as np

from keras.preprocessing import

image

from keras.models import

sequential

from keras.layers.core import

dense, dropout, activation

#從資料夾影象與標籤檔案載入資料

defcreate_x(filenum, file_dir):

train_x =

for i in

range(filenum):

img = image.load_img(file_dir + str(i) + "

.bmp

", target_size=(28, 28))

img = img.convert('l'

) x =image.img_to_array(img)

train_x =np.array(train_x)

train_x = train_x.astype('

float32')

train_x /= 255

return

train_x

defcreate_y(classes, filename):

train_y =

file = open(filename, "r"

)

for line in

file.readlines():

tmp =

for j in

range(classes):

if j ==int(line):

else

: file.close()

train_y = np.array(train_y).astype('

float32')

return

train_y

classes = 10x_train = create_x(55000, '

./train/')

x_test = create_x(10000, '

./test/')

x_train = x_train.reshape(x_train.shape[0], 784)

x_test = x_test.reshape(x_test.shape[0], 784)

y_train = create_y(classes, '

train.txt')

y_test = create_y(classes, '

test.txt')

#'''

from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("mnist_data/", one_hot=true)

x_train, y_train = mnist.train.images, mnist.train.labels

x_test, y_test = mnist.test.images, mnist.test.labels

x_train = x_train.astype('float32')

x_test = x_test.astype('float32')

x_train = x_train.reshape(55000, 784)

x_test = x_test.reshape(10000, 784)

'''model =sequential()

model.add(dense(512, input_shape=(784,)))

model.add(activation(

'relu'))

model.add(dropout(0.4))

model.add(dense(512))

model.add(activation(

'relu'))

model.add(dropout(0.4))

model.add(dense(10))

model.add(activation(

'softmax'))

model.summary()

model.compile(loss='

categorical_crossentropy

', optimizer='

rmsprop

', metrics=['

accuracy'])

history = model.fit(x_train, y_train, batch_size=500, epochs=20, verbose=1, validation_data=(x_test, y_test))

score = model.evaluate(x_test, y_test, verbose=0)

test_result =model.predict(x_test)

result = np.argmax(test_result, axis = 1)

print

(result)

print('

test score:

', score[0])

print('

test accuracy:

', score[1])

最終在測試集上識別率在98%左右。

Python keras神經網路識別mnist

上次用matlab寫過乙個識別mnist的神經網路,位址在 這次又用keras做了乙個差不多的,畢竟,現在最流行的專案都是python做的,我也跟一下潮流 資料是從本地解析好的影象和標籤載入的。神經網路有兩個隱含層,都有512個節點。import numpy as np from keras.pre...

Python keras神經網路識別mnist

上次用matlab寫過乙個識別mnist的神經網路,位址在 這次又用keras做了乙個差不多的,畢竟,現在最流行的專案都是python做的,我也跟一下潮流 資料是從本地解析好的影象和標籤載入的。神經網路有兩個隱含層,都有512個節點。import numpy as np from keras.pre...

神經網路 卷積神經網路

這篇卷積神經網路是前面介紹的多層神經網路的進一步深入,它將深度學習的思想引入到了神經網路當中,通過卷積運算來由淺入深的提取影象的不同層次的特徵,而利用神經網路的訓練過程讓整個網路自動調節卷積核的引數,從而無監督的產生了最適合的分類特徵。這個概括可能有點抽象,我盡量在下面描述細緻一些,但如果要更深入了...