Tensorflow實戰4 多層感知機

2021-07-29 19:46:46 字數 2007 閱讀 6384

1.多層感知機簡介

多層感知機(multi-layer perceptron, mlp),又叫做多層神經網路。如果使用的是沒有隱含層的神經網路,那麼這樣的神經網路只能解決一些線性可分的問題,但是在實際的生活中,很多問題並不是線性可分的,例如xor函式問題,在這個特徵空間中,這就是乙個線性不可分問題,我們可以使用曲線來劃分這兩類樣本。在通常情況下,神經網路的隱含層越多,就可以對原有的特徵進行越抽象的變換,模型的擬合能力就越強。這個就是多層感知機的功能所在。

2.多層感知機的**構建

載入mnist資料集,並建立預設的interactive session

from tensorflow.examples.tutorials.mnist import input_data 

import tensorflow as tf

mnist = input_data.read_data_sets(「mnist_data」, one_hot = true)

sess = tf.interactivesession()

定義隱含層的引數並進行初始化。這裡的初始化使用的是截斷的正態分佈,其標準差為0.1。

in_units = 784

h1_units = 300

w1 = tf.variable(tf.truncated_normal([in_units, h1_units], stddev = 0.1))

b1 = tf.variable(tf.zeros([h1_units]))

w2 = tf.variable(tf.zeros([h1_units, 10]))

b2 = tf.variable(tf.zeros([10]))

定義placeholder

x = tf.placeholder(tf.float32, [none, in_units])

keep_prob = tf.placeholder(tf.float32)

定義模型結構,dropout相當於是隨機的把一些節點置0,這樣相當於是把一些中的畫素點變成黑色,增加網路結構的泛化能力

hidden1 = tf.nn.relu(tf.matmul(x, w1) + b1)

hidden1_drop = tf.nn.dropout(hidden1, keep_prob)

y = tf.nn.softmax(tf.matmul(hidden1_drop, w2) + b2)

定義損失函式和優化器

y_ = tf.placeholder(tf.float32, [none, 10])

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices = [1]))

train_step = tf.train.adagradoptimizer(0.3).minimize(cross_entropy)

初始化資料,並設定訓練次數。

tf.global_variables_initializer().run()

for i in range(3000):

batch_xs, batch_ys = mnist.train.next_batch(100)

train_step.run()

對模型進行**

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))

accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

print(accuracy.eval()

這篇部落格真是命途多舛,寫了整整三遍,儲存的時候各種報錯,還被我不小心刪掉了,真是絕了~~好歹堅持不懈,又寫了一遍o(∩_∩)o

《tensorflow實戰》之實現多層感知器(二)

理論研究表明,神經網路隱含層,層數越多,所需要的隱含節點可以越少。有一種方法叫dropout,在使用複雜的卷積神經網路訓練影象資料時尤其有效,簡單說,就是將神經網路某一層的輸出節點資料隨機丟棄一部分。實質上等於創造出了很多新的隨機樣本,通過增大樣本量 減少特徵數量來防止過擬合。拿sgd來舉例,不同的...

Tensorflow實戰之自編碼器與多層感知機

在無標註資料的情況下,則可利用無監督自編碼器來進行影象特徵的提取 自編碼器,即使用自身的高階特徵對自身進行編碼,簡單來說就是該網路訓練時,輸出等於輸入,使得中間層能夠學習組成影象的基本高階特徵,然後實現利用這些稀疏的高階特徵組合重構自己,所以其本質也是一種輸入輸出一致的神經網路。期望輸出與輸入一致 ...

tensorflow實現多層感知機

tensorflow 多層感知機識別手寫數字 匯入資料 import tensorflow as tf import tensorflow.tutorials.minist.input data as input data minist input data.read datasets mnist ...