4.Transfer Learning

Intro

这是深度学习第4课。

在本课程结束时,您将能够使用迁移学习为您的自定义目标构建高度准确的计算机视觉模型,即使您的数据相对较少。

Lesson

[1]

from IPython.display import YouTubeVideo
YouTubeVideo('mPFq5KMxKVw', width=800, height=450)

Sample Code

Specify Model

[2]

from tensorflow.python.keras.applications import ResNet50
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dense, Flatten, GlobalAveragePooling2D

num_classes = 2
resnet_weights_path = '../input/resnet50/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5'

my_new_model = Sequential()
my_new_model.add(ResNet50(include_top=False, pooling='avg', weights=resnet_weights_path))
my_new_model.add(Dense(num_classes, activation='softmax'))

# Say not to train first layer (ResNet) model. It is already trained
my_new_model.layers[0].trainable = False

Compile Model

[3]

my_new_model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy'])

Fit Model

[4]

from tensorflow.python.keras.applications.resnet50 import preprocess_input
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator

image_size = 224
data_generator = ImageDataGenerator(preprocessing_function=preprocess_input)


train_generator = data_generator.flow_from_directory(
        '../input/urban-and-rural-photos/rural_and_urban_photos/train',
        target_size=(image_size, image_size),
        batch_size=24,
        class_mode='categorical')

validation_generator = data_generator.flow_from_directory(
        '../input/urban-and-rural-photos/rural_and_urban_photos/val',
        target_size=(image_size, image_size),
        class_mode='categorical')

my_new_model.fit_generator(
        train_generator,
        steps_per_epoch=3,
        validation_data=validation_generator,
        validation_steps=1)
Found 72 images belonging to 2 classes.
Found 20 images belonging to 2 classes.
Epoch 1/1
3/3 [==============================] - 29s 10s/step - loss: 0.5130 - acc: 0.8056 - val_loss: 0.3568 - val_acc: 0.9000

<tensorflow.python.keras._impl.keras.callbacks.History at 0x7f9f5bc56a20>

Note on Results:

在此阶段,打印出的验证准确度可能比训练准确度更好。 这一开始可能令人费解。
之所以出现这种情况,是因为随着网络的改进,在多个点计算训练精度(卷积中的数字正在更新以使模型更准确)。 当模型看到第一个训练图像时,网络是不准确的,因为权重还没有被训练/改进。 
在模型完成所有数据后计算验证损失和准确度度量。 因此,在计算这些分数时,网络已经过全面训练。
这在实践中不是一个严重的问题,我们不会担心它。

Your Turn

写下您自己的内核来进行迁移学习。

Exercise:Using Transfer Learning

Exercise Introduction

拍摄我们深度学习视频的摄像师提到了一个我们可以通过深度学习解决的令人沮丧的问题。

他提供扫描照片和幻灯片的服务,以数字方式存储它们。他使用的机器能够快速扫描许多照片。但是根据原始照片的方向,许多图像都是横向数字化的。他目前花了很多时间寻找哪些照片需要侧向旋转,所以他可以修复它们。

如果这个过程可以自动化,那将节省他很多时间。在本练习中,您将构建一个模型,用于区分哪些照片是横向的,哪些照片是竖向的。

如果您打算在商业上销售此服务,则可以使用大型数据集来训练模型。但即使是一个小数据集,我们也会取得巨大成功。我们将使用一个小型关于狗的图片数据集,其中一半是横向旋转。

指定和编译模型看起来与您看到的示例相同。但是您需要进行一些更改以适应模型。

1)Specify the Model

由于这是您第一次,您将无法从头开始创建。

我们已经填写了您需要的大部分代码,但是将一些关键部分留空了。

在下面的代码中填写(标有____)。 然后取消注释这些行并运行单元格。

[1]

from tensorflow.python.keras.applications import ResNet50
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dense, Flatten, GlobalAveragePooling2D

# num_classes is the number of categories your model chooses between for each prediction
# num_classes = ____
resnet_weights_path = '../input/resnet50/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5'

# my_new_model = Sequential()
# my_new_model.add(ResNet50(include_top=False, pooling='avg', weights=resnet_weights_path))
# my_new_model.add(Dense(num_classes, activation='softmax'))

# The value below is either True or False.  If you choose the wrong answer, your modeling results
# won't be very good.  Recall whether the first layer should be trained/changed or not.
# my_new_model.layers[0].trainable = ____

2)Compile the Model

我们再次提供了大部分代码,并留下了一个非常重要的部分。 填写空白(标有____)。 然后取消注释该行代码并运行单元格。

[2]

# We are calling the compile command for some python object. 
# Which python object is being compiled? Fill in the answer so the compile command works.
# ____.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy'])

3)Fit Model

您的训练数据位于../input/dogs-gone-sideways/images/train目录中。 验证数据在../input/dogs-gone-sideways/images/val中。 设置train_generator和validation_generator时使用该信息。

您有220张训练数据图像和217张验证数据。 对于训练生成器,选择批量大小为10。在fit_generator调用中找出steps_per_epoch的相应值? 它与示例中的不同。

填写所有空白(再次标记为____)。 然后取消注释每一行并运行代码单元格。 观察您的模型训练权重并提高准确度。

【3】

from tensorflow.python.keras.applications.resnet50 import preprocess_input
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator

image_size = 224
data_generator = ImageDataGenerator(preprocess_input)

#train_generator = data_generator.flow_from_directory(
#        directory = ____,
#        target_size=(image_size, image_size),
#        batch_size=____,
#        class_mode='categorical')

#validation_generator = data_generator.flow_from_directory(
#        directory = ____,
#        target_size=(image_size, image_size),
#        class_mode='categorical')

#my_new_model.fit_generator(
#        train_generator,
#        steps_per_epoch=____,
#        validation_data=____,
#        validation_steps=1)

您能从结果中判断出您的模型在验证数据中的正确时间吗?

在下一步中,我们将看看我们是否可以改进。

Keep Going

继续学习数据增强。 这是改进模型的一种巧妙而简单的方法。 然后,您将数据增强应用于此自动图像旋转问题。

猜你喜欢

转载自blog.csdn.net/cg129054036/article/details/82849106