递归神经网络(LSTM)

时间:2016-02-27 21:05:33

标签: python neural-network lstm recurrent-neural-network

来自an exampleElman Recurrent Neural Network使用Neurolab Python Library

import neurolab as nl
import numpy as np

# Create train samples
i1 = np.sin(np.arange(0, 20))
i2 = np.sin(np.arange(0, 20)) * 2

t1 = np.ones([1, 20])
t2 = np.ones([1, 20]) * 2

input = np.array([i1, i2, i1, i2]).reshape(20 * 4, 1)
target = np.array([t1, t2, t1, t2]).reshape(20 * 4, 1)

# Create network with 2 layers
net = nl.net.newelm([[-2, 2]], [10, 1], [nl.trans.TanSig(), nl.trans.PureLin()])
# Set initialized functions and init
net.layers[0].initf = nl.init.InitRand([-0.1, 0.1], 'wb')
net.layers[1].initf= nl.init.InitRand([-0.1, 0.1], 'wb')
net.init()
# Train network
error = net.train(input, target, epochs=500, show=100, goal=0.01)
# Simulate network
output = net.sim(input)

# Plot result
import pylab as pl
pl.subplot(211)
pl.plot(error)
pl.xlabel('Epoch number')
pl.ylabel('Train error (default MSE)')

pl.subplot(212)
pl.plot(target.reshape(80))
pl.plot(output.reshape(80))
pl.legend(['train target', 'net output'])
pl.show()

在此示例中,合并 2单位长度输入,并且它合并 2单位长度输出。之后,它使用这些合并数组来训练网络。

首先,它似乎不是我从here得到的架构:

enter image description here

我的主要问题是;

我必须使用任意长度的 输入输出来训练网络,如下所示:

  • 固定长度输出的任意长度输入
  • 固定长度输入到任意长度输出
  • 任意长度输入到任意长度输出

此时您会想到:“您的答案是Long short-term memory networks。”

我知道但Neurolab很容易使用,因为它是good features。特别是,它非常 Pythonic 。所以我坚持使用 Neurolab Library 解决我的问题。但是如果你建议我另一个库像Neurolab那样具有更好的LSTM功能,我会接受它

最终,如何针对任意长度的输入和输出重新排列此示例?

我对RNN和LSTM没有最好的理解,所以请解释一下。

1 个答案:

答案 0 :(得分:1)

经过很长一段时间,当我今天看到我的这个问题时,我可以看到这是一个对神经网络缺乏了解的人的问题。

矩阵乘法是神经网络核心的基本数学。您不能简单地更改输入矩阵的形状,因为它会改变产品的形状并破坏数据集之间的一致性。

神经网络始终以固定长度的输入和输出进行训练。这是一个非常简单的神经网络实现,只使用numpy的点积来提供前馈:

import numpy as np

# sigmoid function
def nonlin(x,deriv=False):
    if(deriv==True):
        return x*(1-x)
    return 1/(1+np.exp(-x))

# input dataset
X = np.array([  [0,0,1],
                [0,1,1],
                [1,0,1],
                [1,1,1] ])

# output dataset            
y = np.array([[0,0,1,1]]).T

# seed random numbers to make calculation
# deterministic (just a good practice)
np.random.seed(1)

# initialize weights randomly with mean 0
syn0 = 2*np.random.random((3,1)) - 1

for iter in xrange(10000):

    # forward propagation
    l0 = X
    l1 = nonlin(np.dot(l0,syn0))

    # how much did we miss?
    l1_error = y - l1

    # multiply how much we missed by the 
    # slope of the sigmoid at the values in l1
    l1_delta = l1_error * nonlin(l1,True)

    # update weights
    syn0 += np.dot(l0.T,l1_delta)

print "Output After Training:"
print l1

信用:http://iamtrask.github.io/2015/07/12/basic-python-network/

相关问题