深度學習 - Kaggle - Dog & Cat - 不做任何處理直接訓練
#資料夾分類處理後的路徑
original_dataset_dir ='C:\\Users\\lido_lee\\Downloads\\kaggle_original_data'
base_dir = 'C:\\Users\\lido_lee\\Downloads\\cats_and_dogs_small'
train_dir = 'C:\\Users\\lido_lee\\Downloads\\cats_and_dogs_small\\train'
validation_dir = 'C:\\Users\\lido_lee\\Downloads\\cats_and_dogs_small\\validation'
將Kaggle下載的資料分類處理,之後再來複習,這邊先跳過詳細過程。
#建立模型網絡
from keras import layers
from keras import models
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu',input_shape=(150, 150, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(512, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
#選擇優化器RMSprop、損失函數binary_crossentropy、指標acc
from keras import optimizers
model.compile(loss='binary_crossentropy',
optimizer=optimizers.RMSprop(lr=1e-4),
metrics=['acc'])
#使用Keras內建圖型Data生成器
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)
若要使用圖形增強,直接使用
ImageDataGenerator的function即可,後續會用到。
#將訓練資料縮小至150*150,每個批量20張圖,所以2000張圖跌代一次要跑100次
train_generator = train_datagen.flow_from_directory(train_dir,
target_size=(150, 150),
batch_size=20,
class_mode='binary')
#驗證資料同上
validation_generator = test_datagen.flow_from_directory( validation_dir,
target_size=(150, 150),
batch_size=20,
class_mode='binary')
#將訓練&驗證資料丟進fit_generator訓練
history = model.fit_generator( train_generator,
steps_per_epoch=100,
epochs=30,
validation_data=validation_generator,
validation_steps=50)
#將訓練完的模型&參數儲存起來
model.save('cats_and_dogs_small_1.h5')
沒有留言:
張貼留言