tensorflow 樣例程式

2022-08-23 17:15:13 字數 2565 閱讀 2554

import

tensorflow as tf

from numpy.random import

randomstate

#定義訓練資料batch的大小

batch_size = 8

#定義神經網路的引數

w1 = tf.variable(tf.random_normal([2, 3], stddev=1, seed=1))

w2 = tf.variable(tf.random_normal([3, 1], stddev=1, seed=1))

#訓練集的輸入資料和對應的標籤

x = tf.placeholder(tf.float32, shape=(none,2), name='

x-input')

y_ = tf.placeholder(tf.float32, shape=(none,1), name='

y-input')

#定義神經網路前向傳播的過程

a =tf.matmul(x, w1)

y =tf.matmul(a, w2)

#定義損失函式和反向傳播的演算法

cross_entropy = -tf.reduce_mean(

y_ * tf.log(tf.clip_by_value(y, 1e-10, 1.0)))

train_start = tf.train.adamoptimizer(0.001).minimize(cross_entropy)

#通過隨機數生成乙個模擬資料集

rdm = randomstate(1) #

1為隨機種子

dataset_size = 128x = rdm.rand(dataset_size, 2)

#x = rdm.uniform(3, 4, (2, 3))

'''x的輸出結果

array([[3.26865012, 3.80827801, 3.29528879],

[3.54412138, 3.48792149, 3.85535641]])

'''y = [[int(x1+x2 < 1)] for (x1, x2) in

x]init_op =tf.global_variables_initializer()

with tf.session() as sess:

sess.run(init_op)

print

(sess.run(w1))

print

(sess.run(w2))

'''在訓練之前神經網路的引數的值:

w1 = [[-0.8113182 1.4845988 0.06532937]

[-2.4427042 0.0992484 0.5912243 ]]

w2 = [[-0.8113182 ], [ 1.4845988 ], [ 0.06532937]]

'''trainstep = 5000

for i in

range(trainstep):

#每次選取 batch_size 個樣本進行訓練。

start = (i * batch_size) %dataset_size

end = min(start+batch_size, dataset_size)

#通過選取的樣本訓練神經網路並更新引數

sess.run(train_start, feed_dict=)

if i % 1000 ==0:

total_cross_entropy =sess.run(

cross_entropy, feed_dict=)

print("

after %d training step(s), cross entropy on all data is %g

" %(i, total_cross_entropy))

'''輸出結果:

after 0 training step(s), cross entropy on all data is 0.0674925

after 1000 training step(s), cross entropy on all data is 0.0163385

after 2000 training step(s), cross entropy on all data is 0.00907547

after 3000 training step(s), cross entropy on all data is 0.00714436

after 4000 training step(s), cross entropy on all data is 0.00578471

'''print

(sess.run(w1))

print

(sess.run(w2))

'''在訓練之後神經網路的引數的值:

w1 = [[-1.9618274 2.582354 1.6820377]

[-3.4681718 1.0698233 2.11789 ]]

w2 = [[-1.8247149], [ 2.6854665], [ 1.418195 ]]

'''

完整神經網路樣例程式詳解

主要是對 tensorflow 實戰google深度學習框架 的第三章中在模擬資料集上訓練神經網路的完整程式進行詳解,所利用的神經網路結構圖如下 詳細 如下 import tensorflow as tf from numpy.random import randomstate 定義神經網路的引數,...

TensorFlow入門例程 mnist手寫資料集

使用tensorflow訓練模型,大概分為以下幾個步驟 定義變數並初始化,宣告用到的佔位符 建立模型 訓練模型,首先需要定義乙個指標來評估這個模型的好壞。在本教程中使用交叉熵來表徵模型的效能好壞。使用一些優化演算法 如梯度下降法 來最小化目標函式 交叉熵 評估模型,判斷 值和真實值之間的差值。得到 ...

CUDA實戰 第乙個樣例程式

這兩天開始看 gpu高效能程式設計cuda實戰 這本書,學到的東西稍稍在部落格做個記錄。使用cuda c程式設計的話,當然首先需要有個支援cuda的gpu,市面上很多gpu都已經支援cuda,之後需要為gpu安裝cuda驅動程式,我使用的是ubuntu系統,安裝方法在這篇部落格 cuda7.5 安裝...