tensorflow 實(shí)現(xiàn)XOR(異或)


import tensorflow as tf
import numpy as np

x_ = tf.placeholder(tf.float32, shape=[4, 2], name='x-input')
y_ = tf.placeholder(tf.float32, shape=[4, 1], name='y-input')

w1 = tf.Variable(tf.random_normal([2, 2], -1, 1), name='weights1')
w2 = tf.Variable(tf.random_normal([2, 1], -1, 1), name='weights2')

b1 = tf.Variable(tf.zeros([2]), name='bias1')
b2 = tf.Variable(tf.zeros([1]), name='bias2')

z2 = tf.sigmoid(tf.matmul(x_, w1) + b1)
pred = tf.sigmoid(tf.matmul(z2, w2) + b2)

cost = tf.reduce_mean(((y_ * tf.log(pred)) +((1 - y_) * tf.log(1.0 - pred)) ) * -1)

learning_rate = 0.01
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

XOR_X = [[0, 0], [0, 1], [1, 0], [1, 1]]
XOR_Y = [[0], [1], [1], [0]]

init = tf.initialize_all_variables()

with tf.Session() as sess:
    sess.run(init)
    write = tf.summary.FileWriter("./tb/XOR_logs", sess.graph)
    for i in range(100000):
        sess.run(train_step, feed_dict={x_: XOR_X, y_: XOR_Y})

    print ("Final prediction ", sess.run(pred, feed_dict={x_: XOR_X, y_: XOR_Y}))
XOR.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容