tf cnn

import tensorflow as tf


### 代码开始 ### (≈ 12 行代码)

# 根据上面处理后的图片大小,补充模型输入
x = tf.placeholder(tf.float32, [None, 64, 64, 1])
y = tf.placeholder(tf.float32, [None, 2])

# 卷积 + 池化 1
conv1 = tf.layers.conv2d(inputs=x, filters=32, kernel_size=[3, 3], padding='same', activation=tf.nn.relu)
#conv1 = tf.layers.Conv2D(filters=32, kernel_size=[3, 3], padding='same', activation=tf.nn.relu).apply(x)
pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2,2], strides=1)

# 卷积 + 池化 2
conv2 = tf.layers.conv2d(inputs=pool1, filters=64, kernel_size=[3, 3], padding='same', activation=tf.nn.relu)
pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2,2], strides=1)

# 卷积 + 池化 3
conv3 = tf.layers.conv2d(inputs=pool2, filters=128, kernel_size=[3, 3], padding='same', activation=tf.nn.relu)
pool3 = tf.layers.max_pooling2d(inputs=conv3, pool_size=[2,2], strides=2)

# 全连接层
flatten = tf.layers.flatten(pool3)
dense = tf.layers.dense(inputs=flatten, units=128, activation=tf.nn.relu)
dropout = tf.layers.dropout(inputs=dense, rate=0.6)
logits = tf.layers.dense(inputs=dropout, units=2) # 输出

### 代码结束 ###

### 代码开始 ### (≈ 3 行代码)

# 损失函数
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=y))

# 优化器
training_op = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)

# 准确率计算公式
acc_func = tf.reduce_mean(tf.cast(tf.nn.in_top_k(logits, tf.argmax(y, 1), 1), tf.float32))

### 代码结束 ###

猜你喜欢

转载自www.cnblogs.com/coshaho/p/10273964.html
今日推荐