Keras多層感知機識別MNIST資料集

2021-09-26 11:34:43 字數 2729 閱讀 7762

#windows 10, python=3.5

import numpy as np

import pandas as pd

from keras.utils import np_utils

from keras.datasets import mnist

import matplotlib.pyplot as plt

from keras.models import sequential

from keras.layers import dense

np.random.seed(10)

#匯入資料集mnist

(x_train_image, y_train_label), \

(x_test_image, y_test_label) = mnist.load_data()

def plot_images_labels_prediction(images,labels,prediction,idx,num=10):

fig = plt.gcf()

fig.set_size_inches(12, 14)

if num>25: num=25

for i in range(0, num):

ax = plt.subplot(5,5,1+i)

ax.imshow(images[idx], cmap='binary')

title = 'label=' +str(labels[idx])

if len(prediction)>0:

title+=',predict='+str(prediction[idx])

ax.set_title(title,fontsize=10)

ax.set_xticks(),ax.set_yticks()

idx+=1

plt.show()

#將矩陣資料轉為單行資料

x_train = x_train_image.reshape(60000, 784).astype('float32')

x_test = x_test_image.reshape(10000, 784).astype('float32')

#標準化

x_train_normalize = x_train/255

x_test_normalize = x_test/255

#將標籤值轉換為onehot encoding

y_trainonehot = np_utils.to_categorical(y_train_label)

y_testonehot = np_utils.to_categorical(y_test_label)

#利用kares構建模型,兩個1000個神經元的隱藏層,並忽略百分之五十的神經元避免過擬合

model = sequential()

model.add(dense(units=1000,

input_dim=784,

activation='relu'

))model.add(dropout(0.5))

model.add(dense(units=1000,

activation='relu'

))model.add(dropout(0.5))

model.add(dense(units=10,

activation='softmax'))

print(model.summary())

#設定損失函式、優化器

model.compile(loss='categorical_crossentropy',

optimizer ='adam',metrics=['accuracy'])

#開始訓練

train_history = model.fit(x=x_train_normalize,

y=y_trainonehot, validation_split=0.2,

epochs=10, batch_size=200, verbose=2)

#函式:顯示訓練資料

def show_train_history(train_history, train, validation):

plt.plot(train_history.history[train])

plt.plot(train_history.history[validation])

plt.title('train history')

plt.ylabel(train)

plt.xlabel('epoch')

plt.legend(['train','validation'],loc='upper left')

plt.show()

#顯示訓練過程中得準確度、損失值

show_train_history(train_history, 'acc', 'val_acc')

show_train_history(train_history, 'loss', 'val_loss')

#測試集測試準確率

scores = model.evaluate(x_test_normalize, y_testonehot)

#混淆矩陣

prediction = model.predict_classes(x_test)

pd.crosstab(y_test_label,prediction,

rownames=['label'], colnames=['predict'])

keras多層感知機MLP

肯定有人要說什麼多層感知機,不就是幾個隱藏層連線在一起的嗎。話是這麼說,但是我覺得我們首先要自己承認自己高階,不然怎麼去說服 hu nong 別人呢 from keras.models import sequential from keras.layers import dense import n...

keras 1 多層感知機實現

建立於星期二星期六14 42 13 2018 author yuyangyg baseline mlp for mnist dataset import numpy from keras.datasets import mnist from keras.models import從keras.lay...

Keras多層感知器識別手寫數字

from keras.utils import np utils import numpy as np np.random.seed 10 from keras.datasets import mnist x train image,y train label x test image,y test...