Python实现的递归神经网络简单示例


Posted in Python onAugust 11, 2017

本文实例讲述了Python实现的递归神经网络。分享给大家供大家参考,具体如下:

# Recurrent Neural Networks
import copy, numpy as np
np.random.seed(0)
# compute sigmoid nonlinearity
def sigmoid(x):
  output = 1/(1+np.exp(-x))
  return output
# convert output of sigmoid function to its derivative
def sigmoid_output_to_derivative(output):
  return output*(1-output)
# training dataset generation
int2binary = {}
binary_dim = 8
largest_number = pow(2,binary_dim)
binary = np.unpackbits(
  np.array([range(largest_number)],dtype=np.uint8).T,axis=1)
for i in range(largest_number):
  int2binary[i] = binary[i]
# input variables
alpha = 0.1
input_dim = 2
hidden_dim = 16
output_dim = 1
# initialize neural network weights
synapse_0 = 2*np.random.random((input_dim,hidden_dim)) - 1
synapse_1 = 2*np.random.random((hidden_dim,output_dim)) - 1
synapse_h = 2*np.random.random((hidden_dim,hidden_dim)) - 1
synapse_0_update = np.zeros_like(synapse_0)
synapse_1_update = np.zeros_like(synapse_1)
synapse_h_update = np.zeros_like(synapse_h)
# training logic
for j in range(10000):
  # generate a simple addition problem (a + b = c)
  a_int = np.random.randint(largest_number/2) # int version
  a = int2binary[a_int] # binary encoding
  b_int = np.random.randint(largest_number/2) # int version
  b = int2binary[b_int] # binary encoding
  # true answer
  c_int = a_int + b_int
  c = int2binary[c_int]
  # where we'll store our best guess (binary encoded)
  d = np.zeros_like(c)
  overallError = 0
  layer_2_deltas = list()
  layer_1_values = list()
  layer_1_values.append(np.zeros(hidden_dim))
  # moving along the positions in the binary encoding
  for position in range(binary_dim):
    # generate input and output
    X = np.array([[a[binary_dim - position - 1],b[binary_dim - position - 1]]])
    y = np.array([[c[binary_dim - position - 1]]]).T
    # hidden layer (input ~+ prev_hidden)
    layer_1 = sigmoid(np.dot(X,synapse_0) + np.dot(layer_1_values[-1],synapse_h))
    # output layer (new binary representation)
    layer_2 = sigmoid(np.dot(layer_1,synapse_1))
    # did we miss?... if so, by how much?
    layer_2_error = y - layer_2
    layer_2_deltas.append((layer_2_error)*sigmoid_output_to_derivative(layer_2))
    overallError += np.abs(layer_2_error[0])
    # decode estimate so we can print(it out)
    d[binary_dim - position - 1] = np.round(layer_2[0][0])
    # store hidden layer so we can use it in the next timestep
    layer_1_values.append(copy.deepcopy(layer_1))
  future_layer_1_delta = np.zeros(hidden_dim)
  for position in range(binary_dim):
    X = np.array([[a[position],b[position]]])
    layer_1 = layer_1_values[-position-1]
    prev_layer_1 = layer_1_values[-position-2]
    # error at output layer
    layer_2_delta = layer_2_deltas[-position-1]
    # error at hidden layer
    layer_1_delta = (future_layer_1_delta.dot(synapse_h.T) + layer_2_delta.dot(synapse_1.T)) * sigmoid_output_to_derivative(layer_1)
    # let's update all our weights so we can try again
    synapse_1_update += np.atleast_2d(layer_1).T.dot(layer_2_delta)
    synapse_h_update += np.atleast_2d(prev_layer_1).T.dot(layer_1_delta)
    synapse_0_update += X.T.dot(layer_1_delta)
    future_layer_1_delta = layer_1_delta
  synapse_0 += synapse_0_update * alpha
  synapse_1 += synapse_1_update * alpha
  synapse_h += synapse_h_update * alpha
  synapse_0_update *= 0
  synapse_1_update *= 0
  synapse_h_update *= 0
  # print(out progress)
  if j % 1000 == 0:
    print("Error:" + str(overallError))
    print("Pred:" + str(d))
    print("True:" + str(c))
    out = 0
    for index,x in enumerate(reversed(d)):
      out += x*pow(2,index)
    print(str(a_int) + " + " + str(b_int) + " = " + str(out))
    print("------------")

运行输出:

Error:[ 3.45638663]
Pred:[0 0 0 0 0 0 0 1]
True:[0 1 0 0 0 1 0 1]
9 + 60 = 1
------------
Error:[ 3.63389116]
Pred:[1 1 1 1 1 1 1 1]
True:[0 0 1 1 1 1 1 1]
28 + 35 = 255
------------
Error:[ 3.91366595]
Pred:[0 1 0 0 1 0 0 0]
True:[1 0 1 0 0 0 0 0]
116 + 44 = 72
------------
Error:[ 3.72191702]
Pred:[1 1 0 1 1 1 1 1]
True:[0 1 0 0 1 1 0 1]
4 + 73 = 223
------------
Error:[ 3.5852713]
Pred:[0 0 0 0 1 0 0 0]
True:[0 1 0 1 0 0 1 0]
71 + 11 = 8
------------
Error:[ 2.53352328]
Pred:[1 0 1 0 0 0 1 0]
True:[1 1 0 0 0 0 1 0]
81 + 113 = 162
------------
Error:[ 0.57691441]
Pred:[0 1 0 1 0 0 0 1]
True:[0 1 0 1 0 0 0 1]
81 + 0 = 81
------------
Error:[ 1.42589952]
Pred:[1 0 0 0 0 0 0 1]
True:[1 0 0 0 0 0 0 1]
4 + 125 = 129
------------
Error:[ 0.47477457]
Pred:[0 0 1 1 1 0 0 0]
True:[0 0 1 1 1 0 0 0]
39 + 17 = 56
------------
Error:[ 0.21595037]
Pred:[0 0 0 0 1 1 1 0]
True:[0 0 0 0 1 1 1 0]
11 + 3 = 14
------------

英文原文:https://iamtrask.github.io/2015/11/15/anyone-can-code-lstm/

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
python list中append()与extend()用法分享
Mar 24 Python
Python 由字符串函数名得到对应的函数(实例讲解)
Aug 10 Python
Python基于回溯法子集树模板解决数字组合问题实例
Sep 02 Python
基于Python中单例模式的几种实现方式及优化详解
Jan 09 Python
python爬虫正则表达式之处理换行符
Jun 08 Python
python 将列表中的字符串连接成一个长路径的方法
Oct 23 Python
python获取Pandas列名的几种方法
Aug 07 Python
python支付宝支付示例详解
Aug 22 Python
tensorflow多维张量计算实例
Feb 11 Python
基于Python pyecharts实现多种图例代码解析
Aug 10 Python
python 下划线的不同用法
Oct 24 Python
python如何编写类似nmap的扫描工具
Nov 06 Python
Python调用系统底层API播放wav文件的方法
Aug 11 #Python
Django 导出 Excel 代码的实例详解
Aug 11 #Python
python技能之数据导出excel的实例代码
Aug 11 #Python
利用标准库fractions模块让Python支持分数类型的方法详解
Aug 11 #Python
Python对字符串实现去重操作的方法示例
Aug 11 #Python
python中模块查找的原理与方法详解
Aug 11 #Python
python利用lxml读写xml格式的文件
Aug 10 #Python
You might like
ADODB的数据库封包程序库
2006/12/31 PHP
php面向对象全攻略 (二) 实例化对象 使用对象成员
2009/09/30 PHP
php htmlspecialchars()与shtmlspecialchars()函数的深入分析
2013/06/05 PHP
[原创]php简单防盗链验证实现方法
2016/07/09 PHP
YII框架批量插入数据的方法
2017/03/18 PHP
Laravel框架查询构造器 CURD操作示例
2019/09/04 PHP
Laravel框架Eloquent ORM删除数据操作示例
2019/12/03 PHP
Web层改进II-用xmlhttp 无声息提交复杂表单
2007/01/22 Javascript
javascript 学习笔记(八)javascript对象
2011/04/12 Javascript
Bootstrap导航条可点击和鼠标悬停显示下拉菜单的实现代码
2016/06/23 Javascript
angular中不同的组件间传值与通信的方法
2017/11/04 Javascript
vue的一个分页组件的示例代码
2017/12/25 Javascript
vue better scroll 无法滚动的解决方法
2018/06/07 Javascript
JavaScript监听键盘事件代码实现
2020/06/03 Javascript
python中stdout输出不缓存的设置方法
2014/05/29 Python
详解 Python中LEGB和闭包及装饰器
2017/08/03 Python
Python排序搜索基本算法之归并排序实例分析
2017/12/08 Python
在CentOS6上安装Python2.7的解决方法
2018/01/09 Python
Python cookbook(数据结构与算法)将名称映射到序列元素中的方法
2018/03/22 Python
DES加密解密算法之python实现版(图文并茂)
2018/12/06 Python
Django框架验证码用法实例分析
2019/05/10 Python
Python基于机器学习方法实现的电影推荐系统实例详解
2019/06/25 Python
Python实现二叉搜索树BST的方法示例
2019/07/30 Python
将python安装信息加入注册表的示例
2019/11/20 Python
CSS3之边框多颜色Border-color属性使用示例
2013/10/11 HTML / CSS
英国第一蛋白粉品牌:Myprotein
2016/09/14 全球购物
学生党员思想汇报
2013/12/28 职场文书
承诺书范文
2014/06/03 职场文书
社区志愿者活动总结
2014/06/26 职场文书
本科毕业生应聘求职信
2014/07/06 职场文书
领导班子个人对照检查剖析材料
2014/09/29 职场文书
人身损害赔偿协议书格式
2014/11/01 职场文书
干部培训简讯
2015/07/20 职场文书
祝福语集锦:朋友新店开业祝福语
2019/12/10 职场文书
Python的三个重要函数详解
2022/01/18 Python
漫画「狩龙人拉格纳」公开TV动画预告图
2022/03/22 日漫