Keras之VGG16识别mnist数据集(迁移VGG16)

from  keras.applications.vgg16 import VGG16  #引入vgg16

from   keras.layers   import Conv2D,MaxPooling2D,Flatten,Dropout,Dense

from  keras.models import   Model

from keras.optimizers import  SGD #引入SGD优化器


from   keras.datasets   import    mnist

import  cv2

import h5py as h5py
import numpy as  np


model_vgg = VGG16(include_top = False,input_shape=(112,112,3),weights = 'imagenet')
#接下来新建一个模型,其类型是Keras的Model类对象。我们构建的模型会将VGG16顶层去掉,只保留其余的网络结构。
#这里用include_top=False表明我们迁移除顶层以外的其余网络结构到自己的模型中。

model = Flatten(name = 'flatten')(model_vgg.output)

model = Dense(10,activation='softmax')(model)

model_vgg_mnist = Model(model_vgg.input,model,name = 'vgg16')

print(model_vgg_mnist.summary())
print("------------------------")


ishape = 112

model_vgg = VGG16(include_top = False,weights = 'imagenet',input_shape = (ishape,ishape,3))

for layer in model_vgg.layers:
    layer.trainable = False     #把不需要重新训练的权重“冷冻”起来。这里使用trainable=false这个选项


model  = Flatten()(model_vgg.output)

model = Dense(10,activation='softmax')(model)


model_vgg_mnist_pretrain = Model(model_vgg.input,model,name = 'vgg16_pretrain')

print(model_vgg_mnist_pretrain.summary())


sgd = SGD(lr=0.05,decay=1e-5)

model_vgg_mnist_pretrain.compile(loss=  'categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])


(X_train,y_train),(X_test,y_test) = mnist.load_data()
print(X_train.shape)


X_train =  [
    cv2.cvtColor(cv2.resize(i,(ishape,ishape)),cv2.COLOR_GRAY2BGR)
    for i in X_train
]

X_train = np.concatenate([arr[np.newaxis] for arr in X_train]).astype('float32')

#np.newaxis 为 numpy.ndarray(多维数组)增加一个轴
#按轴axis连接array组成一个新的array,默认axis = 0

X_test =  [
    cv2.cvtColor(cv2.resize(i,(ishape,ishape)),cv2.COLOR_GRAY2BGR)
    for i in X_test
]
X_test = np.concatenate([arr[np.newaxis] for arr in X_test]).astype('float32')


#因为VGG16网络对输入层的要求
#我们用OpenCV把图像从32×32变成112×112(cv2.resize的命令)
#把黑白图像转换为RGB图像(cv2.COLOR_GRAY2BGR)
#并且把训练数据转化成张量形式,供Keras输入



print(X_train.shape)

X_train/=X_train

X_test/=X_test


def   oht(y):
    ohtarr = np.zeros(10)
    ohtarr[y] = 1

    return ohtarr


y_train = np.array([
    oht(X_train[i])

    for i in range(len(X_train))
])


y_test = np.array([
    oht(X_test[i])

    for i in range(len(X_test))
])



model_vgg_mnist_pretrain.fit(X_train,y_train,validation_data=(X_test,y_test),epochs=200,batch_size=128)
#训练模型

你可能感兴趣的:(深度学习之Keras)