- TensorFlow 教程
- TensorFlow - 主页
- TensorFlow - 介绍
- TensorFlow - 安装
- 理解人工智能
- 数学基础
- 机器学习与深度学习
- TensorFlow - 基础知识
- 卷积神经网络
- 循环神经网络
- TensorBoard 可视化
- TensorFlow - 词嵌入
- 单层感知器
- TensorFlow - 线性回归
- TFLearn 及其安装
- CNN 和 RNN 的区别
- TensorFlow - Keras
- TensorFlow - 分布式计算
- TensorFlow - 导出
- 多层感知器学习
- 感知器的隐藏层
- TensorFlow - 优化器
- TensorFlow - XOR 实现
- 梯度下降优化
- TensorFlow - 形成图
- 使用 TensorFlow 进行图像识别
- 神经网络培训建议
- TensorFlow 有用资源
- TensorFlow - 快速指南
- TensorFlow - 有用的资源
- TensorFlow - 讨论
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 密码加密方法基本上用来加密很难用蛮力方法破解的数据,即生成匹配适当密钥的随机加密密钥。
用 XOR 密码实现的概念是定义一个 XOR 加密密钥,然后用此密钥对指定字符串中的字符执行 XOR 运算,用户试图加密该字符串。现在,我们将重点了解如何使用 TensorFlow 实现 XOR,方法如下 −
#Declaring necessary modules import tensorflow as tf import numpy as np """ A simple numpy implementation of a XOR gate to understand the backpropagation algorithm """ x = tf.placeholder(tf.float64,shape = [4,2],name = "x") #declaring a place holder for input x y = tf.placeholder(tf.float64,shape = [4,1],name = "y") #declaring a place holder for desired output y m = np.shape(x)[0]#number of training examples n = np.shape(x)[1]#number of features hidden_s = 2 #number of nodes in the hidden layer l_r = 1#learning rate initialization 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) #conducting forward propagation a1 = tf.concat([np.c_[np.ones(x.shape[0])],x],1) #the weights of the first layer are multiplied by the input of the first layer z1 = tf.matmul(a1,theta1) #the input of the second layer is the output of the first layer, passed through the activation function and column of biases is added a2 = tf.concat([np.c_[np.ones(x.shape[0])],tf.sigmoid(z1)],1) #the input of the second layer is multiplied by the weights z3 = tf.matmul(a2,theta2) #the output is passed through the activation function to obtain the final probability h3 = tf.sigmoid(z3) cost_func = -tf.reduce_sum(y*tf.log(h3)+(1-y)*tf.log(1-h3),axis = 1) #built in tensorflow optimizer that conducts gradient descent using specified learning rate to obtain theta values optimiser = tf.train.GradientDescentOptimizer(learning_rate = l_r).minimize(cost_func) #setting required X and Y values to perform XOR operation X = [[0,0],[0,1],[1,0],[1,1]] Y = [[0],[1],[1],[0]] #initializing all variables, creating a session and running a tensorflow session init = tf.global_variables_initializer() sess = tf.Session() sess.run(init) #running gradient descent for each iteration and printing the hypothesis obtained using the updated theta values for i in range(100000): sess.run(optimiser, feed_dict = {x:X,y:Y})#setting place holder values using feed_dict if i%100==0: print("Epoch:",i) print("Hyp:",sess.run(h3,feed_dict = {x:X,y:Y}))
以上代码行生成的输出如下图所示 −
广告