项目的全部代码
链接:https://pan.baidu.com/s/1dCcQzm9G-Z3WcnVWR_6I3g
提取码:xue1
问题遇到的现象和发生背景
def ResNet152FineTuning(num_classes=3):
conv_base =tf.keras.applications.ResNet152(weights='imagenet',include_top=False,
input_shape=(224, 224, 3))
# 网络结构的最后一层,resnet152 有 1000 类,去掉最后一层
# resnet50 模型倒数第二层的输出是三维矩阵-卷积层的输出,做 pooling 或展平
# 参数有两种 imagenet 和 None,None 为从头开始训练,imagenet 为从网络下载已训练好的模型开始训练
model = tf.keras.models.Sequential()
model.add(conv_base)
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(num_classes, activation='softmax'))
# 因为 include_top = False,所以需要自己定义最后一层
return model
训练的代码
from fine_tuning_models import *
model = ResNet152FineTuning(33) # 引用的是上面的代码
filepath = 'animal33.h5'
from keras.preprocessing.image import ImageDataGenerator
#将所有图像乘以 1/255 缩放
train_datagen = ImageDataGenerator(rescale=1./255, rotation_range=40, width_shift_range=0.2,
height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True,)
validation_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(r'.\datasets\animal33\train', # 目标目录
target_size=(224, 224), # 将所有图像的大小调整为256*256
batch_size=5,
class_mode='categorical') # 因为使用了crossentropy损失
validation_generator = validation_datagen.flow_from_directory(r'.\datasets\animal33\validation',
target_size=(224, 224),
batch_size=5,
class_mode='categorical')
test_generator = test_datagen.flow_from_directory(r'.\datasets\animal33\test',
target_size=(224, 224),
batch_size=5,
class_mode='categorical')
from keras.callbacks import ModelCheckpoint
# 有一次提升, 则覆盖一次.
checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1,
save_best_only=True, mode='max', period=1)
callbacks_list = [checkpoint]
model.compile(loss='categorical_crossentropy',
optimizer=tf.keras.optimizers.Adam(learning_rate=0.00001), metrics=['acc'])
history = model.fit(train_generator, steps_per_epoch=6165, epochs=30,
validation_data=validation_generator,
validation_steps=3300,
callbacks=callbacks_list)
model.load_weights(filepath)
print("=============== 测试精度 ===============")
scores = model.evaluate(test_generator) # steps=30, verbose = 0)
print("{0}: {1:.2f}%".format(model.metrics_names[1], scores[1] * 100))
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
from com.util import plotting
plotting(acc, loss, val_acc, val_loss, mark_every=2)
这是画图的函数
def plotting(acc,loss,val_acc=None,val_loss=None,mark_every=1):
epochs=len(acc)
plt.rcParams['font.sans-serif']=['SimHei'] #显示中文(替换sans-serif字体)
f,ax=plt.subplots(1,2)
x1=np.arange(epochs)
x2=np.arange(epochs)
ax[0].plot(x1,loss,marker='v',label='训练数据',markevery=mark_every)
if val_loss !=None:
ax[0].plot(x1,val_loss,marker='s',label='验证数据',markevery=mark_every)
ax[1].plot(x2, acc, marker='v', label='训练数据', markevery=mark_every)
if val_acc !=None:
ax[1].plot(x2,val_acc,marker='s',label='验证数据',markevery=mark_every)
plt.ylim(0,1.0)
ax[0].legend(loc='upper right')
ax[0].set_title('损失值')
ax[1].legend(loc='lower right')
ax[1].set_title('精度')
ax[0].set_xlabel('轮次')
ax[0].set_ylabel('损失')
ax[1].set_xlabel('轮次')
ax[1].set_ylabel('精度')
plt.show()
问题相关代码,请勿粘贴截图
运行结果及报错内容
我的解答思路和尝试过的方法
我用这种方法,输出的结果都是一样的
from fine_tuning_models import *
from tensorflow.keras.applications.vgg16 import preprocess_input
from tensorflow.keras.preprocessing.image import load_img, img_to_array
import matplotlib.pyplot as plt
model = ResNet152FineTuning(14)
model.build(input_shape=(1, 224, 224, 3))
model.load_weights('animal14.h5')
img = load_img(path='cat.4000.jpg', target_size=(224, 224))
# img = load_img(path='cow_100.jpg', target_size=(224, 224))
# img = load_img(path='dog.2.jpg', target_size=(224, 224))
plt.axis('off')
img = img_to_array(img)
img = img.reshape((1, img.shape[0], img.shape[1], img.shape[2]))
#在预测之前,我们要对图片进行归一化处理
img = preprocess_input(img)
y_predictions = model.predict(img)
print(y_predictions)
输出的结果:
[[1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0.]]
我想要达到的结果
输入一张动物图片,使用已经训练好的模型进行预测,打印出预测的结果是什么动物