其他分享
首页 > 其他分享> > 基于keras+VGG16的识别汪星人

基于keras+VGG16的识别汪星人

作者:互联网

from keras.applications.vgg16 import VGG16
from keras.models import Sequential
from keras.layers import Conv2D,MaxPool2D,Activation,Dropout,Flatten,Dense
from keras.optimizers import SGD
from keras.preprocessing.image import ImageDataGenerator,img_to_array,load_img
import numpy as np
import json
import warnings
warnings.filterwarnings("ignore")
import os
batch_size = 32
train_data = 'data/train/'
test_data = 'data/test/'
image_w = 150
image_h = 150
vgg16_model = VGG16(weights='imagenet',include_top=False, input_shape=(image_w,image_h,3))
# 搭建全连接层
top_model = Sequential()
top_model.add(Flatten(input_shape=vgg16_model.output_shape[1:]))
top_model.add(Dense(256,activation='relu'))
top_model.add(Dropout(0.5))
top_model.add(Dense(10,activation='softmax'))

model = Sequential()
model.add(vgg16_model)
model.add(top_model)
train_datagen = ImageDataGenerator(
    rotation_range = 40,     # 随机旋转度数
    width_shift_range = 0.2, # 随机水平平移
    height_shift_range = 0.2,# 随机竖直平移
    rescale = 1/255,         # 数据归一化
    shear_range = 20,       # 随机错切变换
    zoom_range = 0.2,        # 随机放大
    horizontal_flip = True,  # 水平翻转
    fill_mode = 'nearest',   # 填充方式
) 
test_datagen = ImageDataGenerator(
    rescale = 1/255,         # 数据归一化
) 
# 生成训练数据
train_generator = train_datagen.flow_from_directory(
    train_data,
    target_size=(image_w,image_h),
    batch_size=batch_size,
    )

# 测试数据
test_generator = test_datagen.flow_from_directory(
    test_data,
    target_size=(image_w,image_h),
    batch_size=batch_size,
    )

在这里插入图片描述

label = train_generator.class_indices

在这里插入图片描述

label = dict(zip(label.values(), label.keys()))
file = open('label.json','w',encoding='utf-8')
json.dump(label,file)
model.compile(optimizer=SGD(lr=1e-3,momentum=0.9),loss='categorical_crossentropy',metrics=['accuracy'])

model.fit_generator(train_generator,steps_per_epoch=len(train_generator),epochs=50,validation_data=test_generator,validation_steps=len(test_generator))
model.save('model_vgg16_dog.h5')

测试

from keras.models import load_model
from keras.preprocessing.image import img_to_array, load_img
import json
import numpy as np
import matplotlib.pyplot as plt
file = open('label.json','r',encoding='utf-8')
label = json.load(file)

# 载入模型
model = load_model('model_vgg16_dog.h5')
def predict(image):
    # 导入图片
    image = load_img(image)
    plt.imshow(image)
    image = image.resize((150,150))
    image = img_to_array(image)
    image = image/255
    image = np.expand_dims(image,0)   
    plt.title(label[str(model.predict_classes(image)[0])])
    plt.axis('off')
    plt.show()

传入图像路径测试

predict('data/test/n02093056-bullterrier/Niutougeng-is09aa7re.jpg')

在这里插入图片描述

标签:汪星,keras,VGG16,image,label,train,test,import,model
来源: https://blog.csdn.net/cyj5201314/article/details/118331000