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 THREADING模块中的JOIN()方法深入理解
Feb 18 Python
在树莓派2或树莓派B+上安装Python和OpenCV的教程
Mar 30 Python
Python的__builtin__模块中的一些要点知识
May 02 Python
Python爬虫爬验证码实现功能详解
Apr 14 Python
python读取二进制mnist实例详解
May 31 Python
解决PyCharm中光标变粗的问题
Aug 05 Python
在Python中pandas.DataFrame重置索引名称的实例
Nov 06 Python
python在回调函数中获取返回值的方法
Feb 22 Python
在python中实现调用可执行文件.exe的3种方法
Jul 07 Python
Python super()函数使用及多重继承
May 06 Python
python 多线程共享全局变量的优劣
Sep 24 Python
Python批量修改xml的坐标值全部转为整数的实例代码
Nov 26 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
收音机鉴频器对声音的影响和频偏分析
2021/03/02 无线电
php排序算法(冒泡排序,快速排序)
2012/10/09 PHP
微信公众号开发之微信公共平台消息回复类实例
2014/11/14 PHP
功能强大的php分页函数
2016/07/20 PHP
PHP常用的三种设计模式汇总
2016/08/28 PHP
PHP导出带样式的Excel示例代码
2016/08/28 PHP
通过判断JavaScript的版本实现执行不同的代码
2010/05/11 Javascript
js TextArea的选中区域处理
2010/12/28 Javascript
jQuery EasyUI API 中文文档 - DataGrid数据表格
2011/11/17 Javascript
JavaScript 参数中的数组展开 [译]
2012/09/21 Javascript
通过onmouseover选项卡实现img图片的变化
2014/02/12 Javascript
JS对img标签进行优化使用onerror显示默认图像
2014/04/24 Javascript
jquery调取json数据实现省市级联的方法
2015/01/29 Javascript
JavaScript轮播图简单制作方法
2017/02/20 Javascript
JavaScript错误处理和堆栈追踪详解
2017/04/18 Javascript
JS匹配日期和时间的正则表达式示例
2017/05/12 Javascript
日期时间范围选择插件:daterangepicker使用总结(必看篇)
2017/09/14 Javascript
详解RequireJs官方使用教程
2017/10/31 Javascript
vue 实现复制内容到粘贴板clipboard的方法
2018/03/17 Javascript
小程序自定义单页面、全局导航栏的实现代码
2019/03/15 Javascript
教你使用vue-cli快速构建的小说阅读器
2019/05/13 Javascript
vue自定义指令和动态路由实现权限控制
2020/08/28 Javascript
Python修改MP3文件的方法
2015/06/15 Python
简单解析Django框架中的表单验证
2015/07/17 Python
Python中对象迭代与反迭代的技巧总结
2016/09/17 Python
基于python的socket实现单机五子棋到双人对战
2020/03/24 Python
Django models文件模型变更错误解决
2020/05/11 Python
Python中openpyxl实现vlookup函数的实例
2020/10/28 Python
Html5 Geolocation获取地理位置信息实例
2016/12/09 HTML / CSS
TripAdvisor西班牙官方网站:全球领先的旅游网站
2018/01/10 全球购物
法警的竞聘演讲稿
2014/01/02 职场文书
教师节学生演讲稿
2014/09/03 职场文书
银行求职自荐信范文
2015/03/04 职场文书
2015年施工员工作总结范文
2015/04/20 职场文书
小学见习报告
2015/06/23 职场文书
MySQL高速缓存启动方法及参数详解(query_cache_size)
2021/07/01 MySQL