zoukankan      html  css  js  c++  java
  • alexnet- tensorflow

    alexnet 在 imagenet上夺冠是卷积神经网络如今这么火热的起点。

    虽然卷积神经网络很早就被提出来,但是由于计算能力和各方面原因,没有得到关注。

    alexnet 为什么能取得这么好的成绩,它的主要归功于

    • ReLU激活函数(能更快的收敛)
    • LRN 局部响应归一化(ReLU 之后的结果不像tanh,或sigmoid函数一样在一个区间,需要进行归一化)
    • dropout(防止过拟合,一定概率的删除一些神经元)
    • data augmentation(从256*256的图像中提取227*227的patches)
    • import os
      import numpy as np
      import tensorflow as tf
      from scipy.misc import imread
      
      train_x=np.zeros((1,227,227,3)).astype(np.float32)
      train_y=np.zeros((1,1000)).astype(np.float32)
      xdim=train_x.shape[1:]
      def conv(input, kernel, biases,s_h,s_w,padding="VALID",group=1):
          c=input.get_shape()[-1]
          assert c%group==0
      
              # conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, name=None)  
           # lambda实现匿名函数, 参数为i,k,
          convolve=lambda i,k: tf.nn.conv2d(i,k,[1,s_h,s_w,1],padding=padding)
          if group==1:
              conv=convolve(input,kernel)
          else:
              # tf.split(num_split,input,dimension): which dimension to split
              input_groups=tf.split(input,group,3)
              kernel_groups=tf.split(kernel,group,3)
              output_groups=[convolve(i,k) for i,k in zip(input_groups, kernel_groups)]
              conv=tf.concat(output_groups,3)
          return tf.reshape(tf.nn.bias_add(conv,biases),[-1]+conv.get_shape().as_list()[1:])
      
       #   load 加载 npy数据,训练好的alexnet网络
      # item函数是将dict 中的key 和 value 组成一个元组
      net=np.load("bvlc_alexnet.npy")
      # .item() convert the key and value in dict to a cell.
      # person={'name':''lizhang','age':'26'}  for key, value in person.items() : print key value
      net=net.item()
      
      im1=(imread("2.jpg").astype(np.float32))
      im1=im1-np.mean(im1)
      im1[:,:,0]=im1[:,:,2]
      im1[:,:,2]=im1[:,:,0]
      im1=im1.reshape(1,227,227,3)
      x=tf.placeholder(tf.float32,(None,)+xdim)
      
      conv1w=tf.Variable(net["conv1"][0])
      conv1b=tf.Variable(net["conv1"][1])
      
      s_h=4
      s_w=4
      ## 取 conv1 对应的参数,net_data["conv1"] 是value,包含两组值,net_data["conv1"][0]是卷积核的值, net_data["conv1"][1]对应偏置的值
      conv1=conv(x,conv1w,conv1b,s_h,s_w,padding="SAME",group=1)
      conv1=tf.nn.relu(conv1)
      radius=2
      alpha=2e-05
      beta=0.75
      bias=1.0
      lrn1=tf.nn.local_response_normalization(conv1,depth_radius=radius,alpha=alpha,beta=beta,bias=bias)
      maxpooling1=tf.nn.max_pool(lrn1,ksize=[1,3,3,1],strides=[1,2,2,1],padding='VALID')
      
      conv2w=tf.Variable(net["conv2"][0])
      conv2b=tf.Variable(net["conv2"][1])
      conv2=conv(maxpooling1,conv2w,conv2b,1,1,padding="SAME",group=2)
      conv2=tf.nn.relu(conv2)
      lrn2=tf.nn.local_response_normalization(conv2,depth_radius=radius,alpha=alpha,beta=beta,bias=bias)
      maxpooling2=tf.nn.max_pool(lrn2,ksize=[1,3,3,1],strides=[1,2,2,1],padding='VALID')
      
      
      conv3w=tf.Variable(net["conv3"][0])
      conv3b=tf.Variable(net["conv3"][1])
      conv3=conv(maxpooling2,conv3w,conv3b,1,1,padding="SAME",group=1)
      conv3=tf.nn.relu(conv3)
      
      conv4w=tf.Variable(net["conv4"][0])
      conv4b=tf.Variable(net["conv4"][1])
      conv4=conv(conv3,conv4w,conv4b,1,1,padding="SAME",group=2)
      conv4=tf.nn.relu(conv4)
      
      conv5w=tf.Variable(net["conv5"][0])
      conv5b=tf.Variable(net["conv5"][1])
      conv5=conv(conv4,conv5w,conv5b,1,1,padding="SAME",group=2)
      conv5=tf.nn.relu(conv5)
      maxpooling5=tf.nn.max_pool(conv5,ksize=[1,3,3,1],strides=[1,2,2,1],padding='VALID')
      
      fc6w=tf.Variable(net["fc6"][0])
      fc6b=tf.Variable(net["fc6"][1])
      fc6=tf.nn.relu_layer(tf.reshape(maxpooling5,[1,9216]),fc6w,fc6b)
      
      fc7w=tf.Variable(net["fc7"][0])
      fc7b=tf.Variable(net["fc7"][1])
      fc7=tf.nn.relu_layer(fc6,fc7w,fc7b)
      
      fc8w=tf.Variable(net["fc8"][0])
      fc8b=tf.Variable(net["fc8"][1])
      fc8=tf.nn.xw_plus_b(fc7,fc8w,fc8b)
      
      prob=tf.nn.softmax(fc8)
      init=tf.initialize_all_variables()
      sess=tf.Session()
      sess.run(init)
      output=sess.run(prob,feed_dict={x:im1})
      
      inds=np.argsort(output)[0,:]
      for x in range(5):
          print(inds[x])
      

     github:  https://github.com/hahafan/tensorflow_learning/blob/master/README.md

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

    除去name参数用以指定该操作的name,与方法有关的一共五个参数

    第一个参数input:指需要做卷积的输入图像,它要求是一个Tensor,具有[batch, in_height, in_width, in_channels]这样的shape,具体含义是[训练时一个batch的图片数量, 图片高度, 图片宽度, 图像通道数],注意这是一个4维的Tensor,要求类型为float32和float64其中之一

    第二个参数filter:相当于CNN中的卷积核,它要求是一个Tensor,具有[filter_height, filter_width, in_channels, out_channels]这样的shape,具体含义是[卷积核的高度,卷积核的宽度,图像通道数,卷积核个数],要求类型与参数input相同,有一个地方需要注意,第三维in_channels,就是参数input的第四维

    第三个参数strides:卷积时在图像每一维的步长,这是一个一维的向量,长度4

    第四个参数padding:string类型的量,只能是"SAME","VALID"其中之一,这个值决定了不同的卷积方式(后面会介绍)

    第五个参数:use_cudnn_on_gpu:bool类型,是否使用cudnn加速,默认为true

    结果返回一个Tensor,这个输出,就是我们常说的feature map

    conv2d实际上执行了以下操作:

      1. 将filter转为二维矩阵,shape为
        [filter_height * filter_width * in_channels, output_channels].
      2. 从input tensor中提取image patches,每个patch是一个virtual tensor,shape[batch, out_height, out_width, filter_height * filter_width * in_channels].
      3. 将每个filter矩阵和image patch向量相乘

    load(alexnet.npy) : alexnet.npy 是通过caffe model 转过来的, 具体见https://github.com/ethereon/caffe-tensorflow

     出现问题:

    • Tensorflow 函数tf.cocat([fw,bw],2)出错:TypeError: Expected int32, got list containing Tensors of type ‘_Message’ instead.

    Expected int32, got list containing Tensors of type ‘_Message’ inst
    原因是11版本的函数形式为:tf.concat(2,[fw,bw]),即应把串联的维度与串联值位置调换即可.

    • Input ‘split_dim’ of ‘Split’ Op has type float32 that does not match expected type of int32

      复制代码
      #原来是这样的:
      This is because in Tensorflow versions < 0.12.0 the split function takes the arguments as:
      x = tf.split(0, n_steps, x) # tf.split(axis, num_or_size_splits, value)
      
      #修改成这样的:
      The tutorial you are working from was written for versions > 0.12.0, which has been changed to be consistent with Numpy’s split syntax:
      x = tf.split(x, n_steps, 0) # tf.split(value, num_or_size_splits, axis)
  • 相关阅读:
    Oracle——内置函数介绍(日期函数)
    Oracle——内置函数介绍(数学函数)
    Oracle——内置函数介绍(字符串函数)
    css9——复合选择器(后代选择器,子选择器,并集选择器,链接伪类选择器,:focus伪类选择器)
    ASP.NET Core 如何使用Mvc相关技术建立Controller、Tag Helper (上)
    ASP.NET Core 包管理工具(4)
    ASP.NET Core3.x (3)
    ASP.NET Core3.x 基础—注册服务(2)
    ASP.NET Core3.x 基础(1)
    C#基础之接口(6)
  • 原文地址:https://www.cnblogs.com/fanhaha/p/7636890.html
Copyright © 2011-2022 走看看