【Kaggle学习笔记】 | Deep Learning

本文详细介绍了深度学习中卷积神经网络的基础模块及关键参数,包括图像大小、分类数量、池化策略等,并通过实例展示了如何使用ResNet50进行图像分类,以及如何构建和训练自己的模型。

卷积是深度学习的基础模块,一些重要参数的定义如下:

image_size:图片大小

num_classes:几分类问题,即最后结果需要分为几类

pooling:池化策略

loss:损失函数,用来判断梯度下降的方向

metrics:评价函数,用于判断模型性能

activation:激活函数的选择

optimizer:梯度优化器,即选择梯度下降的策略

batch_size:将数据分成的批数,模型每处理一批数据进行梯度更新

epoch:模型训练几轮,即数据被喂入模型几轮

Iteration:使用一个batch数据对模型进行一次参数更新的过程

kernel_size:卷积核大小

strides:卷积核在输入上移动的步长

# 简单的卷积核
# 水平线卷积
horizontal_line_conv = [[1, 1], 
                        [-1, -1]]
# 垂直线卷积
vertical_line_conv = [[1,-1],
                      [1,-1]]

简单步骤

  1. 加载图片并统一图片大小
# 选择图片路径
from os.path import join
image_dir = '../input/dog-breed-identification/train/' # 保存图片的文件夹目录
img_paths = [join(image_dir, filename) for filename in 
                           ['0c8fe33bd89646b678f6b2891df8a1c6.jpg',
                            '0c3b282ecbed1ca9eb17de4cb1b6e326.jpg',
                            '04fb4d719e9fe2b6ffe32d9ae7be8a22.jpg',
                            '0e79be614f12deb4f7cae18614b7391b.jpg']]
# 处理图片
import numpy as np
from tensorflow.python.keras.applications.resnet50 import preprocess_input
from tensorflow.python.keras.preprocessing.image import load_img, img_to_array
image_size = 224 # 设置图片大小
def read_and_prep_images(img_paths, img_height=image_size, img_width=image_size):
    imgs = [load_img(img_path, target_size=(img_height, img_width)) for img_path in img_paths]
    img_array = np.array([img_to_array(img) for img in imgs])
    output = preprocess_input(img_array)
    return(output)
  1. 构建模型
from tensorflow.python.keras.applications import ResNet50
my_model = ResNet50(weights='../input/resnet50/resnet50_weights_tf_dim_ordering_tf_kernels.h5')
test_data = read_and_prep_images(img_paths)
preds = my_model.predict(test_data)
  1. 得到结果
# 可视化预测结果
from learntools.deep_learning.decode_predictions import decode_predictions
from IPython.display import Image, display
most_likely_labels = decode_predictions(preds, top=3, class_list_path='../input/resnet50/imagenet_class_index.json') # 得到前3名预测结果,分别有编号、标签和预测概率3个值
for i, img_path in enumerate(img_paths):
    display(Image(img_path)) # 展示原图
    print(most_likely_labels[i])

自己构建模型

有些时候想要自己构造一个模型,或在已有模型上加上几层,需要经过如下几步(以在ResNet50模型上加多一层softmax为例)

在已训练的模型上构建

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 = 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'))
my_new_model.layers[0].trainable = False # 第一层Resnet已经训练好,不需要再训练
  1. 编译模型
my_new_model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy']) # 设置梯度优化方式为SGD、损失函数为分类交叉熵、性能指标为准确率
  1. 拟合模型
from tensorflow.python.keras.applications.resnet50 import preprocess_input
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator
image_size = 224
# ImageDataGenerator可用来进行数据增强,如horizontal_flip(水平反转)、width_shift_range (水平平移范围)、height_shift_range(垂直平移范围)等参数可设置,preprocessing_function是选择的处理函数,如preprocess_input为归一化处理
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, # 进行梯度下降时每个batch包含的样本数,按一个Batch来进行梯度更新
        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, # 一个epoch包含的步数(每一步是一个batch的数据送入)
        validation_data=validation_generator,
        validation_steps=1)
自己从头建一个模型
# 导入一些库
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from tensorflow.python import keras
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dense, Flatten, Conv2D, Dropout
img_rows, img_cols = 28, 28 # 图片大小为28*28
num_classes = 10 # 十分类
# 数据预处理
def data_prep(raw):
    out_y = keras.utils.to_categorical(raw.label, num_classes)

    num_images = raw.shape[0]
    x_as_array = raw.values[:,1:]
    x_shaped_array = x_as_array.reshape(num_images, img_rows, img_cols, 1)
    out_x = x_shaped_array / 255
    return out_x, out_y
train_file = "../input/digit-recognizer/train.csv"
raw_data = pd.read_csv(train_file)
x, y = data_prep(raw_data)
# 构建模型
model = Sequential()
model.add(Conv2D(30, kernel_size=(3, 3), # 30个卷积核,每个为3*3
                 strides=2, # 步长为2
                 activation='relu', # 激活函数为relu
                 input_shape=(img_rows, img_cols, 1))) # 输入图片为28*28*1
model.add(Dropout(0.5)) # Dropout层,50%的神经元被剪掉
model.add(Conv2D(30, kernel_size=(3, 3), strides=2, activation='relu'))
model.add(Dropout(0.5)) # Dropout层,50%的神经元被剪掉
model.add(Flatten()) # Flattern层,将多维输入压成一维,常用在卷积层和全连接层之间
model.add(Dense(128, activation='relu')) # 全连接层,输出128个分类
model.add(Dense(num_classes, activation='softmax')) # 全连接层,输出10个分类
# 编译并拟合模型
model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer='adam', # 梯度优化器为adam
              metrics=['accuracy']) # 性能指标为准确率
model.fit(x, y,
          batch_size=128, # 一批数据128张
          epochs=2, # 两轮训练,即数据被喂入模型两次
          validation_split = 0.2) # 20%的验证集
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值