使用tf-slim的ResNet V1 152和ResNet V2 152预训练模型进行图像分类

首先给大家推荐一下我老师大神的人工智能教学网站。教学不仅零基础,通俗易懂,而且非常风趣幽默,还时不时有内涵黄段子!点这里可以跳转到网站

本文使用tf-slim的ResNet V1 152和ResNet V2 152预训练模型进行图像分类,并研究slim网络的scope命名等。

tf-slim文档不太多,实现过程中多参考官网的源码: https://github.com/tensorflow/models/tree/master/research/slim
注意resnet v2的预处理有点不一样,输入是299而不是224
ResNet V2 152
(tf-slim: ResNet V2 models use Inception pre-processing and input image size of 299 (use –preprocessing_name inception –eval_image_size 299 when using eval_image_classifier.py). Performance numbers for ResNet V2 models are reported on the ImageNet validation set.)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 29 16:25:16 2017

@author: wayne


我们用的是tf1.2,最新的tf1.3地址是
https://github.com/tensorflow/models/tree/master/research/slim

http://geek.csdn.net/news/detail/126133
如何用TensorFlow和TF-Slim实现图像分类与分割

https://www.2cto.com/kf/201706/649266.html
【Tensorflow】辅助工具篇——tensorflow slim(TF-Slim)介绍

https://stackoverflow.com/questions/39582703/using-pre-trained-inception-resnet-v2-with-tensorflow
The Inception networks expect the input image to have color channels scaled from [-1, 1]. As seen here.
You could either use the existing preprocessing, or in your example just scale the images yourself: im = 2*(im/255.0)-1.0 before feeding them to the network.
Without scaling the input [0-255] is much larger than the network expects and the biases all work to very strongly predict category 918 (comic books).

TensorFlow实现ResNet(ResNet 152网络结构的forward耗时检测)
http://blog.csdn.net/superman_xxx/article/details/65452735
ResNet原理及其在TF-Slim中的实现
http://www.jianshu.com/p/3af06422c768
"""

import tensorflow as tf
slim = tf.contrib.slim
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import imagenet  #注意需要用最新版tf中的对应文件,否则http地址是不对的

from inception_resnet_v2 import *
from resnet_v1 import *
from resnet_v2 import *

import inception_preprocessing
import vgg_preprocessing


'''
inception_resnet_v2
  Returns:
    tensor_out: output tensor corresponding to the final_endpoint.
    end_points: a set of activations for external use, for example summaries or
                losses.
'''
tf.reset_default_graph()

checkpoint_file = 'inception_resnet_v2_2016_08_30.ckpt'
image = tf.image.decode_jpeg(tf.read_file('dog.jpeg'), channels=3) #['dog.jpg', 'panda.jpg']

image_size = inception_resnet_v2.default_image_size #  299

'''这个函数做了裁剪,缩放和归一化等'''
processed_image = inception_preprocessing.preprocess_image(image, 
                                                        image_size, 
                                                        image_size,
                                                        is_training=False,)
processed_images  = tf.expand_dims(processed_image, 0)

'''Creates the Inception Resnet V2 model.'''
arg_scope = inception_resnet_v2_arg_scope()
with slim.arg_scope(arg_scope):
  logits, end_points = inception_resnet_v2(processed_images, is_training=False)   

probabilities = tf.nn.softmax(logits)

saver = tf.train.Saver()


with tf.Session() as sess:
    saver.restore(sess, checkpoint_file)

    #predict_values, logit_values = sess.run([end_points['Predictions'], logits])
    logits2, image2, network_inputs, probabilities2 = sess.run([logits,
                                                                image,
                                                       processed_images,
                                                       probabilities])

    print(logits2)  
    print(logits2.shape) #(1, 1001)

    print(network_inputs.shape)
    print(probabilities2.shape)
    probabilities2 = probabilities2[0,:]
    sorted_inds = [i[0] for i in sorted(enumerate(-probabilities2),
                                        key=lambda x:x[1])]    


# 显示下载的图片
plt.figure()
plt.imshow(image2)#.astype(np.uint8))
plt.suptitle("Original image", fontsize=14, fontweight='bold')
plt.axis('off')
plt.show()

# 显示最终传入网络模型的图片
plt.imshow(network_inputs[0,:,:,:])
plt.suptitle("Resized, Cropped and Mean-Centered inputs to network",
             fontsize=14, fontweight='bold')
plt.axis('off')
plt.show()

names = imagenet.create_readable_names_for_imagenet_labels()
for i in range(5):
    index = sorted_inds[i]
    print(index)
    # 打印top5的预测类别和相应的概率值。
    print('Probability %0.2f => [%s]' % (probabilities2[index], names[index+1]))





'''https://github.com/tensorflow/models/blob/master/research/slim/train_image_classifier.py'''
def _get_variables_to_train():
    """Returns a list of variables to train.
    Returns:
      A list of variables to train by the optimizer.
    """
    trainable_scopes = 'InceptionResnetV2/Logits,InceptionResnetV2/AuxLogits'

    if trainable_scopes is None:
      return tf.trainable_variables()
    else:
      scopes = [scope.strip() for scope in trainable_scopes.split(',')]

    variables_to_train = []
    for scope in scopes:
      variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope)
      variables_to_train.extend(variables)
    return variables_to_train

'''
一些关于inception_resnet_v2变量的测试,在理解模型代码和迁移学习中很有用
'''
exx = tf.trainable_variables()
print(type(exx))
print(exx[0])
print(exx[-1])
print(exx[-2])
print(exx[-3])
print(exx[-4])
print(exx[-5])
print(exx[-6])
print(exx[-7])
print(exx[-8])
print(exx[-9])
print(exx[-10])

print('###############################################################')
variables_to_train = _get_variables_to_train()
print(variables_to_train)

print('###############################################################')
exclude = ['InceptionResnetV2/Logits', 'InceptionResnetV2/AuxLogits']
variables_to_restore = slim.get_variables_to_restore(exclude = exclude)
print(variables_to_restore[0])
print(variables_to_restore[-1])

print('###############################################################')
exclude = ['InceptionResnetV2/Logits']
variables_to_restore = slim.get_variables_to_restore(exclude = exclude)
print(variables_to_restore[0])
print(variables_to_restore[-1])



'''
resnet_v2 152
    num_classes: Number of predicted classes for classification tasks. If None
      we return the features (2048) before the logit layer.

  Returns:
    net: A rank-4 tensor of size [batch, height_out, width_out, channels_out].
      If global_pool is False, then height_out and width_out are reduced by a
      factor of output_stride compared to the respective height_in and width_in,
      else both height_out and width_out equal one. If num_classes is None, then
      net is the output of the last ResNet block, potentially after global
      average pooling. If num_classes is not None, net contains the pre-softmax
      activations.
    end_points: A dictionary from components of the network to the corresponding
      activation.
'''
tf.reset_default_graph()

checkpoint_file = 'resnet_v2_152.ckpt'
image = tf.image.decode_jpeg(tf.read_file('dog.jpeg'), channels=3) #['dog.jpg', 'panda.jpg']

image_size = inception_resnet_v2.default_image_size #  299

'''这个函数做了裁剪,缩放和归一化等'''
processed_image = inception_preprocessing.preprocess_image(image, 
                                                        image_size, 
                                                        image_size,
                                                        is_training=False,)
processed_images  = tf.expand_dims(processed_image, 0)

'''Creates the Resnet V2 model.'''
arg_scope = resnet_arg_scope()
with slim.arg_scope(arg_scope):
    net, end_points = resnet_v2_152(processed_images, 1001, is_training=False)   


probabilities = tf.nn.softmax(net)

saver = tf.train.Saver()


with tf.Session() as sess:
    saver.restore(sess, checkpoint_file)

    net2, image2, network_inputs, end_points2, probabilities2= sess.run([net, 
                                                             image,
                                                       processed_images,
                                                       end_points,
                                                       probabilities])
    print(net2)
    print(net2.shape)  #(1, 1, 1, 2048)
    print(type(end_points2)) #<class 'collections.OrderedDict'>
    print(network_inputs.shape)

    print(probabilities2.shape)
    probabilities2 = probabilities2[0,:]
    sorted_inds = [i[0] for i in sorted(enumerate(-probabilities2),
                                        key=lambda x:x[1])]    


# 显示下载的图片
plt.figure()
plt.imshow(image2)#.astype(np.uint8))
plt.suptitle("Original image", fontsize=14, fontweight='bold')
plt.axis('off')
plt.show()

# 显示最终传入网络模型的图片
plt.imshow(network_inputs[0,:,:,:])
plt.suptitle("Resized, Cropped and Mean-Centered inputs to network",
             fontsize=14, fontweight='bold')
plt.axis('off')
plt.show()

names = imagenet.create_readable_names_for_imagenet_labels()
for i in range(5):
    index = sorted_inds[i]
    print(index)
    # 打印top5的预测类别和相应的概率值。
    print('Probability %0.2f => [%s]' % (probabilities2[index], names[index+1]))


def _get_variables_to_train():
    """Returns a list of variables to train.
    Returns:
      A list of variables to train by the optimizer.
    """
    trainable_scopes = 'resnet_v2_152/logits'

    if trainable_scopes is None:
      return tf.trainable_variables()
    else:
      scopes = [scope.strip() for scope in trainable_scopes.split(',')]

    variables_to_train = []
    for scope in scopes:
      variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope)
      variables_to_train.extend(variables)
    return variables_to_train

exx = tf.trainable_variables()
print(type(exx))
print(exx[0])
print(exx[-1])
print(exx[-2])
print(exx[-3])
print(exx[-4])
print(exx[-5])
print(exx[-6])
print(exx[-7])
print(exx[-8])
print(exx[-9])
print(exx[-10])

print('###############################################################')
variables_to_train = _get_variables_to_train()
print(variables_to_train)

print('###############################################################')
exclude = ['resnet_v2_152/logits']
variables_to_restore = slim.get_variables_to_restore(exclude = exclude)
print(variables_to_restore[0])
print(variables_to_restore[-1])



'''
resnet_v1 152
  Returns:
    net: A rank-4 tensor of size [batch, height_out, width_out, channels_out].
      If global_pool is False, then height_out and width_out are reduced by a
      factor of output_stride compared to the respective height_in and width_in,
      else both height_out and width_out equal one. If num_classes is None, then
      net is the output of the last ResNet block, potentially after global
      average pooling. If num_classes is not None, net contains the pre-softmax
      activations.
    end_points: A dictionary from components of the network to the corresponding
      activation.
'''
tf.reset_default_graph()

checkpoint_file = 'resnet_v1_152.ckpt'
image = tf.image.decode_jpeg(tf.read_file('dog.jpeg'), channels=3) #['dog.jpg', 'panda.jpg']

image_size = resnet_v1_152.default_image_size #  224

'''
https://github.com/tensorflow/models/blob/master/research/slim/preprocessing/preprocessing_factory.py
'''
processed_image = vgg_preprocessing.preprocess_image(image, 
                                                        image_size, 
                                                        image_size,
                                                        is_training=False,)
processed_images  = tf.expand_dims(processed_image, 0)

'''Creates the Resnet V1 model.'''
arg_scope = resnet_arg_scope()
with slim.arg_scope(arg_scope):
    net, end_points = resnet_v1_152(processed_images, 1000, is_training=False)   


probabilities = tf.nn.softmax(net)

saver = tf.train.Saver()


with tf.Session() as sess:
    saver.restore(sess, checkpoint_file)

    net2, image2, network_inputs, end_points2, probabilities2= sess.run([net, 
                                                             image,
                                                       processed_images,
                                                       end_points,
                                                       probabilities])
    print(net2)
    print(net2.shape)  #(1, 1, 1, 2048)
    print(type(end_points2)) #<class 'collections.OrderedDict'>
    print(network_inputs.shape)

    print(probabilities2.shape)
    probabilities2 = probabilities2[0,:]
    sorted_inds = [i[0] for i in sorted(enumerate(-probabilities2),
                                        key=lambda x:x[1])]    


# 显示下载的图片
plt.figure()
plt.imshow(image2)#.astype(np.uint8))
plt.suptitle("Original image", fontsize=14, fontweight='bold')
plt.axis('off')
plt.show()

# 显示最终传入网络模型的图片
plt.imshow(network_inputs[0,:,:,:])
plt.suptitle("Resized, Cropped and Mean-Centered inputs to network",
             fontsize=14, fontweight='bold')
plt.axis('off')
plt.show()

names = imagenet.create_readable_names_for_imagenet_labels()
for i in range(5):
    index = sorted_inds[i]
    print(index)
    # 打印top5的预测类别和相应的概率值。
    print('Probability %0.2f => [%s]' % (probabilities2[index], names[index+1]))


def _get_variables_to_train():
    """Returns a list of variables to train.
    Returns:
      A list of variables to train by the optimizer.
    """
    trainable_scopes = 'resnet_v1_152/logits'

    if trainable_scopes is None:
      return tf.trainable_variables()
    else:
      scopes = [scope.strip() for scope in trainable_scopes.split(',')]

    variables_to_train = []
    for scope in scopes:
      variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope)
      variables_to_train.extend(variables)
    return variables_to_train

exx = tf.trainable_variables()
print(type(exx))
print(exx[0])
print(exx[-1])
print(exx[-2])
print(exx[-3])
print(exx[-4])
print(exx[-5])
print(exx[-6])
print(exx[-7])
print(exx[-8])
print(exx[-9])
print(exx[-10])

print('###############################################################')
variables_to_train = _get_variables_to_train()
print(variables_to_train)

print('###############################################################')
exclude = ['resnet_v1_152/logits']
variables_to_restore = slim.get_variables_to_restore(exclude = exclude)
print(variables_to_restore[0])
print(variables_to_restore[-1])

输出(图片省略):

INFO:tensorflow:Restoring parameters from inception_resnet_v2_2016_08_30.ckpt
[[-0.08273687 -0.53579688  0.20845751 ..., -0.73690009 -0.14878741
   0.46925241]]
(1, 1001)
(1, 299, 299, 3)
(1, 1001)




208
Probability 0.87 => [Labrador retriever]
209
Probability 0.03 => [Chesapeake Bay retriever]
258
Probability 0.00 => [Samoyed, Samoyede]
853
Probability 0.00 => [thatch, thatched roof]
245
Probability 0.00 => [French bulldog]
<class 'list'>
<tf.Variable 'InceptionResnetV2/Conv2d_1a_3x3/weights:0' shape=(3, 3, 3, 32) dtype=float32_ref>
<tf.Variable 'InceptionResnetV2/Logits/Logits/biases:0' shape=(1001,) dtype=float32_ref>
<tf.Variable 'InceptionResnetV2/Logits/Logits/weights:0' shape=(1536, 1001) dtype=float32_ref>
<tf.Variable 'InceptionResnetV2/AuxLogits/Logits/biases:0' shape=(1001,) dtype=float32_ref>
<tf.Variable 'InceptionResnetV2/AuxLogits/Logits/weights:0' shape=(768, 1001) dtype=float32_ref>
<tf.Variable 'InceptionResnetV2/AuxLogits/Conv2d_2a_5x5/BatchNorm/beta:0' shape=(768,) dtype=float32_ref>
<tf.Variable 'InceptionResnetV2/AuxLogits/Conv2d_2a_5x5/weights:0' shape=(5, 5, 128, 768) dtype=float32_ref>
<tf.Variable 'InceptionResnetV2/AuxLogits/Conv2d_1b_1x1/BatchNorm/beta:0' shape=(128,) dtype=float32_ref>
<tf.Variable 'InceptionResnetV2/AuxLogits/Conv2d_1b_1x1/weights:0' shape=(1, 1, 1088, 128) dtype=float32_ref>
<tf.Variable 'InceptionResnetV2/Conv2d_7b_1x1/BatchNorm/beta:0' shape=(1536,) dtype=float32_ref>
<tf.Variable 'InceptionResnetV2/Conv2d_7b_1x1/weights:0' shape=(1, 1, 2080, 1536) dtype=float32_ref>
###############################################################
[<tf.Variable 'InceptionResnetV2/Logits/Logits/weights:0' shape=(1536, 1001) dtype=float32_ref>, <tf.Variable 'InceptionResnetV2/Logits/Logits/biases:0' shape=(1001,) dtype=float32_ref>, <tf.Variable 'InceptionResnetV2/AuxLogits/Conv2d_1b_1x1/weights:0' shape=(1, 1, 1088, 128) dtype=float32_ref>, <tf.Variable 'InceptionResnetV2/AuxLogits/Conv2d_1b_1x1/BatchNorm/beta:0' shape=(128,) dtype=float32_ref>, <tf.Variable 'InceptionResnetV2/AuxLogits/Conv2d_2a_5x5/weights:0' shape=(5, 5, 128, 768) dtype=float32_ref>, <tf.Variable 'InceptionResnetV2/AuxLogits/Conv2d_2a_5x5/BatchNorm/beta:0' shape=(768,) dtype=float32_ref>, <tf.Variable 'InceptionResnetV2/AuxLogits/Logits/weights:0' shape=(768, 1001) dtype=float32_ref>, <tf.Variable 'InceptionResnetV2/AuxLogits/Logits/biases:0' shape=(1001,) dtype=float32_ref>]
###############################################################
<tf.Variable 'InceptionResnetV2/Conv2d_1a_3x3/weights:0' shape=(3, 3, 3, 32) dtype=float32_ref>
<tf.Variable 'InceptionResnetV2/Conv2d_7b_1x1/BatchNorm/moving_variance:0' shape=(1536,) dtype=float32_ref>
###############################################################
<tf.Variable 'InceptionResnetV2/Conv2d_1a_3x3/weights:0' shape=(3, 3, 3, 32) dtype=float32_ref>
<tf.Variable 'InceptionResnetV2/AuxLogits/Logits/biases:0' shape=(1001,) dtype=float32_ref>





INFO:tensorflow:Restoring parameters from resnet_v2_152.ckpt
[[-0.05580056  0.1566713   0.27344602 ..., -0.62925488  0.42608482
   1.22355282]]
(1, 1001)
<class 'collections.OrderedDict'>
(1, 299, 299, 3)
(1, 1001)




208
Probability 0.90 => [Labrador retriever]
209
Probability 0.06 => [Chesapeake Bay retriever]
264
Probability 0.00 => [Cardigan, Cardigan Welsh corgi]
837
Probability 0.00 => [sunglasses, dark glasses, shades]
838
Probability 0.00 => [sunscreen, sunblock, sun blocker]
<class 'list'>
<tf.Variable 'resnet_v2_152/conv1/weights:0' shape=(7, 7, 3, 64) dtype=float32_ref>
<tf.Variable 'resnet_v2_152/logits/biases:0' shape=(1001,) dtype=float32_ref>
<tf.Variable 'resnet_v2_152/logits/weights:0' shape=(1, 1, 2048, 1001) dtype=float32_ref>
<tf.Variable 'resnet_v2_152/postnorm/gamma:0' shape=(2048,) dtype=float32_ref>
<tf.Variable 'resnet_v2_152/postnorm/beta:0' shape=(2048,) dtype=float32_ref>
<tf.Variable 'resnet_v2_152/block4/unit_3/bottleneck_v2/conv3/biases:0' shape=(2048,) dtype=float32_ref>
<tf.Variable 'resnet_v2_152/block4/unit_3/bottleneck_v2/conv3/weights:0' shape=(1, 1, 512, 2048) dtype=float32_ref>
<tf.Variable 'resnet_v2_152/block4/unit_3/bottleneck_v2/conv2/BatchNorm/gamma:0' shape=(512,) dtype=float32_ref>
<tf.Variable 'resnet_v2_152/block4/unit_3/bottleneck_v2/conv2/BatchNorm/beta:0' shape=(512,) dtype=float32_ref>
<tf.Variable 'resnet_v2_152/block4/unit_3/bottleneck_v2/conv2/weights:0' shape=(3, 3, 512, 512) dtype=float32_ref>
<tf.Variable 'resnet_v2_152/block4/unit_3/bottleneck_v2/conv1/BatchNorm/gamma:0' shape=(512,) dtype=float32_ref>
###############################################################
[<tf.Variable 'resnet_v2_152/logits/weights:0' shape=(1, 1, 2048, 1001) dtype=float32_ref>, <tf.Variable 'resnet_v2_152/logits/biases:0' shape=(1001,) dtype=float32_ref>]
###############################################################
<tf.Variable 'resnet_v2_152/conv1/weights:0' shape=(7, 7, 3, 64) dtype=float32_ref>
<tf.Variable 'resnet_v2_152/postnorm/moving_variance:0' shape=(2048,) dtype=float32_ref>





INFO:tensorflow:Restoring parameters from resnet_v1_152.ckpt
[[ -2.77457213e+00  -8.63605142e-01  -2.58620429e+00  -3.61055827e+00
   -1.99115193e+00  -1.4507538e+00 .................
   -3.33744287e-01  -2.16450262e+00   1.86213362e+00   3.07718039e+00]]
(1, 1000)
<class 'collections.OrderedDict'>
(1, 224, 224, 3)
(1, 1000)




207
Probability 0.86 => [golden retriever]
208
Probability 0.09 => [Labrador retriever]
852
Probability 0.01 => [tennis ball]
263
Probability 0.01 => [Pembroke, Pembroke Welsh corgi]
235
Probability 0.00 => [German shepherd, German shepherd dog, German police dog, alsatian]
<class 'list'>
<tf.Variable 'resnet_v1_152/conv1/weights:0' shape=(7, 7, 3, 64) dtype=float32_ref>
<tf.Variable 'resnet_v1_152/logits/biases:0' shape=(1000,) dtype=float32_ref>
<tf.Variable 'resnet_v1_152/logits/weights:0' shape=(1, 1, 2048, 1000) dtype=float32_ref>
<tf.Variable 'resnet_v1_152/block4/unit_3/bottleneck_v1/conv3/BatchNorm/gamma:0' shape=(2048,) dtype=float32_ref>
<tf.Variable 'resnet_v1_152/block4/unit_3/bottleneck_v1/conv3/BatchNorm/beta:0' shape=(2048,) dtype=float32_ref>
<tf.Variable 'resnet_v1_152/block4/unit_3/bottleneck_v1/conv3/weights:0' shape=(1, 1, 512, 2048) dtype=float32_ref>
<tf.Variable 'resnet_v1_152/block4/unit_3/bottleneck_v1/conv2/BatchNorm/gamma:0' shape=(512,) dtype=float32_ref>
<tf.Variable 'resnet_v1_152/block4/unit_3/bottleneck_v1/conv2/BatchNorm/beta:0' shape=(512,) dtype=float32_ref>
<tf.Variable 'resnet_v1_152/block4/unit_3/bottleneck_v1/conv2/weights:0' shape=(3, 3, 512, 512) dtype=float32_ref>
<tf.Variable 'resnet_v1_152/block4/unit_3/bottleneck_v1/conv1/BatchNorm/gamma:0' shape=(512,) dtype=float32_ref>
<tf.Variable 'resnet_v1_152/block4/unit_3/bottleneck_v1/conv1/BatchNorm/beta:0' shape=(512,) dtype=float32_ref>
###############################################################
[<tf.Variable 'resnet_v1_152/logits/weights:0' shape=(1, 1, 2048, 1000) dtype=float32_ref>, <tf.Variable 'resnet_v1_152/logits/biases:0' shape=(1000,) dtype=float32_ref>]
###############################################################
<tf.Variable 'resnet_v1_152/conv1/weights:0' shape=(7, 7, 3, 64) dtype=float32_ref>
<tf.Variable 'resnet_v1_152/block4/unit_3/bottleneck_v1/conv3/BatchNorm/moving_variance:0' shape=(2048,) dtype=float32_ref>

参考:

def resnet_v2(inputs,
              blocks,
              num_classes=None,
              is_training=True,
              global_pool=True,
              output_stride=None,
              include_root_block=True,
              spatial_squeeze=True,
              reuse=None,
              scope=None):
  '''
  Generator for v2 (preactivation) ResNet models.

  This function generates a family of ResNet v2 models. See the resnet_v2_*()
  methods for specific model instantiations, obtained by selecting different
  block instantiations that produce ResNets of various depths.

  Training for image classification on Imagenet is usually done with [224, 224]
  inputs, resulting in [7, 7] feature maps at the output of the last ResNet
  block for the ResNets defined in [1] that have nominal stride equal to 32.
  However, for dense prediction tasks we advise that one uses inputs with
  spatial dimensions that are multiples of 32 plus 1, e.g., [321, 321]. In
  this case the feature maps at the ResNet output will have spatial shape
  [(height - 1) / output_stride + 1, (width - 1) / output_stride + 1]
  and corners exactly aligned with the input image corners, which greatly
  facilitates alignment of the features to the image. Using as input [225, 225]
  images results in [8, 8] feature maps at the output of the last ResNet block.

  For dense prediction tasks, the ResNet needs to run in fully-convolutional
  (FCN) mode and global_pool needs to be set to False. The ResNets in [1, 2] all
  have nominal stride equal to 32 and a good choice in FCN mode is to use
  output_stride=16 in order to increase the density of the computed features at
  small computational and memory overhead, cf. http://arxiv.org/abs/1606.00915.

  Args:
    inputs: A tensor of size [batch, height_in, width_in, channels].
    blocks: A list of length equal to the number of ResNet blocks. Each element
      is a resnet_utils.Block object describing the units in the block.
    num_classes: Number of predicted classes for classification tasks. If None
      we return the features before the logit layer.
    is_training: whether is training or not.
    global_pool: If True, we perform global average pooling before computing the
      logits. Set to True for image classification, False for dense prediction.
    output_stride: If None, then the output will be computed at the nominal
      network stride. If output_stride is not None, it specifies the requested
      ratio of input to output spatial resolution.
    include_root_block: If True, include the initial convolution followed by
      max-pooling, if False excludes it. If excluded, `inputs` should be the
      results of an activation-less convolution.
    spatial_squeeze: if True, logits is of shape [B, C], if false logits is
        of shape [B, 1, 1, C], where B is batch_size and C is number of classes.
        To use this parameter, the input images must be smaller than 300x300
        pixels, in which case the output logit layer does not contain spatial
        information and can be removed.
    reuse: whether or not the network and its variables should be reused. To be
      able to reuse 'scope' must be given.
    scope: Optional variable_scope.


  Returns:
    net: A rank-4 tensor of size [batch, height_out, width_out, channels_out].
      If global_pool is False, then height_out and width_out are reduced by a
      factor of output_stride compared to the respective height_in and width_in,
      else both height_out and width_out equal one. If num_classes is None, then
      net is the output of the last ResNet block, potentially after global
      average pooling. If num_classes is not None, net contains the pre-softmax
      activations.
    end_points: A dictionary from components of the network to the corresponding
      activation.

  Raises:
    ValueError: If the target output_stride is not valid.
  '''

点这里可以跳转到人工智能网站

发表评论