问题描述:基于AlexNet模型的图像分类
AlexNet 框架包含了输入层、5个卷积层、3个全连接层以及输出层。其中有3个卷积层进行了最大池化。
AlexNet框架的特点:1、使用了Relu激活函数,相比于sigmoid或tanh函数,它是一种非饱和函数,运行速度更快;并且Relu激活函数利用分片线性结构实现了非线性的表达方式,更适合于层数较深的网络。
2、局部响应归一化:为了改善网络的性能,在部分卷积层中使用了归一化处理。
3、重叠池化:传统的池化没有重叠,不同窗口的池化过程独立计算。AlexNet使用了重叠池化,与不重叠窗口相比,有助于缓解过拟合现象。
4、同时,AlexNet网络采用丢失输出操作减少过拟合现象。
具体实现:
inputdata.py:定义了数据集的情况,数据集中一共有两类图片,分别是sun.jpg,另一类是cac.jpg.对这两类图片进行读取。
inputdata.py
import tensorflow as tf
import os
import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
def get_files(file_dir):
sun = []
label_sun = []
cac = []
label_cac = []
for file in os.listdir(file_dir):
name = file.split(sep='.')
if 'sun' in name[0]:
sun.append(file_dir + file)
label_sun.append(0)
else:
if 'cac' in name[0]:
cac.append(file_dir + file)
label_cac.append(1)
image_list = np.hstack((sun, cac))
label_list = np.hstack((label_sun, label_cac))
# 把标签和图片都放倒一个 temp 中 然后打乱顺序,然后取出来
temp = np.array([image_list, label_list])
temp = temp.transpose()
# 打乱顺序
np.random.shuffle(temp)
# 取出第一个元素作为 image 第二个元素作为 label
image_list = list(temp[:, 0])
label_list = list(temp[:, 1])
label_list = [int(i) for i in label_list]
return image_list, label_list
# image_W ,image_H 指定图片大小,batch_size 每批读取的个数 ,capacity队列中 最多容纳元素的个数
def get_batch(image, label, image_W, image_H, batch_size, capacity):
# 转换数据为 ts 能识别的格式
image = tf.cast(image, tf.string)
label = tf.cast(label, tf.int32)
# 将image 和 label 放倒队列里
input_queue = tf.train.slice_input_producer([image, label])
label = input_queue[1]
# 读取图片的全部信息
image_contents = tf.read_file(input_queue[0])
# 把图片解码,channels =3 为彩色图片, r,g ,b 黑白图片为 1 ,也可以理解为图片的厚度
image = tf.image.decode_png(image_contents, channels=3)
# 将图片以图片中心进行裁剪或者扩充为 指定的image_W,image_H
image = tf.image.resize_image_with_crop_or_pad(image, image_W, image_H)
# 对数据进行标准化,标准化,就是减去它的均值,除以他的方差
image = tf.image.per_image_standardization(image)
# 生成批次 num_threads 有多少个线程根据电脑配置设置 capacity 队列中 最多容纳图片的个数 tf.train.shuffle_batch 打乱顺序,
image_batch, label_batch = tf.train.batch([image, label], batch_size=batch_size, num_threads=4, capacity=capacity)
# 重新定义下 label_batch 的形状
label_batch = tf.reshape(label_batch, [batch_size])
# 转化图片
image_batch