以下是创建模型然后将其保存本地目录的代码。这里所有图像都放在本地标记的文件夹中。现在,我想在不同标记的文件夹中添加更多图像,并将其包含在此型号中。因此,总的来说,而不是从头开始重新培训模型,我想增加新标签
from keras.layers import Conv2D, Activation, MaxPooling2D, Flatten, Dense
from keras.models import Sequential
from keras.optimizers import Adam
def readTestData(testDir):
data = []
filenames = []
# loop over the input images
images = os.listdir(testDir)
for imageFileName in images:
# load the image, pre-process it, and store it in the data list
imageFullPath = os.path.join(testDir, imageFileName)
#print(imageFullPath)
img = load_img(imageFullPath)
arr = img_to_array(img) # Numpy array with shape (...,..,3)
arr = cv2.resize(arr, (HEIGHT,WIDTH))
data.append(arr)
filenames.append(imageFileName)
return data, filenames
def createModel():
#model = Sequential()
#model.add(Conv2D(20, (5, 5), padding="same", input_shape=inputShape))
#model.add(Activation("relu"))
#model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
#model.add(Conv2D(50, (5, 5), padding="same"))
#model.add(Activation("relu"))
#model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
#model.add(Flatten())
#model.add(Dense(500))
#model.add(Activation("relu"))
#model.add(Dense(output_dim=22))
#model.add(Activation("softmax"))
model = load_model('test')
model.pop()
model.pop()
for layer in model.layers:
layer.trainable = False
model.add(Dense(output_dim=24,name='new_Dense',activation='softmax'))
opt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)
model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=
["accuracy"])
return model
random.seed(10)
X, Y = readTrainData("labelled images directory path")
# scale the raw pixel intensities to the range [0, 1]
X = np.array(X, dtype="float") / 255.0
Y = np.array(Y)
# convert the labels from integers to vectors
Y = to_categorical(Y, num_classes=22)
(trainX, valX, trainY, valY) = train_test_split(X,Y,test_size=0.10,
random_state=10)
aug = ImageDataGenerator(rotation_range=30, width_shift_range=0.1,
height_shift_range=0.1, shear_range=0.2, zoom_range=0.2,
horizontal_flip=True, fill_mode="nearest")
# initialize the model
model = createModel()
# train the network
H = model.fit_generator(aug.flow(trainX, trainY, batch_size=BS),
validation_data=(valX, valY),
steps_per_epoch=len(trainX) // BS, samples_per_epoch=len(trainX) *
5,epochs=EPOCHS, verbose=1)
# save the model to disk
model.save("test_new")
,因此您可能要做的是删除最后2层,该层对应于22的输出维度,并添加与新输出维度相对应的2个新层(相同但是Dense
层的维度不同(。
,如果您想拥有一个不错的初始化,则可以在新数据上重新装置模型。但是,如果您想"冻结"模型的权重,只需微调最后一层,则需要将模型的所有层视为不可训练的层,然后重新编译模型:
# these lines will remove the last 2 layers
model.pop()
model.pop()
# do the following 2 lines only if you want to keep the weights from the first training
for layer in model.layers:
layer.trainable = False
model.add(Dense(output_dim=new_output_dim))
model.add(Activation("softmax"))
# do the following 2 lines only if you want to keep the weights from the first training
opt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)
model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=
["accuracy"])