下面是创建模型,然后将其保存在本地目录中的代码。这里所有图像都放置在本地标记的文件夹中。现在,我想在其他带标签的文件夹中添加更多图像,并将它们包括到该模型中。所以总的来说,我不想从头开始训练模型,而是想增加新标签
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")
答案 0 :(得分:0)
因此,您可能想要做的是删除最后2层,它们对应于22的输出尺寸,并添加2层与新的输出尺寸相对应的新层({ {1}}层。
如果只想进行漂亮的初始化,则可以根据新数据重新调整模型。但是,如果要“冻结”模型的权重并仅微调最后一层,则需要将模型的所有层设置为不可训练,然后重新编译模型:
Dense