【问题标题】:Retrain existing built keras cnn sequential model(predicting 16 categories) with more categories用更多类别重新训练现有构建的 keras cnn 顺序模型(预测 16 个类别)
【发布时间】: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


【解决方案1】:

所以你可能想要做的是删除最后 2 层,它们对应于输出维度 22,并添加对应于新输出维度的 2 个新层(相同但 @ 的维度不同987654322@层)。

然后,如果您只想进行良好的初始化,您可以根据新数据重新调整您的模型。但是,如果您想“冻结”模型的权重并仅微调最后一层,则需要将模型的所有层设置为不可训练,然后重新编译模型:

# 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"])

【讨论】:

  • 我无法理解如何使用上述代码保持权重,我指的是另一个链接,这里他们提供了另一种权重方式:- weights_training = model.layers[-1].get_weights() 。链接:-stackoverflow.com/questions/51498608/…。是否有任何博客/网址可以让我获得如何将新层添加到现有模型的完整代码。
  • 您只需在代码中添加类似的行,然后使用新数据集进行训练。此外,您不需要在此处获取权重,因为您手头已有模型,或者我可能对您的问题不了解。
  • 我需要预测以前的标签以及新添加的标签,所以我需要获取以前的权重并将它们添加到新模型中吗?
  • 如果您使用我在我的方法中向您展示的内容,您仍然使用相同的基本模型,因此您无需担心权重。此代码 sn-p 将位于您在问题中显示的代码的末尾。
  • 我使用了您的方法,但出现以下错误:- ValueError:名称“dense_1”在模型中使用了 2 次。所有图层名称都应该是唯一的。 ValueError:名称“activation_1”在模型中使用了 2 次。所有图层名称都应该是唯一的。所以用 model.add(Dense(output_dim=24),name='new_Dense',activation='softmax') 替换 step model.add(Dense(output_dim=22)) 我能够创建新模型,但它只能预测新模型甚至旧图像的类别也具有 54% 的准确率。我在本地创建了一个新的培训目录,只有这两个新标签,是不是错了?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-14
  • 1970-01-01
  • 2017-04-14
  • 1970-01-01
  • 1970-01-01
  • 2018-04-15
相关资源
最近更新 更多