# 2、ResNet网络结构

ResNet中最重要的是残差学习单元：

# 3、ResNet代码实战

``````import tensorflow.contrib.slim as slim
``````

``````def res_identity(input_tensor,conv_depth,kernel_shape,layer_name):
with tf.variable_scope(layer_name):
relu = tf.nn.relu(slim.conv2d(input_tensor,conv_depth,kernel_shape))
outputs = tf.nn.relu(slim.conv2d(relu,conv_depth,kernel_shape) + input_tensor)
return outputs
``````

``````def res_change(input_tensor,conv_depth,kernel_shape,layer_name):
with tf.variable_scope(layer_name):
relu = tf.nn.relu(slim.conv2d(input_tensor,conv_depth,kernel_shape,stride=2))
input_tensor_reshape = slim.conv2d(input_tensor,conv_depth,[1,1],stride=2)
outputs = tf.nn.relu(slim.conv2d(relu,conv_depth,kernel_shape) + input_tensor_reshape)
return outputs
``````

``````def inference(inputs):
x = tf.reshape(inputs,[-1,28,28,1])
conv_1 = tf.nn.relu(slim.conv2d(x,32,[3,3])) #28 * 28 * 32
pool_1 = slim.max_pool2d(conv_1,[2,2]) # 14 * 14 * 32
block_1 = res_identity(pool_1,32,[3,3],'layer_2')
block_2 = res_change(block_1,64,[3,3],'layer_3')
block_3 = res_identity(block_2,64,[3,3],'layer_4')
block_4 = res_change(block_3,32,[3,3],'layer_5')
net_flatten = slim.flatten(block_4,scope='flatten')
fc_1 = slim.fully_connected(slim.dropout(net_flatten,0.8),200,activation_fn=tf.nn.tanh,scope='fc_1')
output = slim.fully_connected(slim.dropout(fc_1,0.8),10,activation_fn=None,scope='output_layer')
return output
``````