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批量导出导入MySQL用户的方法
Nov 15 Python
Python深入学习之上下文管理器
Aug 31 Python
Python在Console下显示文本进度条的方法
Feb 14 Python
Python如何import文件夹下的文件(实现方法)
Jan 24 Python
Python3中bytes类型转换为str类型
Sep 27 Python
Python命名空间的本质和加载顺序
Dec 17 Python
Python离线安装PIL 模块的方法
Jan 08 Python
Python实现平行坐标图的两种方法小结
Jul 04 Python
Python3 执行系统命令并获取实时回显功能
Jul 09 Python
pytorch 加载(.pth)格式的模型实例
Aug 20 Python
Django 简单实现分页与搜索功能的示例代码
Nov 07 Python
基于Python+QT的gui程序开发实现
Jul 03 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
php简单浏览目录内容的实现代码
2013/06/07 PHP
php计算2个日期的差值函数分享
2015/02/02 PHP
PHP实现的数独求解问题示例
2017/04/18 PHP
php识别翻转iphone拍摄的颠倒图片
2018/05/17 PHP
面向对象Javascript核心支持代码分享
2012/05/23 Javascript
javascript表单验证 - Parsley.js使用和配置
2013/01/25 Javascript
js和as的稳定传值问题解决
2013/07/14 Javascript
jquery二级导航内容均分的原理及实现
2013/08/13 Javascript
jquery ajax对特殊字符进行转义防止js注入使用示例
2013/11/21 Javascript
js日期对象兼容性的处理方法
2014/01/28 Javascript
JQuery 实现在同一页面锚点链接之间的平滑滚动
2014/10/29 Javascript
jQuery对象的selector属性用法实例
2014/12/27 Javascript
纯javascript实现四方向文本无缝滚动效果
2015/06/16 Javascript
原生js实现吸顶效果
2017/03/13 Javascript
nodejs中向HTTP响应传送进程的输出
2017/03/19 NodeJs
vue.js删除动态绑定的radio的指定项
2017/06/02 Javascript
微信小程序 监听手势滑动切换页面实例详解
2017/06/15 Javascript
Node.js中环境变量process.env的一些事详解
2017/10/26 Javascript
使用veloticy-ui生成文字动画效果
2018/02/08 Javascript
详解React+Koa实现服务端渲染(SSR)
2018/05/23 Javascript
JavaScript设计模式之装饰者模式实例详解
2019/01/17 Javascript
微信小程序的tab选项卡的实现效果
2019/05/15 Javascript
实现一个 Vue 吸顶锚点组件方法
2019/07/10 Javascript
[50:44]DOTA2-DPC中国联赛 正赛 SAG vs Dragon BO3 第二场 2月22日
2021/03/11 DOTA
Python Tkinter基础控件用法
2014/09/03 Python
完美解决python遍历删除字典里值为空的元素报错问题
2016/09/11 Python
python用plt画图时,cmp设置方法
2018/12/13 Python
python使用pipeline批量读写redis的方法
2019/02/18 Python
python文件读写代码实例
2019/10/21 Python
如何基于Python按行合并两个txt
2020/11/03 Python
自我评价优秀范文分享
2013/11/30 职场文书
商务日语专业毕业生自荐信
2014/03/27 职场文书
慈善晚会策划方案
2014/05/14 职场文书
重大事项社会稳定风险评估方案
2014/06/15 职场文书
2015年大学学生会工作总结
2015/05/13 职场文书
生产车间管理制度
2015/08/04 职场文书