1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
| from google.colab import drive drive.mount('/content/drive')
from PIL import ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True import os from keras.preprocessing.image import ImageDataGenerator
base_dir = '/content/drive/My Drive/MachineLearning/dogImages'
train_dir = os.path.join(base_dir, 'train') valid_dir = os.path.join(base_dir, 'valid') test_dir = os.path.join(base_dir, 'test')
train_datagen = ImageDataGenerator( rescale=1./255, rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, vertical_flip=True, fill_mode='nearest') valid_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory( train_dir, target_size=(512, 512), batch_size=32, class_mode='categorical') valid_generator = valid_datagen.flow_from_directory( valid_dir, target_size=(512, 512), batch_size=32, class_mode='categorical')
import matplotlib.pyplot as plt from PIL import Image Image.MAX_IMAGE_PIXELS = 1000000000 %matplotlib inline
print('训练集部分原始图像:') display(Image.open(os.path.join(train_dir, '039.Bull_terrier/Bull_terrier_02752.jpg'))) print('训练集部分数据(图像)增强后的图像:') img = train_generator[0][0] fig = plt.figure(figsize=(40,4)) for i in range(0, 12): ax = fig.add_subplot(1, 12, i+1) ax.imshow(img[i]) plt.savefig('/content/drive/My Drive/MachineLearning/augmentation.png') plt.show() plt.close()
from keras.applications.inception_v3 import InceptionV3 from keras.models import Model from keras.layers import Dense
base_model = InceptionV3( weights='imagenet', include_top=False, input_shape=(512, 512, 3), pooling='avg') x = base_model.output
x = Dense(1024, activation='relu')(x)
predictions = Dense(133, activation='softmax')(x)
model = Model(inputs=base_model.input, outputs=predictions)
for i, layer in enumerate(base_model.layers): print(i, layer.name)
for layer in model.layers[:249]: layer.trainable = False for layer in model.layers[249:]: layer.trainable = True
from keras.optimizers import SGD model.compile(optimizer=SGD(lr=0.0001, momentum=0.9), loss='categorical_crossentropy', metrics=['accuracy'])
model.summary()
from keras.utils import plot_model from PIL import Image
plot_model(model, to_file='model.png', show_shapes=True, show_layer_names=True)
display(Image.open('model.png'))
from keras.callbacks import ModelCheckpoint
model.load_weights('/content/drive/My Drive/MachineLearning/dogImages.augmentation.model.weights.best.1.hdf5')
checkpointer = ModelCheckpoint( filepath='/content/drive/My Drive/MachineLearning/dogImages.augmentation.model.weights.best.1.hdf5', verbose=1, save_best_only=True)
history = model.fit_generator( generator=train_generator, epochs=10, validation_data=valid_generator, callbacks=[checkpointer], verbose=1, steps_per_epoch=210, validation_steps=50)
import matplotlib.pyplot as plt
plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('Model accuracy') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Train', 'Val'], loc='upper left') plt.savefig('/content/drive/My Drive/MachineLearning/acc_2.png') plt.show() plt.close()
plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model loss') plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(['Train', 'Val'], loc='upper left') plt.savefig('/content/drive/My Drive/MachineLearning/loss_2.png') plt.show() plt.close()
model.load_weights('/content/drive/My Drive/MachineLearning/dogImages.augmentation.model.weights.best.1.hdf5')
test_datagen = ImageDataGenerator(rescale=1./255) test_generator = test_datagen.flow_from_directory( test_dir, target_size=(512, 512), batch_size=20, class_mode='categorical')
train_loss, train_acc = model.evaluate_generator(train_generator) print('train_loss: ', train_loss) print('train_acc: ', train_acc) valid_loss, valid_acc = model.evaluate_generator(valid_generator) print('valid_loss: ', valid_loss) print('valid_acc: ', valid_acc) test_loss, test_acc = model.evaluate_generator(test_generator) print('test_loss: ', test_loss) print('test_acc: ', test_acc)
|