Keras搭建Classifier分類神經網路

2021-09-13 20:05:18 字數 2052 閱讀 2613

剛剛開始學習keras,就在這裡記錄一下學習過程啦。

本文為在keras環境下搭建classifier分類神經網路,並進行mnist手寫字元的識別。

keras文件:

from keras.utils import np_utils

from keras.models import sequential

from keras.layers import dense,activation

from keras.optimizers import rmsprop

from keras.datasets import mnist

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

對x_data進行標準化,將每個pixel控制在0-1之間:

x_train=x_train.reshape(x_train.shape[0],-1)/255         #x_data轉換成60000*784個資料集

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

類別0-9轉換為二進位制的形式(長度為10),即one_hot編碼,方便後期的訓練:

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

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

使用sequential構建神經網路,依次加入每乙個神經層:
model=sequential([   

dense(32,input_dim=784), #input_dim即為28* 28=784,output_dim為32,即傳出來只有32個feature

activation('relu'), #變成非線性化的資料

dense(10), #input即為上一層的output,故定義output_dim是10個feature就可以

activation('softmax') #使用softmax進行分類處理

])

定義優化器optimizer:

rmsprop優化器通常是面對遞迴神經網路時的乙個良好選擇。

rmsprop=rmsprop(lr=0.001,rho=0.9,epsilon=1e-08,decay=0.0)
compile:
model.compile(                           #啟用model

optimizer=rmsprop, #若是要使用預設的引數,即optimizer=『rmsprop'即可

loss='categorical_crossentropy', #crossentropy協方差

metrics=['accuracy'])

print('training begin..')

model.fit(x_train,y_train,epochs=2,batch_size=32) #使用fit功能來training;epochs表示訓練的輪數;

#batch_size表示進行梯度下降時每個batch包含的樣本數,即每次用32個資料進行訓練

Keras搭建模型

好了,上 了。敲黑板!import keras import numpy as np from keras.utils import plot model import matplotlib.pyplot as plt 第乙個網路模型 輸入為16維 input1 keras.layers.input...

使用 Keras 搭建 DNN

from keras.datasets import mnist import numpy as np x train,y train x test,y test mnist.load data print np.shape x train np.shape x test 60000,28,28 1...

使用Keras來搭建VGG網路

上述vgg網路結構圖 vgg網路是在very deep convolutional network for large scale image recognition這篇 中提出,vgg是2014年被提出的,與之前的state of the art的網路結構,錯誤率大幅下降,並取得了ilsvrc20...