TensorFlow - XOR 实现
在本章中,我们将学习使用 TensorFlow 实现 XOR。在开始使用 TensorFlow 实现 XOR 之前,让我们先看看 XOR 真值表。这将帮助我们理解加密和解密过程。
| A | B | A XOR B |
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
XOR Cipher 加密方法主要用于加密数据,这些数据难以通过暴力破解方法(即生成随机加密密钥以匹配正确密钥)来破解。
使用 XOR Cipher 实现的概念是定义一个 XOR 加密密钥,然后对用户尝试加密的指定字符串中的字符与该密钥执行 XOR 操作。现在我们将重点关注使用 TensorFlow 的 XOR 实现,如下所示 −
#声明必要的模块
import tensorflow as tf
import numpy as np
"""
一个简单的 numpy 实现的 XOR 门,用于理解反向传播算法
"""
x = tf.placeholder(tf.float64,shape = [4,2],name = "x")
#声明输入 x 的占位符
y = tf.placeholder(tf.float64,shape = [4,1],name = "y")
#声明期望输出 y 的占位符
m = np.shape(x)[0]#训练样本数量
n = np.shape(x)[1]#特征数量
hidden_s = 2 #隐藏层中的节点数量
l_r = 1#学习率初始化
theta1 = tf.cast(tf.Variable(tf.random_normal([3,hidden_s]),name = "theta1"),tf.float64)
theta2 = tf.cast(tf.Variable(tf.random_normal([hidden_s+1,1]),name = "theta2"),tf.float64)
#执行前向传播
a1 = tf.concat([np.c_[np.ones(x.shape[0])],x],1)
#第一层的权重与第一层的输入相乘
z1 = tf.matmul(a1,theta1)
#第二层的输入是第一层的输出,经过激活函数处理并添加偏置列
a2 = tf.concat([np.c_[np.ones(x.shape[0])],tf.sigmoid(z1)],1)
#第二层的输入与权重相乘
z3 = tf.matmul(a2,theta2)
#输出经过激活函数处理以获得最终概率
h3 = tf.sigmoid(z3)
cost_func = -tf.reduce_sum(y*tf.log(h3)+(1-y)*tf.log(1-h3),axis = 1)
#TensorFlow 内置的优化器,使用指定的学习率执行梯度下降以获得 theta 值
optimiser = tf.train.GradientDescentOptimizer(learning_rate = l_r).minimize(cost_func)
#设置执行 XOR 操作所需的 X 和 Y 值
X = [[0,0],[0,1],[1,0],[1,1]]
Y = [[0],[1],[1],[0]]
#初始化所有变量,创建会话并运行 TensorFlow 会话
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
#为每次迭代运行梯度下降,并打印使用更新后的 theta 值获得假设
for i in range(100000):
sess.run(optimiser, feed_dict = {x:X,y:Y})#使用 feed_dict 设置占位符值
if i%100==0:
print("Epoch:",i)
print("Hyp:",sess.run(h3,feed_dict = {x:X,y:Y}))
上述代码行会生成如下截图所示的输出 −
