最近完成了一个以图搜图的项目,项目总共用时三个多月。记录一下项目中用到机器学习的地方,以及各种踩过的坑。总的来说,项目分为一下几个部分:
新增AI编程课程,引领技术教育新趋势
def add_new_last_layer(base_model, nb_classes): ''' 添加最后的层 :param base_model: 预训练模型 :param nb_classes: 分类数量 :return: 新的 model ''' x = base_model.output x = GlobalAveragePooling2D()(x) x = Dense(128, activation='relu')(x) #输出的特征维度 88 predictions = Dense(nb_classes, activation='softmax')(x) model = Model(input=base_model.input, output=predictions) return model
3、冻结 base 层
以前的参数可以使用预训练好的参数,不需要重新训练,所以需要冻结,不让其改变。
def freeze_base_layer(model, base_model): for layer in base_model.layers: layer.trainable = False
4、编译模型
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics= ['accuracy']) # optimizer: 优化器# loss: 损失函数,多类的对数损失需要将分类标签转换为(将标签转化为形如(nb_samples, nb_classes)的二值序列) # metrics: 列表,包含评估模型在训练和测试时的网络性能的指标准备训练数据。
5、训练
#数据准备 IM_WIDTH, IM_HEIGHT = 224,224 train_dir = './refine_img_data/train' val_dir = './refine_img_data/test' nb_classes = 5 np_epoch = 3 batch_size = 16 nb_train_samples = get_nb_files(train_dir) nb_classes = len(glob.glob(train_dir + '/*')) nb_val_samples = get_nb_files(val_dir) # 根据现有数据,设置新数据生成参数 train_datagen = ImageDataGenerator( preprocessing_function=preprocess_input, rotation_range=30, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True ) test_datagen = ImageDataGenerator( preprocessing_function=