【发布时间】:2019-05-08 22:22:04
【问题描述】:
以下是创建模型并将其保存在本地目录的代码。这里所有的图像都放在本地标记的文件夹中。现在我想在不同的标签文件夹中添加更多图像并将它们包含到这个模型中。所以总的来说,我不想从头开始重新训练模型,而是增加新标签
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")
【问题讨论】:
-
你能否展示一些代码,提供一些关于你已经拥有的和你尝试过的信息?
-
为了更清晰,我添加了代码,您能帮我如何在现有模型中添加更多标签。
-
好的,谢谢,确保您在代码示例中定义了所有变量。例如,我添加了正确的导入并添加了缩进以使其更易于使用。
标签: python-3.x machine-learning