卷積神經網路(convolutional neural networks, cnn)是一類包含卷積計算且具有深度結構的前饋神經網路(feedforward neural networks),是深度學習(deep learning)的代表演算法之一。
這裡分享乙個demo。
# coding=utf-8
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.variable(initial)
def conv2d(x, w):
return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='same')
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='same')
mnist = input_data.read_data_sets('mnist_data/', one_hot=true)
sess = tf.interactivesession()
x = tf.placeholder('float', [none, 784])
y_ = tf.placeholder('float', [none, 10]) # 真實輸出的佔位符,佔位符用輸入資料填充
# 第一層卷積
w_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
x_image = tf.reshape(x, [-1, 28, 28, 1])
h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
# 第二層卷積
w_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
# 密集連線層
w_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, w_fc1) + b_fc1)
# dropout
keep_prob = tf.placeholder('float')
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# 輸出層
w_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, w_fc2) + b_fc2)
# 評估
cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))
train_step = tf.train.adamoptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))
sess.run(tf.initialize_all_variables())
for i in range(20000):
batch = mnist.train.next_batch(50)
if i % 100 == 0:
train_accuracy = accuracy.eval(feed_dict=)
print('step %d, training accuracy %g' % (i, train_accuracy))
train_step.run(feed_dict=)
print('test accuracy %g' % accuracy.eval(feed_dict=))
sess.close()
神經網路 卷積神經網路
這篇卷積神經網路是前面介紹的多層神經網路的進一步深入,它將深度學習的思想引入到了神經網路當中,通過卷積運算來由淺入深的提取影象的不同層次的特徵,而利用神經網路的訓練過程讓整個網路自動調節卷積核的引數,從而無監督的產生了最適合的分類特徵。這個概括可能有點抽象,我盡量在下面描述細緻一些,但如果要更深入了...
神經網路 卷積神經網路
1.卷積神經網路概覽 來自吳恩達課上一張,通過對應位置相乘求和,我們從左邊矩陣得到了右邊矩陣,邊緣是白色寬條,當畫素大一些時候,邊緣就會變細。觀察卷積核,左邊一列權重高,右邊一列權重低。輸入,左邊的部分明亮,右邊的部分灰暗。這個學到的邊緣是權重大的寬條 都是30 表示是由亮向暗過渡,下面這個圖左邊暗...
卷積神經網路 有趣的卷積神經網路
一 前言 最近一直在研究深度學習,聯想起之前所學,感嘆數學是一門樸素而神奇的科學。f g m1 m2 r 萬有引力描述了宇宙星河運轉的規律,e mc 描述了恆星發光的奧秘,v h d哈勃定律描述了宇宙膨脹的奧秘,自然界的大部分現象和規律都可以用數學函式來描述,也就是可以求得乙個函式。神經網路 簡單又...