Tensorflow学习记录9--alexnet网络

alexnet总结

总共八层,作者说层数越多应该效果会更好,但是考虑GPU的计算能力整成八层,作者说任意减掉一层都会是识别效果下降,前俩层有卷积层,局部激活响应归一化lrn,激活函数relu以及池化层,中间俩层只有卷积和激活函数relu,第五层的卷积层只有卷积和池化层,没有lrn和relu,第六七八层又全都是全链接层,最后一层的输出为1000个神经元。
其中使用了relu,dropout,lrn,image patch,pca等方法来优化结果。

具体网络结构如下:

#conv1 (Convolution)kernel size:11 stride:4 pad:0 out_layer:96
#lrn
#relu
#pool1(MAX Pooling)kernel size :3 stride:2 pad:0

#conv2 (Convolution)kernel size:5 stride:1 pad:2 out_layer:256
#lrn
#relu
#pool2(MAX Pooling)kernel size :3 stride:2 pad:0

#conv3(Convolution)kernel size:3 stride:1 pad:1 out_layer:384

#conv4(Convolution)kernel size:3 stride:1 pad:1 out_layer:384

#conv5(Convolution)kernel size:3 stride:1 pad:1 out_layer:256
#pool5(MAX Pooling)kernel size:3 stride:2 pad:0

#fc6 
#relu6
#drop6 out 4096

#fc7
#relu7
#drop7 out 4096

#fc8 out 1000

疑问:
1. 输出层数跟其他东西有关系吗??步长

注意事项

1 卷积需要设置的参数

tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, data_format=None, name=None)

  1. W也就是filter
    举个例子:
    W=(11,11,3,96),11*11为卷积滤波器的高和宽,3为输入的维数,96为输出的维数,96可以理解为有96个这样,同样大小的滤波器,

  2. Strides
    一般这么设置,strides=[1, k, k, 1],代表以k为步长

  3. padding

  1. “SAME”, “VALID”了俩个选项
  2. SAME那么卷积后生成的图像大小为 W/k向上取整,即还有剩下的就补全,k为步长,也可以这样理解,如果能够整除,也加一,如果不能整除,反正也要加一,所以可以这么写。
  3. VALID代表不会再原有的输入的基础上再添加新的像素,卷积后生成的图像大小为(w-f+1)/k向上取整,也可以等于(w-f)/k + 1,可以理解为最后一个填满了减掉11,前面除以步长则为前面的个数,最后再加一则为输出,自行体会哈哈哈
  1. 实例
    假设输入图像为224×224×3,即为input
    W=(11,11,3,96)
    strides=[1, 4, 4, 1]
    padding=same
    这样,输出的矩形框的大小就为55×55,227/4 向上取整。

2 ReLUs与Local Response Normalization

收敛效果比tanh,sigmoid快,并且不容易梯度消失,但是,使用ReLU f(x)=max(0,x)后,激活函数后的值没有了区域空间,一般在Relu之后会做一个normalization。思想是找周围n个核的激活函数的值做归一化。具体如下图:
未添加图

3 pooling注意事项

tf.nn.max_pool(value, ksize, strides, padding, data_format=’NHWC’, name=None)
1. value,输入,shape为[batch,height,width,channels]
2. ksize=[1,k_h,k_w,1],pooling核的大小
3. stride=[1,s_h,s_w,1]
4. pading=padding,与上面一致
5. data_format

  1. 有NHWC,NCHW俩种选择。
  2. NHWC:[batch, in_height, in_width, in_channels]
  3. NCHW:[batch, in_channels, in_height, in_width]

4 数据处理

image patch

为了防止过拟合,最简单的方式是增加数据,patch也可以用来扩展数据集。
从256×256中随机提出224×224的patches,一般的patch的方式有:

  1. Flat
  2. Linear
  3. Quadratic
  4. Edged

另一种方式是利用PCA来扩展数据。

下面是一个alexnet网络来训练手写数字识别的例子

# -*- coding: utf-8 -*-
# 输入数据
import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

import tensorflow as tf

# 定义网络超参数
learning_rate = 0.001
training_iters = 200000
batch_size = 64
display_step = 20

# 定义网络参数
n_input = 784 # 输入的维度
n_classes = 10 # 标签的维度
dropout = 0.8 # Dropout 的概率

# 占位符输入
x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_classes])
keep_prob = tf.placeholder(tf.float32)

# 卷积操作
def conv2d(name, l_input, w, b):
    return tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(l_input, w, strides=[1, 1, 1, 1], padding='SAME'),b), name=name)

# 最大下采样操作
def max_pool(name, l_input, k):
    return tf.nn.max_pool(l_input, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME', name=name)

# 归一化操作
def norm(name, l_input, lsize=4):
    return tf.nn.lrn(l_input, lsize, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name=name)

# 定义整个网络 
def alex_net(_X, _weights, _biases, _dropout):
    # 向量转为矩阵
    # 这个是把x的-1维即最后一维,即每一副图像从一维变为28*28*1维的图像
    _X = tf.reshape(_X, shape=[-1, 28, 28, 1])

    # 卷积层
    conv1 = conv2d('conv1', _X, _weights['wc1'], _biases['bc1'])
    # 下采样层
    pool1 = max_pool('pool1', conv1, k=2)
    # 归一化层
    norm1 = norm('norm1', pool1, lsize=4)
    # Dropout
    norm1 = tf.nn.dropout(norm1, _dropout)

    # 卷积
    conv2 = conv2d('conv2', norm1, _weights['wc2'], _biases['bc2'])
    # 下采样
    pool2 = max_pool('pool2', conv2, k=2)
    # 归一化
    norm2 = norm('norm2', pool2, lsize=4)
    # Dropout
    norm2 = tf.nn.dropout(norm2, _dropout)

    # 卷积
    conv3 = conv2d('conv3', norm2, _weights['wc3'], _biases['bc3'])
    # 下采样
    pool3 = max_pool('pool3', conv3, k=2)
    # 归一化
    norm3 = norm('norm3', pool3, lsize=4)
    # Dropout
    norm3 = tf.nn.dropout(norm3, _dropout)

    # 全连接层,先把特征图转为向量
    dense1 = tf.reshape(norm3, [-1, _weights['wd1'].get_shape().as_list()[0]]) 
    dense1 = tf.nn.relu(tf.matmul(dense1, _weights['wd1']) + _biases['bd1'], name='fc1') 
    # 全连接层
    dense2 = tf.nn.relu(tf.matmul(dense1, _weights['wd2']) + _biases['bd2'], name='fc2') # Relu activation

    # 网络输出层
    out = tf.matmul(dense2, _weights['out']) + _biases['out']
    return out

# 存储所有的网络参数
weights = {
    'wc1': tf.Variable(tf.random_normal([3, 3, 1, 64])),
    'wc2': tf.Variable(tf.random_normal([3, 3, 64, 128])),
    'wc3': tf.Variable(tf.random_normal([3, 3, 128, 256])),
    'wd1': tf.Variable(tf.random_normal([4096, 1024])),
    #'wd1': tf.Variable(tf.random_normal([4\*4\*256, 1024])),
    'wd2': tf.Variable(tf.random_normal([1024, 1024])),
    'out': tf.Variable(tf.random_normal([1024, 10]))
}
biases = {
    'bc1': tf.Variable(tf.random_normal([64])),
    'bc2': tf.Variable(tf.random_normal([128])),
    'bc3': tf.Variable(tf.random_normal([256])),
    'bd1': tf.Variable(tf.random_normal([1024])),
    'bd2': tf.Variable(tf.random_normal([1024])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}

# 构建模型
pred = alex_net(x, weights, biases, keep_prob)

# 定义损失函数和学习步骤
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

# 测试网络
correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

# 初始化所有的共享变量
init = tf.initialize_all_variables()

# 开启一个训练
with tf.Session() as sess:
    sess.run(init)
    step = 1
    # Keep training until reach max iterations
    #while step \* batch_size < training_iters:
    while step * batch_size < training_iters:
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)
        # 获取批数据
        sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys, keep_prob: dropout})
        if step % display_step == 0:
            # 计算精度
            acc = sess.run(accuracy, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 1.})
            # 计算损失值
            loss = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 1.})
            #print "Iter " + str(step\*batch_size) + ", Minibatch Loss= " + "{:.6f}".format(loss) + ", Training Accuracy= " + "{:.5f}".format(acc)
            print "Iter " + str(step*batch_size) + ", Minibatch Loss= " + "{:.6f}".format(loss) + ", Training Accuracy= " + "{:.5f}".format(acc)
        step += 1
    print "Optimization Finished!"
    # 计算测试精度
    print "Testing Accuracy:", sess.run(accuracy, feed_dict={x: mnist.test.images[:256], y: mnist.test.labels[:256], keep_prob: 1.})

input_data代码如下:

# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

"""Functions for downloading and reading MNIST data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import gzip
import os
import tempfile

import numpy
from six.moves import urllib
from six.moves import xrange  # pylint: disable=redefined-builtin
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: tensorflow cifar-10-batches-py是一个经典的深度学习数据集,被广泛用于图像分类任务的训练和评估。 该数据集是CIFAR-10数据集的Python版本,提供了10个类别的60000个32x32彩色图像。其中,50000张图像作为训练集,10000张图像作为测试集。 这个数据集是用Python编写的,并且使用了pickle库来加载和处理数据。它可以通过执行"import cifar10"来导入,并使用"cifar10.load_data()"来加载其数据。 加载数据后,可以使用TensorFlow来构建一个图像分类模型。TensorFlow是一个开源的深度学习框架,可以用于构建、训练和评估机器学习模型。 使用tensorflow cifar-10-batches-py数据集,可以进行图像分类任务的实验和研究。可以结合卷积神经网络等深度学习模型,对图像进行特征提取和分类。 在训练模型时,可以使用训练集进行权重更新和优化,然后使用测试集来评估模型的性能。 总结来说,tensorflow cifar-10-batches-py是一个常用的深度学习数据集,可以用于图像分类任务的研究和实验。它结合了TensorFlow框架,提供了加载、处理和评估数据的功能。通过使用它,可以建立一个自定义的图像分类模型,并对其进行训练和评估。 ### 回答2: tensorflow cifar-10-batches-py是一个用于在tensorflow框架中处理CIFAR-10数据集的Python脚本。CIFAR-10数据集是一个广泛应用于图像分类的数据集,包含10个不同类别的影像数据,每个类别有6000个32x32大小的彩色图像。 这个Python脚本通过提供一些函数和类来加载CIFAR-10数据集,并且将图像和标签进行预处理,以便于在训练和测试模型时使用。脚本中的函数可以帮助我们将原始的二进制数据转换成可用于训练的张量形式。 该脚本提供的函数可以将CIFAR-10数据集分为训练集和测试集,并提供了一个函数用于获取下一个训练批或测试批的图像和标签。此外,该脚本还提供了一个函数用于显示CIFAR-10数据集中的图像。 使用tensorflow cifar-10-batches-py脚本,我们可以很方便地加载和预处理CIFAR-10数据集,并用于训练和测试图像分类模型。这个脚本是使用Python编写的,可以在tensorflow环境中直接使用。 ### 回答3: TensorFlow的cifar-10-batches-py是一个用于训练和验证图像分类模型的数据集。它是基于CIFAR-10数据集的一个版本,其中包含50000张用于训练的图像和10000张用于验证的图像。 CIFAR-10数据集是一个常用的图像分类数据集,包含10个不同的类别,每个类别有大约6000张图像。这些类别包括:飞机、汽车、鸟类、猫、鹿、狗、青蛙、马、船和卡车。每个图像的大小为32x32像素,是彩色图像。 cifar-10-batches-py数据集通过Python脚本cifar10.py提供,它将数据集分为5个训练批次和1个验证批次。在训练过程中,可以使用这些批次中的图像进行训练,并根据验证数据集的结果来评估模型的性能。 这个数据集提供了一个方便的方式来测试和评估不同的图像分类算法和模型。使用TensorFlow的cifar10.py脚本可以加载这个数据集,并提供一些函数,用于解析和处理图像数据。 在使用cifar-10-batches-py数据集进行训练时,通常会将图像数据进行预处理,例如将像素值进行归一化处理,以便于模型的训练。同时,还可以使用数据增强的技术,如随机翻转、旋转或裁剪图像,以增加数据的多样性。 总的来说,TensorFlow的cifar-10-batches-py数据集是为了方便机器学习研究人员进行图像分类模型训练和验证而提供的一个常用数据集。它可以用于测试和评估不同的图像分类算法和模型的性能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值