简介
本文主要介绍一些使用Keras过程中使用频率较高的常用代码段。
表格文件快速生成数据集
from keras.preprocessing.image import ImageDataGeneratortrain_gen = ImageDataGenerator(rescale=1/255., validation_split=0.2, horizontal_flip=False, shear_range=0.2, width_shift_range=0.1)test_gen = ImageDataGenerator(rescale=1/255.) img_size = (224, 224)batch_size = 32train_generator = train_gen.flow_from_dataframe(dataframe=df_train,directory='data/train',x_col='file_id',y_col='accent',batch_size=batch_size,class_mode='categorical',target_size=img_size, subset='training')valid_generator = train_gen.flow_from_dataframe(dataframe=df_train,directory="data/train",x_col="file_id",y_col="accent",batch_size=batch_size,class_mode="categorical", target_size=img_size,subset='validation')test_generator = test_gen.flow_from_dataframe(dataframe=df_test,directory = "data/test",x_col="file_id",target_size=img_size,batch_size=1,shuffle=False,class_mode=None)
预训练模型使用
from keras.applications.densenet import DenseNet121from keras.models import Modelfrom keras.layers import GlobalAveragePooling2D, Input, Dropout, Dense, BatchNormalizationfrom keras.optimizers import Adamdef build_densenet(input_shape=(224, 224, 3), n_classes=3):input_layer = Input(shape=input_shape)densenet121 = DenseNet121(include_top=False, weights='imagenet', input_tensor=input_layer)x = GlobalAveragePooling2D()(densenet121.output)x = Dropout(0.5)(x)x = Dense(n_classes, activation='softmax')(x)model = Model(input_layer, x)pile(loss='categorical_crossentropy', optimizer=Adam(lr=3e-4), metrics=['accuracy'])return modeldensenet = build_densenet()
如果觉得《Keras-常用代码》对你有帮助,请点赞、收藏,并留下你的观点哦!