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发送邮件实例讲解(python发邮件附件可以使用email模块实现)
Dec 03 Python
python网络编程之UDP通信实例(含服务器端、客户端、UDP广播例子)
Apr 25 Python
Python greenlet实现原理和使用示例
Sep 24 Python
python读写二进制文件的方法
May 09 Python
python numpy函数中的linspace创建等差数列详解
Oct 13 Python
解决Python 使用h5py加载文件,看不到keys()的问题
Feb 08 Python
pycharm修改文件的默认打开方式的步骤
Jul 29 Python
tensorflow使用L2 regularization正则化修正overfitting过拟合方式
May 22 Python
python excel多行合并的方法
Dec 09 Python
Python 制作自动化翻译工具
Apr 25 Python
Python的这些库,你知道多少?
Jun 09 Python
Python借助with语句实现代码段只执行有限次
Mar 23 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压缩HTML函数轻松实现压缩html/js/Css及注意事项
2013/01/27 PHP
PHP实现视频文件上传完整实例
2014/08/28 PHP
PHP中array_slice函数用法实例详解
2014/11/25 PHP
Javascript中eval函数的使用方法与示例
2007/04/09 Javascript
JavaScript 编程引入命名空间的方法与代码
2007/08/13 Javascript
jQuery 学习 几种常用方法
2009/06/11 Javascript
跨域表单提交状态的变相判断代码
2009/11/12 Javascript
解析jQuery与其它js(Prototype)库兼容共存
2013/07/04 Javascript
js的alert样式如何更改如背景颜色
2014/01/22 Javascript
JavaScript中的console.group()函数详细介绍
2014/12/29 Javascript
jQuery制作仿Mac Lion OS滚动条效果
2015/02/10 Javascript
js使用post 方式打开新窗口
2015/02/26 Javascript
bootstrapValidator自定验证方法写法
2016/12/01 Javascript
关于angular js_$watch监控属性和对象详解
2017/04/24 Javascript
vue 表单之通过v-model绑定单选按钮radio
2019/05/13 Javascript
微信小程序实现页面浮动导航
2020/01/08 Javascript
在博客园博文中添加自定义右键菜单的方法详解
2020/02/05 Javascript
Vue 同步异步存值取值实现案例
2020/08/05 Javascript
JavaScript实现缓动动画
2020/11/25 Javascript
Python获取暗黑破坏神3战网前1000命位玩家的英雄技能统计
2016/07/04 Python
python中使用%与.format格式化文本方法解析
2017/12/27 Python
python快速编写单行注释多行注释的方法
2019/07/31 Python
python读取dicom图像示例(SimpleITK和dicom包实现)
2020/01/16 Python
基于python实现可视化生成二维码工具
2020/07/08 Python
Python Unittest原理及基本使用方法
2020/11/06 Python
python 解决Windows平台上路径有空格的问题
2020/11/10 Python
CSS3 旋转立方体问题详解
2020/01/09 HTML / CSS
HTML5的postMessage的使用手册
2018/12/19 HTML / CSS
德国汽车零件和汽车配件网上商店:kfzteile24
2018/11/14 全球购物
网络管理员岗位职责
2014/03/17 职场文书
合作意向书范本
2014/03/31 职场文书
杨善洲观后感
2015/06/04 职场文书
2015年行政管理人员工作总结
2015/10/15 职场文书
2016年师德师风学习心得体会
2016/01/12 职场文书
Python 实现Mac 屏幕截图详解
2021/10/05 Python
VW、VH适配移动端的解决方案与常见问题
2023/05/21 HTML / CSS