我在 svhn 数据库上运行 VGG16 网络进行图像分类。 我将图像保存为形状 (None,64,64,3) 和形状标签 (None,10)。标签是大小为 10 的一维数组。
下面是我的部分代码。
import pandas as pd
import numpy as np
import cv2
import tensorflow as tf
import os
import scipy
from skimage import data, io, filters
import scipy.io as sio
from utils import *
import h5py
vgg = tf.keras.applications.vgg16.VGG16 (include_top=False,
weights='imagenet',
input_tensor=None,
input_shape=(64,64,3),
pooling='avg',
classes=10)
vgg.compile(loss='categorical_crossentropy',
optimizer='sgd',
metrics=['accuracy'])
vgg.fit(train_data, labels_data, epochs=5, batch_size=32)
所以我得到错误:
ValueError: Error when checking target: expected block5_pool to have shape (None, 512) but got array with shape (None, 10)
我应该做什么改变?
请您参考如下方法:
根据 Keras docs ,当您将 include_top 设置为 False 时,您将省略 3 个完全连接的层,如果将其设置为 True,则需要有 1000 个类imagenet 预训练权重。
因此,您需要在 vgg 网络之上附加全连接层:
model = Sequential([vgg, Dense(10), Activation('softmax')])
model.compile(loss='categorical_crossentropy',
optimizer='sgd',
metrics=['accuracy'])
# now check the input/output shapes
print(model.input_shape)
print(model.output_shape)
