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-基础-入门 简介
Aug 09 Python
Python提示[Errno 32]Broken pipe导致线程crash错误解决方法
Nov 19 Python
python生成excel的实例代码
Nov 08 Python
Python实现动态图解析、合成与倒放
Jan 18 Python
Python将文本去空格并保存到txt文件中的实例
Jul 24 Python
tensorflow实现图像的裁剪和填充方法
Jul 27 Python
pycharm安装和首次使用教程
Aug 27 Python
解决每次打开pycharm直接进入项目的问题
Oct 28 Python
python爬取指定微信公众号文章
Dec 20 Python
Python内置random模块生成随机数的方法
May 31 Python
pytest fixtures装饰器的使用和如何控制用例的执行顺序
Jan 28 Python
python读取excel数据并且画图的实现示例
Feb 08 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
用cookies来跟踪识别用户
2006/10/09 PHP
第十三节--对象串行化
2006/11/16 PHP
PHP $_SERVER详解
2009/01/16 PHP
精美漂亮的php分页类代码
2013/04/02 PHP
php生成随机密码自定义函数代码(简单快速)
2014/05/10 PHP
PHP获取时间排除周六、周日的两个方法
2014/06/30 PHP
php搜索文件程序分享
2015/10/30 PHP
laravel 中如何使用ajax和vue总结
2017/08/16 PHP
TP5框架实现一次选择多张图片并预览的方法示例
2020/04/04 PHP
使用RequireJS优化JavaScript引用代码的方法
2015/07/01 Javascript
javascript+html5实现绘制圆环的方法
2015/07/28 Javascript
ajax在兼容模式下失效的快速解决方法
2016/03/22 Javascript
jQuery EasyUI 组件加上“清除”功能实例详解
2017/04/11 jQuery
vue动态生成dom并且自动绑定事件
2017/04/19 Javascript
AngularJS实现根据不同条件显示不同控件
2017/04/20 Javascript
react-router4 嵌套路由的使用方法
2017/07/24 Javascript
微信小程序时间戳转日期的详解
2019/04/30 Javascript
jQuery属性选择器用法实例分析
2019/06/28 jQuery
layui 根据后台数据动态创建下拉框并同时默认选中的实例
2019/09/02 Javascript
深度剖析使用python抓取网页正文的源码
2014/06/11 Python
Python中防止sql注入的方法详解
2017/02/25 Python
Python语言描述连续子数组的最大和
2018/01/04 Python
详解numpy的argmax的具体使用
2019/05/27 Python
python爬虫神器Pyppeteer入门及使用
2019/07/13 Python
pip安装python库的方法总结
2019/08/02 Python
H5页面适配iPhoneX(就是那么简单)
2019/12/02 HTML / CSS
MCM英国官网:奢侈皮具制品
2017/04/18 全球购物
精美的手工家居和生活用品:Nkuku
2019/11/01 全球购物
求职简历自荐信范文
2013/10/21 职场文书
怎样客观的做好自我评价
2013/12/28 职场文书
消防安全员岗位职责
2014/03/10 职场文书
工作作风承诺书
2014/08/30 职场文书
中班下学期幼儿评语
2014/12/30 职场文书
小学一年级语文教学反思
2016/03/03 职场文书
七年级作文(600字3篇)
2019/09/24 职场文书
Golang全局变量加锁的问题解决
2021/05/08 Golang