之前我们介绍了Recurrent neural network (RNN) 的原理:

http://blog.csdn.net/matrix_space/article/details/53374040

http://blog.csdn.net/matrix_space/article/details/53376870  

这里,我们构建一个简单的RNN网络,激励函数我们用sigmoid 函数,利用这个网络,我们来测试二进制数的运算。网络重复模块的表达式是:

ht=σ(Wh⋅ht−1+Wi⋅Xt)
ot=σ(Wo⋅ht)
e=12(yt−ot)2
import copy, numpy as np

np.random.seed(0)

# compute sigmoid nonlinearity
# 定义sigmoid 函数
def sigmoid (x):
output = 1 / (1+np.exp(-x))
return output # convert output to sigmoid function to its derivative
# 定义sigmoid 函数的导数
def sigmoid_output_to_derivative(output):
return output*(1-output) # training dataset generation
# 生成训练集
int2binary = {}
binary_dim = 8
max_number = pow (2, binary_dim)
binary = np.unpackbits(np.array([range(max_number)], dtype=np.uint8).T, axis=1)
# np.unpackbits 是将一个uint8的数组元素都转换成0-1二进制形式,这里max_number 是256, 
# binary 里面一共存了0-255 共 256 个二进制数 for i in range(max_number):
int2binary[i]=binary[i] # input parameters
alpha = 0.1
input_dim = 2
hidden_dim = 16
output_dim = 1 # weight 的初始化
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) for j in range(10000):
# 生成一个0-128之间的随机数
# 获取这个数的二进制序列
a_int = np.random.randint(max_number/2)
a = int2binary [a_int]    b_int = np.random.randint(max_number/2)
b = int2binary [b_int] c_int = a_int + b_int
c = int2binary [c_int] 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      # 计算重复模块的隐含层的输入和输出
layer_1 = sigmoid(np.dot(X, synapse_0) + np.dot(layer_1_values[-1], synapse_h)) layer_2 = sigmoid(np.dot(layer_1, synapse_1))      # BP
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]) d[binary_dim-position-1] = np.round(layer_2[0][0]) 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]
pre_layer_1 = layer_1_values[-position-2] layer_2_delta = layer_2_deltas[-position-1] layer_1_delta = (future_layer_1_delta.dot(synapse_h.T) + layer_2_delta.dot(
synapse_1.T)) * sigmoid_output_to_derivative(layer_1) # weight update
synapse_1_update += np.atleast_2d(layer_1).T.dot(layer_2_delta)
synapse_h_update += np.atleast_2d(pre_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 % 500 == 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: ', '[ 4.02253884]')
('Pred:', '[0 1 1 0 1 0 1 1]')
('True:', '[1 0 0 0 0 0 0 1]')
112+17=107
---------------
('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.99234598]')
('Pred:', '[1 1 0 1 1 0 1 0]')
('True:', '[1 0 1 1 0 0 1 1]')
78+101=218
---------------
('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.65154804]')
('Pred:', '[1 1 0 1 1 0 1 0]')
('True:', '[1 1 0 1 1 1 1 0]')
122+100=218
---------------
('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.35048888]')
('Pred:', '[1 0 0 1 1 0 0 1]')
('True:', '[1 0 0 1 0 0 0 1]')
76+69=153
---------------
('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.43239777]')
('Pred:', '[0 1 1 0 1 0 1 1]')
('True:', '[0 1 1 0 1 0 1 1]')
72+35=107
---------------
('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: ', '[ 1.87382863]')
('Pred:', '[0 1 1 0 0 0 1 0]')
('True:', '[0 1 1 0 0 0 1 0]')
21+77=98
---------------
('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: ', '[ 0.75100965]')
('Pred:', '[0 0 1 1 1 1 0 0]')
('True:', '[0 0 1 1 1 1 0 0]')
49+11=60
---------------
('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.6594703]')
('Pred:', '[0 1 1 0 1 1 0 0]')
('True:', '[0 1 1 0 1 1 0 0]')
80+28=108
---------------
('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.7200904]')
('Pred:', '[1 0 1 0 1 0 0 0]')
('True:', '[1 0 1 0 1 0 0 0]')
123+45=168
---------------
('Error: ', '[ 0.21595037]')
('Pred:', '[0 0 0 0 1 1 1 0]')
('True:', '[0 0 0 0 1 1 1 0]')
11+3=14
---------------
('Error: ', '[ 0.52112049]')
('Pred:', '[1 0 1 0 1 0 1 1]')
('True:', '[1 0 1 0 1 0 1 1]')
71+100=171
---------------

参考来源:

https://github.com/llSourcell/recurrent_neural_net_demo

机器学习: Python with Recurrent Neural Network的更多相关文章

  1. Recurrent Neural Network系列2--利用Python,Theano实现RNN

    作者:zhbzz2007 出处:http://www.cnblogs.com/zhbzz2007 欢迎转载,也请保留这段声明.谢谢! 本文翻译自 RECURRENT NEURAL NETWORKS T ...

  2. Recurrent Neural Network系列4--利用Python,Theano实现GRU或LSTM

    yi作者:zhbzz2007 出处:http://www.cnblogs.com/zhbzz2007 欢迎转载,也请保留这段声明.谢谢! 本文翻译自 RECURRENT NEURAL NETWORK ...

  3. Recurrent Neural Network系列1--RNN(循环神经网络)概述

    作者:zhbzz2007 出处:http://www.cnblogs.com/zhbzz2007 欢迎转载,也请保留这段声明.谢谢! 本文翻译自 RECURRENT NEURAL NETWORKS T ...

  4. 课程五(Sequence Models),第一 周(Recurrent Neural Networks) —— 1.Programming assignments:Building a recurrent neural network - step by step

    Building your Recurrent Neural Network - Step by Step Welcome to Course 5's first assignment! In thi ...

  5. Recurrent Neural Network(递归神经网络)

    递归神经网络(RNN),是两种人工神经网络的总称,一种是时间递归神经网络(recurrent neural network),另一种是结构递归神经网络(recursive neural network ...

  6. Sequence Models Week 1 Building a recurrent neural network - step by step

    Building your Recurrent Neural Network - Step by Step Welcome to Course 5's first assignment! In thi ...

  7. Recurrent Neural Network(循环神经网络)

    Reference:   Alex Graves的[Supervised Sequence Labelling with RecurrentNeural Networks] Alex是RNN最著名变种 ...

  8. Recurrent Neural Network系列3--理解RNN的BPTT算法和梯度消失

    作者:zhbzz2007 出处:http://www.cnblogs.com/zhbzz2007 欢迎转载,也请保留这段声明.谢谢! 这是RNN教程的第三部分. 在前面的教程中,我们从头实现了一个循环 ...

  9. 循环神经网络(Recurrent Neural Network,RNN)

    为什么使用序列模型(sequence model)?标准的全连接神经网络(fully connected neural network)处理序列会有两个问题:1)全连接神经网络输入层和输出层长度固定, ...

随机推荐

  1. Centos配置java环境

    安装jdk JDK 是开发Java程序必须安装的软件,我们查看一下 yum 源里面的 JDK:yum list java* 选择适合本机的JDK,并安装:yum install java-1.7.0- ...

  2. 【Codeforces Round #185 (Div. 2) B】Archer

    [链接] 链接 [题意] 在这里输入题意 [题解] 概率水题. 枚举它是第几轮成功的. 直到满足精度就好 [错的次数] 1 [反思] long double最让人安心. [代码] #include & ...

  3. matlab 程序发布

    将matlab程序发布为可执行程序包 说明,这种可执行程序包可以在没有安装matlab的计算机上运行. 1. 打开Applicaiton Compler 如果下拉列表中没有这个APPLICATIOND ...

  4. Nginx content cache Nginx内容缓存

    原文地址:http://nginx.com/resources/admin-guide/caching/ Nginx content cache Nginx内容缓存 This chapter desc ...

  5. github-vimium-compile-crx

    chrome-62.x版本上安装vimium 1.61.1 https://blog.csdn.net/ZHUJIANWEILI4/article/details/78385346

  6. 简单的Java多线程的使用

    前几天做一个功能.就是在前台更改信息后会自己主动发邮件给其它的人,相关信息已更改,刚開始是直接在更改信息代码后面增加发送邮件的代码,但发现这样会使界面特别慢,而慢的主要原因是因为发送邮件有时会耗时非常 ...

  7. 在word中使用notepad++实现代码的语法高亮 分类: C_OHTERS 2013-09-22 10:38 2273人阅读 评论(0) 收藏

    转载自:http://blog.csdn.net/woohello/article/details/7621651 有时写文档时需要将代码粘贴到word中,但直接粘贴到word中的代码虽能保持换行与缩 ...

  8. 应用 Valgrind 发现 Linux 程序的内存问题及交叉编译for arm

    Valgrind 概述 体系结构 Valgrind是一套Linux下,开放源代码(GPL V2)的仿真调试工具的集合.Valgrind由内核(core)以及基于内核的其他调试工具组成.内核类似于一个框 ...

  9. Windows环境搭建Web自己主动化測试框架Watir(基于Ruby)

    web自己主动化測试一直是一个比較迫切的问题 图1-1 须要安装的工具 http://railsinstaller.org/ 由于安装Ruby还须要用到其它的一些开发工具集.所以建议从站点http:/ ...

  10. 前端开发必备调试工具(Chrome的F12自带的功能和firebug插件差不多)

    前端开发必备调试工具(Chrome的F12自带的功能和firebug插件差不多) 一.总结 Chrome的F12自带的功能和firebug插件差不多 二.前端开发必备调试工具 在前端开发中我们经常会要 ...