tensorflow 異或門的實現

2022-05-01 22:54:24 字數 1913 閱讀 1368

一段小程式:待理解

import tensorflow as tf

import numpy as np

#輸入訓練資料,這裡是python的list, 也可以定義為numpy的ndarray

x_data = [[1., 0.], [0., 1.], [0., 0.], [1., 1.]]

#定義佔位符,佔位符在執行圖的時候必須feed資料

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

#訓練資料的標籤,注意維度

y_data = [[1], [1], [0], [0]]

y = tf.placeholder(tf.float32, shape = [none, 1])

#定義variables,在執行圖的過程中會被按照優化目標改變和儲存

weights =

bias =

#定義對於節點的操作函式

def nn(x, weights, bias):

d1 = tf.matmul(x, weights['w1']) + bias['b1']

d1 = tf.nn.relu(d1)

d2 = tf.matmul(d1, weights['w2']) + bias['b2']

d2 = tf.nn.sigmoid(d2)

return d2

#**值

pred = nn(x, weights, bias)

#損失函式

cost = tf.reduce_mean(tf.square(y - pred))

#學習率

learning_rate = 0.01

#定義tf.train用來訓練

# train_step = tf.train.gradientdescentoptimizer(learning_rate).minimize(cost) ## max_step: 20000, loss: 0.002638

train_step = tf.train.adamoptimizer(learning_rate).minimize(cost) ## max_step: 2000, loss: 0.000014

#初始化引數,圖執行的一開始必須初始化所有變數

init = tf.global_variables_initializer()

# correct_pred = tf.equal(tf.argmax(y, 1), tf.argmax(pred, 1))

# accuracy = tf.reduce_mean(tf.cast(correct_pred, 'float'))

#執行圖,with語句呼叫其後面函式的__enter()__函式,將返回值賦給as後面的引數,並在塊的最後呼叫__exit()__函式,相當於

#sess = tf.sessions(),

with tf.session() as sess:

sess.run(init)

max_step = 2000

for i in range(max_step + 1):

sess.run(train_step, feed_dict = )

loss = sess.run(cost, feed_dict = )

# acc = sess.run(accuracy, feed_dict = )

# 輸出訓練誤差和測試資料的標籤

if i % 100 == 0:

print('step: '+ str(i) + ' loss:' + "".format(loss)) #+ ' accuracy:' + "".format(acc))

print(sess.run(pred, feed_dict = ))

print('end')

#sess.close()

syncbn在TensorFlow中的實現

在syncbn之前我們先簡單介紹一下bn層以及多卡機制 bn層介紹 bn層中有兩個可訓練引數 beta,gamma 以及兩個統計引數 moving mean,moving variance 訓練過程和測試過程,bn層計算方式是不同的。訓練過程,beta和gamma與卷積層中的weight是一樣參與訓...

NLP入門例項推薦(Tensorflow實現)

mnist nn mnist cnn text classification cnn 專案 tensorflow例項 cnn處理句子相似度 multi perspective sentence similarity modeling with convolutional neural network...

基於tensorflow的神經網路簡單例項

通過構建乙個簡單的擬合直線的神經網路來簡單的講解基於tensorflow框架的神經網路構建方法。講解簡單的使用tensorboard來展示 分析神經網路流圖的方法。coding utf 8 呼叫tensorflow import tensorflow as tf import numpy as np...