# python人工智能：完整的图片识别(非图片验证码)，以及模型的使用

###### 我之所以写这篇文章主要是方便像我一样的纯小白使用代码，因为源代码里没有完整的结构，也存在一些小小的问题，献上完整通过的代码。

plain与resnet

residual block

ResNet_demo = {    "layer_50":[{"depth": 256,"num_class": 3},
{"depth": 512,"num_class": 4},
{"depth": 1024,"num_class": 6},
{"depth": 2048,"num_class": 3}],
"layer_101": [{"depth": 256, "num_class": 3},
{"depth": 512, "num_class": 4},
{"depth": 1024, "num_class": 23},
{"depth": 2048, "num_class": 3}],
"layer_152": [{"depth": 256, "num_class": 3},
{"depth": 512, "num_class": 8},
{"depth": 1024, "num_class": 36},
{"depth": 2048, "num_class": 3}]

def sampling(input_tensor,      #Tensor入口
ksize = 1,              #采样块大小
stride = 2):          #采样步长
data = input_tensor
data = slim.max_pool2d(data,ksize,stride = stride)
return data

def depthFilling(input_tensor, #输入
Tensor                depth):        #输出深度
data = input_tensor    #取出输入tensor的深度
input_depth = data.get_shape().as_list()[3]
[0,0],
[0,0],
[abs(depth - input_depth)//2,  abs(depth - input_depth)//2]])
return data

###### 残差模块

def bottleneck(input_tensor,output_depth):
#取出通道
redepth = input_tensor.get_shape().as_list()[3]
# 当通道不相符时，进行全零填充并降采样
if output_depth != redepth:
#全零填充
input_tensor = depthFilling(input_tensor,output_depth)
#降采样
input_tensor= sampling(input_tensor)
data = input_tensor
#降通道处理
data = slim.conv2d(inputs = data,
num_outputs = output_depth//4,
kernel_size = 1,stride = 1)
#提取特征
data = slim.conv2d(inputs = data,
num_outputs = output_depth//4,
kernel_size = 3,stride = 1)
#通道还原
data = slim.conv2d(inputs = data,
num_outputs = output_depth,
kernel_size = 1,stride = 1,
activation_fn=None,
normalizer_fn=None)
#生成残差
data = data + input_tensor
data = tf.nn.relu(data)
return data

FC代码实现

def cnn_to_fc(input_tensor,        #Tensor入口
num_output,          #输出接口数量
train = False,        #是否使用dropout
regularizer = None):  #正则函数
data = input_tensor    #得到输出信息的维度，用于全连接层的输入
data_shape = data.get_shape().as_list()
nodes = data_shape[1] * data_shape[2] * data_shape[3]
reshaped = tf.reshape(data, [data_shape[0], nodes])
#最后全连接层
with tf.variable_scope('layer-fc'):
fc_weights = tf.get_variable("weight",
[nodes,num_output],
initializer=tf.truncated_normal_initializer(stddev=0.1))
if regularizer != None:
fc_biases = tf.get_variable("bias", [num_output],
initializer=tf.constant_initializer(0.1))
fc = tf.nn.relu(tf.matmul(reshaped, fc_weights) + fc_biases)
if train:
fc = tf.nn.dropout(fc, 0.5)
return fc

###### inference
#堆叠ResNet模块
def inference(input_tensor, #数据入口
demos, #模型资料（list）
num_output, #出口数量
is_train):
data = input_tensor #第一层卷积7*7,stride = 2,深度为64
data = conv2d_same(data,64,7,2,is_train,None,normalizer_fn = False)
data = slim.max_pool2d(data,3,2,scope="pool_1")
with tf.variable_scope("resnet"): #堆叠总类瓶颈模块
demo_num = 0
for demo in demos:
demo_num += 1
print("--------------------------------------------") #堆叠子类瓶颈模块
for i in range(demo["num_class"]):
print(demo_num)
if demo_num is not 4:
if i == demo["num_class"] - 1:
stride = 2
else:
stride = 1
else:
stride = 1
data = bottleneck(data,demo["depth"],stride,is_train)
print("--------------------------------------------")
data = tf.layers.batch_normalization(data,training=is_train)
data = tf.nn.relu(data) #平均池化，也可用Avg_pool函数
data = tf.reduce_mean(data, [1, 2], keep_dims=True)
print("output : ", data) #最后全连接层
data = slim.conv2d(data,num_output,1,activation_fn=None)
data_shape = data.get_shape().as_list()
nodes = data_shape[1] * data_shape[2] * data_shape[3]
data = tf.reshape(data, [-1, nodes])
return data
###### inference调用方式
inference(input_tensor = 数据入口
demos = ResNet_demo["layer_101"],      #获取模型词典
num_output = 出口数量,
is_train = False)    # BN是否被训练

#### 使用介绍

Snip20181114_1.png

image.png

image.png

image.png

0 条评论

## 相关文章

4117

2082

### 如何在Python中用LSTM网络进行时间序列预测

Matt MacGillivray 拍摄，保留部分权利 翻译 | AI科技大本营（rgznai100） 长短记忆型递归神经网络拥有学习长观察值序列的潜力。它似...

9794

1944

1123

3868

3152

3047

4903

### 用TensorFlow生成抽象图案艺术

QQ图片20180204220437.jpg

8235