-
python实现循环神经网络RNN
2019-08-02 11:18:44python实现循环神经网络 1 生成一些数据 2 定义激活函数 3训练Softmax线性分类器 3.1 初始化参数 3.2 计算得分 3.3 计算损失 3.4 用反向传播计算分析梯度 3.5 执行参数更新 3.6 测试训练正确率 4 训练神经...目录
python实现循环神经网络
python实现循环神经网络
1 生成一些数据
让我们生成一个不易线性分离的分类数据集。我们最喜欢的例子是螺旋数据集,可以按如下方式生成
#玩具螺旋数据由三个类别(蓝色,红色,黄色)组成,这些类别不是线性可分的。
N = 100 # number of points per class
D = 2 # dimensionality
K = 3 # number of classes
X = np.zeros((N*K,D)) # data matrix (each row = single example)
y = np.zeros(N*K, dtype='uint8') # class labels
for j in range(K):
ix = range(N*j,N*(j+1))
r = np.linspace(0.0,1,N) # radius
t = np.linspace(j*4,(j+1)*4,N) + np.random.randn(N)*0.2 # theta
X[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
y[ix] = j
# lets visualize the data:
plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)
plt.show()
2 定义激活函数
sigmoid函数“压缩”输入位于0和1之间。不幸的是,这意味着对于sigmoid输出接近0或1的输入,相对于这些输入的梯度接近于零。这导致梯度消失的现象,其中梯度下降接近于零,并且网络不能很好地学习。
另一方面,relu函数(max(0,x))不会随输入大小而饱和。
#sigmoid函数“压缩”输入位于0和1之间。不幸的是,这意味着对于sigmoid输出接近0或1的输入,相对于这些输入的梯度接近于零。
#这导致梯度消失的现象,其中梯度下降接近于零,并且网络不能很好地学习。
def sigmoid(x):
x = 1/(1+np.exp(-x))
return x
def sigmoid_grad(x):
return (x)*(1-x)
#relu函数(max(0,x))不会随输入大小而饱和
def relu(x):
return np.maximum(0,x)
3 训练Softmax线性分类器
我们构建一个非常简单的神经网络,有三层(两个隐藏层),您可以换掉ReLU / sigmoid非线性。
定义函数:
def three_layer_net(NONLINEARITY,X,y, model, step_size, reg):
3.1 初始化参数
Softmax分类器具有线性分数函数并使用交叉熵损失。线性分类器的参数由权重矩阵W和b每个类的偏置向量组成。
#parameter initialization
h= model['h']
h2= model['h2']
W1= model['W1']
W2= model['W2']
W3= model['W3']
b1= model['b1']
b2= model['b2']
b3= model['b3']
# some hyperparameter
# 梯度下降
num_examples = X.shape[0]
plot_array_1=[]
plot_array_2=[]
3.2 计算得分
由于这是一个线性分类器,我们可以非常简单地与单个矩阵乘法并行计算所有类别得分:
for i in range(50000):
#前向传播
if NONLINEARITY== 'RELU':
hidden_layer = relu(np.dot(X, W1) + b1)
hidden_layer2 = relu(np.dot(hidden_layer, W2) + b2)
scores = np.dot(hidden_layer2, W3) + b3
elif NONLINEARITY == 'SIGM':
hidden_layer = sigmoid(np.dot(X, W1) + b1)
hidden_layer2 = sigmoid(np.dot(hidden_layer, W2) + b2)
scores = np.dot(hidden_layer2, W3) + b3
在这个例子中,我们有300个2-D点,所以在这个乘法之后,数组scores将具有[300 x 3]的大小,其中每行给出对应于3个类(蓝色,红色,黄色)的类分数。
3.3 计算损失
我们需要的第二个关键因素是损失函数,它是一个可微目标,可以量化我们对计算出的班级分数的不满意程度。直观地说,我们希望正确的类比其他类得分更高。在这种情况下,损失应该很低,否则损失应该很高。有很多方法可以量化这种直觉,但是在这个例子中,让我们使用与Softmax分类器相关的交叉熵损失。回想一下,如果f是单个例子的类分数数组(例如这里的3个数数组),那么Softmax分类器计算该例子的损失为:
我们可以看到Softmax分类器将f的每个元素解释为持有这三个类的(非规范化)对数概率。我们将这些取幂得到(非标准化的)概率,然后将它们标准化得到概率。因此,log中的表达式是正确类的归一化概率。注意这个表达式的工作原理:这个量总是在0和1之间。当正确类的概率非常小(接近于0)时,损失将趋于(正)无穷大。相反,当正确的类概率趋近于1时,损失将趋近于零,因为log(1)=0。因此,当正确的类概率高时,Li的表达式值是低的,当正确的类概率低时,Li的表达式值是非常高的。
完整的Softmax分类器损失被定义为训练实例和正则化之间的平均交叉熵损失:
给定我们上面计算的分数数组,我们可以计算损失。首先,得到概率的方法很简单:
- 计算损失:
#计算损失
#probs大小为[300 x 3] 的数组,其中每行现在包含类概率
exp_scores = np.exp(scores)
probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) # [N x K]
- 我们现在有一个probs大小为[300 x 3] 的数组,其中每行现在包含类概率。特别是,因为我们已将它们标准化,现在每一行总和为一。我们现在可以在每个示例中查询分配给正确类的对数概率:
corect_logprobs = -np.log(probs[range(num_examples),y])
data_loss = np.sum(corect_logprobs)/num_examples
- 该数组correct_logprobs是一维数组,仅包含为每个示例分配给正确类的概率。那么完全损失就是这些对数概率的平均值和正则化损失的和:
reg_loss = 0.5*reg*np.sum(W1*W1) + 0.5*reg*np.sum(W2*W2)+ 0.5*reg*np.sum(W3*W3)
loss = data_loss + reg_loss
3.4 用反向传播计算分析梯度
我们有一种估算损失的方法,现在我们要把它最小化。我们用梯度下降法。也就是说,我们从随机参数开始,计算损失函数相对于参数的梯度,这样我们就知道应该如何改变参数来减少损失。让我们引入中间变量p,它是(标准化)概率的一个向量。
利用链式法则求得:
假设我们计算的概率是p =[0.2, 0.3, 0.5],正确的类是中间类(概率为0.3)。根据这个推导,得分的梯度为df =[0.2, -0.7, 0.5]. 增加的第一个和最后一个元素得分向量f(错误的分数类),会增加损失(由于积极迹象+ 0.2 + 0.5)不好,因此需增加损失损失,而增加正确的班级分数对损失有负面影响。
# compute the gradient on scores
dscores = probs
dscores[range(num_examples),y] -= 1
dscores /= num_examples
反向传播:
# BACKPROP HERE
dW3 = (hidden_layer2.T).dot(dscores)
db3 = np.sum(dscores, axis=0, keepdims=True)
if NONLINEARITY == 'RELU':
#backprop ReLU nonlinearity here
dhidden2 = np.dot(dscores, W3.T)
dhidden2[hidden_layer2 <= 0] = 0
dW2 = np.dot( hidden_layer.T, dhidden2)
plot_array_2.append(np.sum(np.abs(dW2))/np.sum(np.abs(dW2.shape)))
db2 = np.sum(dhidden2, axis=0)
dhidden = np.dot(dhidden2, W2.T)
dhidden[hidden_layer <= 0] = 0
elif NONLINEARITY == 'SIGM':
#backprop sigmoid nonlinearity here
dhidden2 = dscores.dot(W3.T)*sigmoid_grad(hidden_layer2)
dW2 = (hidden_layer.T).dot(dhidden2)
plot_array_2.append(np.sum(np.abs(dW2))/np.sum(np.abs(dW2.shape)))
db2 = np.sum(dhidden2, axis=0)
dhidden = dhidden2.dot(W2.T)*sigmoid_grad(hidden_layer)
dW1 = np.dot(X.T, dhidden)
plot_array_1.append(np.sum(np.abs(dW1))/np.sum(np.abs(dW1.shape)))
db1 = np.sum(dhidden, axis=0)
# add regularization
dW3+= reg * W3
dW2 += reg * W2
dW1 += reg * W1
#option to return loss, grads -- uncomment next comment
grads={}
grads['W1']=dW1
grads['W2']=dW2
grads['W3']=dW3
grads['b1']=db1
grads['b2']=db2
grads['b3']=db3
#return loss, grads
3.5 执行参数更新
现在我们已经计算了梯度我们知道了每个参数如何影响损失函数。我们现在将在负梯度方向进行参数更新,以减少损耗:
# update
W1 += -step_size * dW1
b1 += -step_size * db1
W2 += -step_size * dW2
b2 += -step_size * db2
W3 += -step_size * dW3
b3 += -step_size * db3
3.6 测试训练正确率
# evaluate training set accuracy
if NONLINEARITY == 'RELU':
hidden_layer = relu(np.dot(X, W1) + b1)
hidden_layer2 = relu(np.dot(hidden_layer, W2) + b2)
elif NONLINEARITY == 'SIGM':
hidden_layer = sigmoid(np.dot(X, W1) + b1)
hidden_layer2 = sigmoid(np.dot(hidden_layer, W2) + b2)
scores = np.dot(hidden_layer2, W3) + b3
predicted_class = np.argmax(scores, axis=1)
print ('training accuracy: %.2f' % (np.mean(predicted_class == y)))
4 训练神经网络
4.1 用sigmoid非线性训练网络
N = 100 # number of points per class
D = 2 # dimensionality
K = 3 # number of classes
h=50
h2=50
num_train_examples = X.shape[0]
model={}
model['h'] = h # size of hidden layer 1
model['h2']= h2# size of hidden layer 2
model['W1']= 0.1 * np.random.randn(D,h)
model['b1'] = np.zeros((1,h))
model['W2'] = 0.1 * np.random.randn(h,h2)
model['b2']= np.zeros((1,h2))
model['W3'] = 0.1 * np.random.randn(h2,K)
model['b3'] = np.zeros((1,K))
(sigm_array_1, sigm_array_2, s_W1, s_W2,s_W3, s_b1, s_b2,s_b3) = three_layer_net('SIGM', X,y,model, step_size=1e-1, reg=1e-3)
运行结果:
iteration 0: loss 1.130914
iteration 1000: loss 1.099443
iteration 2000: loss 0.961015
iteration 3000: loss 0.828722
iteration 4000: loss 0.814054
iteration 5000: loss 0.80992
...
iteration 45000: loss 0.471655
iteration 46000: loss 0.470753
iteration 47000: loss 0.469861
iteration 48000: loss 0.468986
iteration 49000: loss 0.468135
training accuracy: 0.96
4.2 用ReLU非线性训练网络
N = 100 # number of points per class
D = 2 # dimensionality
K = 3 # number of classes
h=50
h2=50
num_train_examples = X.shape[0]
model={}
model['h'] = h # size of hidden layer 1
model['h2']= h2# size of hidden layer 2
model['W1']= 0.1 * np.random.randn(D,h)
model['b1'] = np.zeros((1,h))
model['W2'] = 0.1 * np.random.randn(h,h2)
model['b2']= np.zeros((1,h2))
model['W3'] = 0.1 * np.random.randn(h2,K)
model['b3'] = np.zeros((1,K))
(relu_array_1, relu_array_2, r_W1, r_W2,r_W3, r_b1, r_b2,r_b3) = three_layer_net('RELU', X,y,model, step_size=1e-1, reg=1e-3)
运行结果:
iteration 0: loss 1.115254
iteration 1000: loss 0.341567
iteration 2000: loss 0.154439
iteration 3000: loss 0.134785
iteration 4000: loss 0.129502
iteration 5000: loss 0.126574
...
iteration 45000: loss 0.112814
iteration 46000: loss 0.112758
iteration 47000: loss 0.112705
iteration 48000: loss 0.112652
iteration 49000: loss 0.112601
training accuracy: 0.99
5 完整代码
#coding=utf-8 #构建一个非常简单的神经网络,有三层(两个隐藏层) # Setup import numpy as np import matplotlib.pyplot as plt #sigmoid函数“压缩”输入位于0和1之间。不幸的是,这意味着对于sigmoid输出接近0或1的输入,相对于这些输入的梯度接近于零。 #这导致梯度消失的现象,其中梯度下降接近于零,并且网络不能很好地学习。 def sigmoid(x): x = 1/(1+np.exp(-x)) return x def sigmoid_grad(x): return (x)*(1-x) #relu函数(max(0,x))不会随输入大小而饱和 def relu(x): return np.maximum(0,x) plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' # 生成一些数据 # 让我们生成一个不易线性分离的分类数据集。我们最喜欢的例子是螺旋数据集,可以按如下方式生成: #玩具螺旋数据由三个类别(蓝色,红色,黄色)组成,这些类别不是线性可分的。 N = 100 # number of points per class D = 2 # dimensionality K = 3 # number of classes X = np.zeros((N*K,D)) # data matrix (each row = single example) y = np.zeros(N*K, dtype='uint8') # class labels for j in range(K): ix = range(N*j,N*(j+1)) r = np.linspace(0.0,1,N) # radius t = np.linspace(j*4,(j+1)*4,N) + np.random.randn(N)*0.2 # theta X[ix] = np.c_[r*np.sin(t), r*np.cos(t)] y[ix] = j # lets visualize the data: plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral) plt.show() #定义sigmoid和relu函数 #我们构建一个非常简单的神经网络,有三层(两个隐藏层),您可以换掉ReLU / sigmoid非线性。 def three_layer_net(NONLINEARITY,X,y, model, step_size, reg): #NONLINEARITY:表示使用哪种激活函数 #parameter initialization h= model['h'] h2= model['h2'] W1= model['W1'] W2= model['W2'] W3= model['W3'] b1= model['b1'] b2= model['b2'] b3= model['b3'] # some hyperparameters # 梯度下降 num_examples = X.shape[0] plot_array_1=[] plot_array_2=[] for i in range(50000): #前向传播 if NONLINEARITY== 'RELU': hidden_layer = relu(np.dot(X, W1) + b1) hidden_layer2 = relu(np.dot(hidden_layer, W2) + b2) scores = np.dot(hidden_layer2, W3) + b3 elif NONLINEARITY == 'SIGM': hidden_layer = sigmoid(np.dot(X, W1) + b1) hidden_layer2 = sigmoid(np.dot(hidden_layer, W2) + b2) scores = np.dot(hidden_layer2, W3) + b3 #计算损失 #probs大小为[300 x 3] 的数组,其中每行现在包含类概率 exp_scores = np.exp(scores) probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) # [N x K] # compute the loss: average cross-entropy loss and regularization #数组correct_logprobs是一维数组,仅包含为每个示例分配给正确类的概率。那么完全损失就是这些对数概率和正则化损失的平均值 corect_logprobs = -np.log(probs[range(num_examples),y]) data_loss = np.sum(corect_logprobs)/num_examples reg_loss = 0.5*reg*np.sum(W1*W1) + 0.5*reg*np.sum(W2*W2)+ 0.5*reg*np.sum(W3*W3) loss = data_loss + reg_loss if i % 1000 == 0: print ("iteration %d: loss %f" % (i, loss)) # compute the gradient on scores dscores = probs dscores[range(num_examples),y] -= 1 dscores /= num_examples # BACKPROP HERE dW3 = (hidden_layer2.T).dot(dscores) db3 = np.sum(dscores, axis=0, keepdims=True) if NONLINEARITY == 'RELU': #backprop ReLU nonlinearity here dhidden2 = np.dot(dscores, W3.T) dhidden2[hidden_layer2 <= 0] = 0 dW2 = np.dot( hidden_layer.T, dhidden2) plot_array_2.append(np.sum(np.abs(dW2))/np.sum(np.abs(dW2.shape))) db2 = np.sum(dhidden2, axis=0) dhidden = np.dot(dhidden2, W2.T) dhidden[hidden_layer <= 0] = 0 elif NONLINEARITY == 'SIGM': #backprop sigmoid nonlinearity here dhidden2 = dscores.dot(W3.T)*sigmoid_grad(hidden_layer2) dW2 = (hidden_layer.T).dot(dhidden2) plot_array_2.append(np.sum(np.abs(dW2))/np.sum(np.abs(dW2.shape))) db2 = np.sum(dhidden2, axis=0) dhidden = dhidden2.dot(W2.T)*sigmoid_grad(hidden_layer) dW1 = np.dot(X.T, dhidden) plot_array_1.append(np.sum(np.abs(dW1))/np.sum(np.abs(dW1.shape))) db1 = np.sum(dhidden, axis=0) # add regularization dW3+= reg * W3 dW2 += reg * W2 dW1 += reg * W1 #option to return loss, grads -- uncomment next comment grads={} grads['W1']=dW1 grads['W2']=dW2 grads['W3']=dW3 grads['b1']=db1 grads['b2']=db2 grads['b3']=db3 #return loss, grads # update W1 += -step_size * dW1 b1 += -step_size * db1 W2 += -step_size * dW2 b2 += -step_size * db2 W3 += -step_size * dW3 b3 += -step_size * db3 # evaluate training set accuracy if NONLINEARITY == 'RELU': hidden_layer = relu(np.dot(X, W1) + b1) hidden_layer2 = relu(np.dot(hidden_layer, W2) + b2) elif NONLINEARITY == 'SIGM': hidden_layer = sigmoid(np.dot(X, W1) + b1) hidden_layer2 = sigmoid(np.dot(hidden_layer, W2) + b2) scores = np.dot(hidden_layer2, W3) + b3 predicted_class = np.argmax(scores, axis=1) print ('training accuracy: %.2f' % (np.mean(predicted_class == y))) #return cost, grads return plot_array_1, plot_array_2, W1, W2, W3, b1, b2, b3 #用sigmoid非线性训练网络 N = 100 # number of points per class D = 2 # dimensionality K = 3 # number of classes h=50 h2=50 # num_train_examples = X.shape[0] # # model={} # model['h'] = h # size of hidden layer 1 # model['h2']= h2# size of hidden layer 2 # model['W1']= 0.1 * np.random.randn(D,h) # model['b1'] = np.zeros((1,h)) # model['W2'] = 0.1 * np.random.randn(h,h2) # model['b2']= np.zeros((1,h2)) # model['W3'] = 0.1 * np.random.randn(h2,K) # model['b3'] = np.zeros((1,K)) # # (sigm_array_1, sigm_array_2, s_W1, s_W2,s_W3, s_b1, s_b2,s_b3) = three_layer_net('SIGM', X,y,model, step_size=1e-1, reg=1e-3) #用ReLU非线性训练网络 #Re-initialize model, train relu net model={} model['h'] = h # size of hidden layer 1 model['h2']= h2# size of hidden layer 2 model['W1']= 0.1 * np.random.randn(D,h) model['b1'] = np.zeros((1,h)) model['W2'] = 0.1 * np.random.randn(h,h2) model['b2']= np.zeros((1,h2)) model['W3'] = 0.1 * np.random.randn(h2,K) model['b3'] = np.zeros((1,K)) (relu_array_1, relu_array_2, r_W1, r_W2,r_W3, r_b1, r_b2,r_b3) = three_layer_net('RELU', X,y,model, step_size=1e-1, reg=1e-3)
-
Python实现循环神经网络RNN
2017-05-05 21:35:31基于Python的循环神经网络(RNN)实现 -
用纯Python实现循环神经网络RNN向前传播过程(吴恩达DeepLearning.ai作业)
2020-12-22 00:57:02Google TensorFlow程序员...吴恩达deepLearning.ai循环神经网络RNN学习笔记(理论篇) 我们将实现以下结构的RNN,在这个例子中 Tx = Ty。 向量表示以及它的维度 Input with nx number of units 对单个输入样本,x(i) -
python神经网络回归自然_用纯Python实现循环神经网络RNN向前传播过程(吴恩达DeepLearning.ai作业)...
2020-12-17 04:35:17rnn cell- rnn 向前传播重点关注:- 如何把数据向量化的,它们的维度是怎么来的- 一共其实就是两步:单个单元的rnn计算,拉通来的rnn计算在看本文前,可以先看看这篇文章回忆一下:我们将实现以下结构的RNN,在这个...Google TensorFlow程序员点赞的文章!
前言
目录:
- 向量表示以及它的维度
- rnn cell
- rnn 向前传播
重点关注:
- 如何把数据向量化的,它们的维度是怎么来的
- 一共其实就是两步: 单个单元的rnn计算,拉通来的rnn计算
在看本文前,可以先看看这篇文章回忆一下:
我们将实现以下结构的RNN,在这个例子中 Tx = Ty。
向量表示以及它的维度
Input with nx number of units
对单个输入样本,x(i) 是一维输入向量。
用语言来举个例子,将具有5k个单词词汇量的语言用one-hot编码成具有5k个单位的向量,所以 x(i) 的维度是(5000,)。
我们将用符号 nx 表示单个训练样本的单位数。
Batches of size m
如果我们取小批量(mini-batches),每个批次有20个训练样本。
为了受益于向量化,我们将20个样本 x(i) 变成一个2维数组(矩阵)。
比如一个维度是(5000,20)的向量。
我们用m来表示训练样本的数量。
所以小批量训练数据的维度是 (nx, m)。
Time steps of size Tx
循环神经网络有多个时间步骤,我们用t来表示。
我们将看到训练样本 x(i) 将经历多个时间步骤 Tx, 比如如果有10个时间步骤,那么 Tx = 10。
3D Tensor of shape(nx, m, Tx)
输入x就是用维度是 (nx, m, Tx) 的三维张量来表示。
Taking a 2D slice for each time step:
每一个时间步骤,我们用小批量训练样本(不是单个的训练样本)。
所以针对每个时间步骤t,我们用维度是 (nx, m)的2维切片。
我们把它表示成xt。
隐藏状态a的维度
a的定义: 从一个时间步骤到另一个时间步骤的激活值 at, 我们把它叫做隐藏状态。
同输入张量 x 一样,对于单个训练样本的隐藏状态,它的向量长度是na。
如果我们是包含了m个训练样本的小批量数据,那么小批量维度是 (na, m)。
如果我们把时间步加进去,那么隐藏状态的维度就是 (na, m, Tx)。
我们将用索引t来遍历时间步,每次操作是从3维张量切片成的2维向量。
我们用at来表示2维的切片,它的维度是 (na, m)。
预测值y^的维度
同输入x和隐藏状态一样,y^是一个维度是 (ny, m, Ty) 的3维张量。
ny: 代表预测值的单位数。
m: 小批次训练的样本数量。
Ty: 预测的时间数。
比如单个时间步 t,2维的切片 y^ 的维度是 (ny, m)。
RNN cell
我们的第一个任务就是执行单个时间步骤的计算,计算如下图。
输入是a^, xt,输出是at, yt^。以下的代码其实就是把上面的公式代码化,总的步骤分成4步:
取出参数。
计算at。
计算yt^。
返回输出的at, yt^,还要存储一些值缓存起来。
import numpy as np
def rnn_cell_forward(xt, a_prev, parameters):
"""
Implements a single forward step of the RNN-cell as described in Figure (2)
Arguments:
xt -- your input data at timestep "t", numpy array of shape (n_x, m).
a_prev -- Hidden state at timestep "t-1", numpy array of shape (n_a, m)
parameters -- python dictionary containing:
Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x) Waa -- Weight matrix multiplying the hidden state, numpy array of shape (n_a, n_a)
Wya -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
ba -- Bias, numpy array of shape (n_a, 1)
by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
Returns:
a_next -- next hidden state, of shape (n_a, m)
yt_pred -- prediction at timestep "t", numpy array of shape (n_y, m)
cache -- tuple of values needed for the backward pass, contains (a_next, a_prev, xt, parameters)
"""
# 取计算的参数
Wax = parameters["Wax"]
Waa = parameters["Waa"]
Wya = parameters["Wya"]
ba = parameters["ba"]
by = parameters["by"]
# 用公式计算下一个单元的激活值
a_next = np.tanh(np.dot(Waa, a_prev) + np.dot(Wax, xt) + ba)
# 计算当前cell的输出
yt_pred = softmax(np.dot(Wya, a_next) + by)
# 用于向后传播的缓存值
cache = (a_next, a_prev, xt, parameters)
return a_next, yt_pred, cache
RNN向前传播
一个循环神经网络就是不断的重复你上面创建的rnn 单元。
如果你的输入数据序列是10个时间步,那么你就要重复你的rnn cell 10次。
在每个时间步中,每个单元将用2个输入:
a: 前一个单元的隐藏状态。
xt: 当前时间步的输入数据。
每个时间步有两个输出:
一个隐藏状态at
一个测值y^*t*
权重和偏差 (Waa,ba,Wax,bx) 将在每个时间步中循环使用,它们保存在"parameters"的变量中。
def rnn_forward(x, a0, parameters):
"""
Implement the forward propagation of the recurrent neural network described in Figure (3).
Arguments:
x -- Input data for every time-step, of shape (n_x, m, T_x).
a0 -- Initial hidden state, of shape (n_a, m)
parameters -- python dictionary containing:
Waa -- Weight matrix multiplying the hidden state, numpy array of shape (n_a, n_a)
Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x)
Wya -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
ba -- Bias numpy array of shape (n_a, 1)
by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
Returns:
a -- Hidden states for every time-step, numpy array of shape (n_a, m, T_x)
y_pred -- Predictions for every time-step, numpy array of shape (n_y, m, T_x)
caches -- tuple of values needed for the backward pass, contains (list of caches, x)
"""
# 用于存储所有cache的列表,初始化它
caches = []
# 取一些纬度值,用于后面初始化变量
n_x, m, T_x = x.shape
n_y, n_a = parameters["Wya"].shape
# 初始化 a 和 y_pred
a = np.zeros((n_a, m, T_x))
y_pred = np.zeros((n_y, m, T_x))
# 初始化 a_next
a_next = a0
# loop over all time-steps of the input 'x'
for t in range(T_x):
# Update next hidden state, compute the prediction, get the cache
xt = x[:,:,t] # 通过切片的方式从输入变量x中取出当前t时间步的输入xt
a_next, yt_pred, cache = rnn_cell_forward(xt, a_next, parameters)
# 保存当前单元计算的a_next值
a[:,:,t] = a_next
# 保存当前单元的预测值y
y_pred[:,:,t] = yt_pred
# 添加每个单元的缓存值
caches.append(cache)
# store values needed for backward propagation in cache
caches = (caches, x)
return a, y_pred, caches
恭喜你(*^▽^*),到这里你已经能够从0到1的构建循环神经网络的向前传播过程。
在现代深度学习框架中,您仅需实现前向传递,而框架将处理后向传递,因此大多数深度学习工程师无需理会后向传递的细节。我就不写向后传播了。
-
python音频降噪rnn_用纯Python实现循环神经网络RNN向前传播过程(吴恩达DeepLearning.ai作业)...
2020-12-21 19:01:32rnn cell- rnn 向前传播重点关注:- 如何把数据向量化的,它们的维度是怎么来的- 一共其实就是两步:单个单元的rnn计算,拉通来的rnn计算在看本文前,可以先看看这篇文章回忆一下:我们将实现以下结构的RNN,在这个...Google TensorFlow程序员点赞的文章!
前言
目录:
- 向量表示以及它的维度
- rnn cell
- rnn 向前传播
重点关注:
- 如何把数据向量化的,它们的维度是怎么来的
- 一共其实就是两步: 单个单元的rnn计算,拉通来的rnn计算
在看本文前,可以先看看这篇文章回忆一下:
我们将实现以下结构的RNN,在这个例子中 Tx = Ty。
向量表示以及它的维度
Input with nx number of units
对单个输入样本,x(i) 是一维输入向量。
用语言来举个例子,将具有5k个单词词汇量的语言用one-hot编码成具有5k个单位的向量,所以 x(i) 的维度是(5000,)。
我们将用符号 nx 表示单个训练样本的单位数。
Batches of size m
如果我们取小批量(mini-batches),每个批次有20个训练样本。
为了受益于向量化,我们将20个样本 x(i) 变成一个2维数组(矩阵)。
比如一个维度是(5000,20)的向量。
我们用m来表示训练样本的数量。
所以小批量训练数据的维度是 (nx, m)。
Time steps of size Tx
循环神经网络有多个时间步骤,我们用t来表示。
我们将看到训练样本 x(i) 将经历多个时间步骤 Tx, 比如如果有10个时间步骤,那么 Tx = 10。
3D Tensor of shape(nx, m, Tx)
输入x就是用维度是 (nx, m, Tx) 的三维张量来表示。
Taking a 2D slice for each time step:
每一个时间步骤,我们用小批量训练样本(不是单个的训练样本)。
所以针对每个时间步骤t,我们用维度是 (nx, m)的2维切片。
我们把它表示成xt。
隐藏状态a的维度
a的定义: 从一个时间步骤到另一个时间步骤的激活值 at, 我们把它叫做隐藏状态。
同输入张量 x 一样,对于单个训练样本的隐藏状态,它的向量长度是na。
如果我们是包含了m个训练样本的小批量数据,那么小批量维度是 (na, m)。
如果我们把时间步加进去,那么隐藏状态的维度就是 (na, m, Tx)。
我们将用索引t来遍历时间步,每次操作是从3维张量切片成的2维向量。
我们用at来表示2维的切片,它的维度是 (na, m)。
预测值y^的维度
同输入x和隐藏状态一样,y^是一个维度是 (ny, m, Ty) 的3维张量。
ny: 代表预测值的单位数。
m: 小批次训练的样本数量。
Ty: 预测的时间数。
比如单个时间步 t,2维的切片 y^ 的维度是 (ny, m)。
RNN cell
我们的第一个任务就是执行单个时间步骤的计算,计算如下图。
输入是a^, xt,输出是at, yt^。以下的代码其实就是把上面的公式代码化,总的步骤分成4步:
取出参数。
计算at。
计算yt^。
返回输出的at, yt^,还要存储一些值缓存起来。
import numpy as np
def rnn_cell_forward(xt, a_prev, parameters):
"""
Implements a single forward step of the RNN-cell as described in Figure (2)
Arguments:
xt -- your input data at timestep "t", numpy array of shape (n_x, m).
a_prev -- Hidden state at timestep "t-1", numpy array of shape (n_a, m)
parameters -- python dictionary containing:
Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x) Waa -- Weight matrix multiplying the hidden state, numpy array of shape (n_a, n_a)
Wya -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
ba -- Bias, numpy array of shape (n_a, 1)
by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
Returns:
a_next -- next hidden state, of shape (n_a, m)
yt_pred -- prediction at timestep "t", numpy array of shape (n_y, m)
cache -- tuple of values needed for the backward pass, contains (a_next, a_prev, xt, parameters)
"""
# 取计算的参数
Wax = parameters["Wax"]
Waa = parameters["Waa"]
Wya = parameters["Wya"]
ba = parameters["ba"]
by = parameters["by"]
# 用公式计算下一个单元的激活值
a_next = np.tanh(np.dot(Waa, a_prev) + np.dot(Wax, xt) + ba)
# 计算当前cell的输出
yt_pred = softmax(np.dot(Wya, a_next) + by)
# 用于向后传播的缓存值
cache = (a_next, a_prev, xt, parameters)
return a_next, yt_pred, cache
RNN向前传播
一个循环神经网络就是不断的重复你上面创建的rnn 单元。
如果你的输入数据序列是10个时间步,那么你就要重复你的rnn cell 10次。
在每个时间步中,每个单元将用2个输入:
a: 前一个单元的隐藏状态。
xt: 当前时间步的输入数据。
每个时间步有两个输出:
一个隐藏状态at
一个测值y^⟨t⟩
权重和偏差 (Waa,ba,Wax,bx) 将在每个时间步中循环使用,它们保存在"parameters"的变量中。
def rnn_forward(x, a0, parameters):
"""
Implement the forward propagation of the recurrent neural network described in Figure (3).
Arguments:
x -- Input data for every time-step, of shape (n_x, m, T_x).
a0 -- Initial hidden state, of shape (n_a, m)
parameters -- python dictionary containing:
Waa -- Weight matrix multiplying the hidden state, numpy array of shape (n_a, n_a)
Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x)
Wya -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
ba -- Bias numpy array of shape (n_a, 1)
by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
Returns:
a -- Hidden states for every time-step, numpy array of shape (n_a, m, T_x)
y_pred -- Predictions for every time-step, numpy array of shape (n_y, m, T_x)
caches -- tuple of values needed for the backward pass, contains (list of caches, x)
"""
# 用于存储所有cache的列表,初始化它
caches = []
# 取一些纬度值,用于后面初始化变量
n_x, m, T_x = x.shape
n_y, n_a = parameters["Wya"].shape
# 初始化 a 和 y_pred
a = np.zeros((n_a, m, T_x))
y_pred = np.zeros((n_y, m, T_x))
# 初始化 a_next
a_next = a0
# loop over all time-steps of the input 'x'
for t in range(T_x):
# Update next hidden state, compute the prediction, get the cache
xt = x[:,:,t] # 通过切片的方式从输入变量x中取出当前t时间步的输入xt
a_next, yt_pred, cache = rnn_cell_forward(xt, a_next, parameters)
# 保存当前单元计算的a_next值
a[:,:,t] = a_next
# 保存当前单元的预测值y
y_pred[:,:,t] = yt_pred
# 添加每个单元的缓存值
caches.append(cache)
# store values needed for backward propagation in cache
caches = (caches, x)
return a, y_pred, caches
恭喜你(*^▽^*),到这里你已经能够从0到1的构建循环神经网络的向前传播过程。
在现代深度学习框架中,您仅需实现前向传递,而框架将处理后向传递,因此大多数深度学习工程师无需理会后向传递的细节。我就不写向后传播了。
-
python类怎么实例化rnn层_用纯Python实现循环神经网络RNN向前传播过程(吴恩达DeepLearning.ai作业)...
2020-12-22 06:53:48rnn cell- rnn 向前传播重点关注:- 如何把数据向量化的,它们的维度是怎么来的- 一共其实就是两步:单个单元的rnn计算,拉通来的rnn计算在看本文前,可以先看看这篇文章回忆一下:我们将实现以下结构的RNN,在这个...Google TensorFlow程序员点赞的文章!
前言
目录:
- 向量表示以及它的维度
- rnn cell
- rnn 向前传播
重点关注:
- 如何把数据向量化的,它们的维度是怎么来的
- 一共其实就是两步: 单个单元的rnn计算,拉通来的rnn计算
在看本文前,可以先看看这篇文章回忆一下:
我们将实现以下结构的RNN,在这个例子中 Tx = Ty。
向量表示以及它的维度
Input with nx number of units
对单个输入样本,x(i) 是一维输入向量。
用语言来举个例子,将具有5k个单词词汇量的语言用one-hot编码成具有5k个单位的向量,所以 x(i) 的维度是(5000,)。
我们将用符号 nx 表示单个训练样本的单位数。
Batches of size m
如果我们取小批量(mini-batches),每个批次有20个训练样本。
为了受益于向量化,我们将20个样本 x(i) 变成一个2维数组(矩阵)。
比如一个维度是(5000,20)的向量。
我们用m来表示训练样本的数量。
所以小批量训练数据的维度是 (nx, m)。
Time steps of size Tx
循环神经网络有多个时间步骤,我们用t来表示。
我们将看到训练样本 x(i) 将经历多个时间步骤 Tx, 比如如果有10个时间步骤,那么 Tx = 10。
3D Tensor of shape(nx, m, Tx)
输入x就是用维度是 (nx, m, Tx) 的三维张量来表示。
Taking a 2D slice for each time step:
每一个时间步骤,我们用小批量训练样本(不是单个的训练样本)。
所以针对每个时间步骤t,我们用维度是 (nx, m)的2维切片。
我们把它表示成xt。
隐藏状态a的维度
a的定义: 从一个时间步骤到另一个时间步骤的激活值 at, 我们把它叫做隐藏状态。
同输入张量 x 一样,对于单个训练样本的隐藏状态,它的向量长度是na。
如果我们是包含了m个训练样本的小批量数据,那么小批量维度是 (na, m)。
如果我们把时间步加进去,那么隐藏状态的维度就是 (na, m, Tx)。
我们将用索引t来遍历时间步,每次操作是从3维张量切片成的2维向量。
我们用at来表示2维的切片,它的维度是 (na, m)。
预测值y^的维度
同输入x和隐藏状态一样,y^是一个维度是 (ny, m, Ty) 的3维张量。
ny: 代表预测值的单位数。
m: 小批次训练的样本数量。
Ty: 预测的时间数。
比如单个时间步 t,2维的切片 y^ 的维度是 (ny, m)。
RNN cell
我们的第一个任务就是执行单个时间步骤的计算,计算如下图。
输入是a^, xt,输出是at, yt^。以下的代码其实就是把上面的公式代码化,总的步骤分成4步:
取出参数。
计算at。
计算yt^。
返回输出的at, yt^,还要存储一些值缓存起来。
import numpy as np
def rnn_cell_forward(xt, a_prev, parameters):
"""
Implements a single forward step of the RNN-cell as described in Figure (2)
Arguments:
xt -- your input data at timestep "t", numpy array of shape (n_x, m).
a_prev -- Hidden state at timestep "t-1", numpy array of shape (n_a, m)
parameters -- python dictionary containing:
Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x) Waa -- Weight matrix multiplying the hidden state, numpy array of shape (n_a, n_a)
Wya -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
ba -- Bias, numpy array of shape (n_a, 1)
by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
Returns:
a_next -- next hidden state, of shape (n_a, m)
yt_pred -- prediction at timestep "t", numpy array of shape (n_y, m)
cache -- tuple of values needed for the backward pass, contains (a_next, a_prev, xt, parameters)
"""
# 取计算的参数
Wax = parameters["Wax"]
Waa = parameters["Waa"]
Wya = parameters["Wya"]
ba = parameters["ba"]
by = parameters["by"]
# 用公式计算下一个单元的激活值
a_next = np.tanh(np.dot(Waa, a_prev) + np.dot(Wax, xt) + ba)
# 计算当前cell的输出
yt_pred = softmax(np.dot(Wya, a_next) + by)
# 用于向后传播的缓存值
cache = (a_next, a_prev, xt, parameters)
return a_next, yt_pred, cache
RNN向前传播
一个循环神经网络就是不断的重复你上面创建的rnn 单元。
如果你的输入数据序列是10个时间步,那么你就要重复你的rnn cell 10次。
在每个时间步中,每个单元将用2个输入:
a: 前一个单元的隐藏状态。
xt: 当前时间步的输入数据。
每个时间步有两个输出:
一个隐藏状态at
一个测值y^⟨t⟩
权重和偏差 (Waa,ba,Wax,bx) 将在每个时间步中循环使用,它们保存在"parameters"的变量中。
def rnn_forward(x, a0, parameters):
"""
Implement the forward propagation of the recurrent neural network described in Figure (3).
Arguments:
x -- Input data for every time-step, of shape (n_x, m, T_x).
a0 -- Initial hidden state, of shape (n_a, m)
parameters -- python dictionary containing:
Waa -- Weight matrix multiplying the hidden state, numpy array of shape (n_a, n_a)
Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x)
Wya -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
ba -- Bias numpy array of shape (n_a, 1)
by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
Returns:
a -- Hidden states for every time-step, numpy array of shape (n_a, m, T_x)
y_pred -- Predictions for every time-step, numpy array of shape (n_y, m, T_x)
caches -- tuple of values needed for the backward pass, contains (list of caches, x)
"""
# 用于存储所有cache的列表,初始化它
caches = []
# 取一些纬度值,用于后面初始化变量
n_x, m, T_x = x.shape
n_y, n_a = parameters["Wya"].shape
# 初始化 a 和 y_pred
a = np.zeros((n_a, m, T_x))
y_pred = np.zeros((n_y, m, T_x))
# 初始化 a_next
a_next = a0
# loop over all time-steps of the input 'x'
for t in range(T_x):
# Update next hidden state, compute the prediction, get the cache
xt = x[:,:,t] # 通过切片的方式从输入变量x中取出当前t时间步的输入xt
a_next, yt_pred, cache = rnn_cell_forward(xt, a_next, parameters)
# 保存当前单元计算的a_next值
a[:,:,t] = a_next
# 保存当前单元的预测值y
y_pred[:,:,t] = yt_pred
# 添加每个单元的缓存值
caches.append(cache)
# store values needed for backward propagation in cache
caches = (caches, x)
return a, y_pred, caches
恭喜你(*^▽^*),到这里你已经能够从0到1的构建循环神经网络的向前传播过程。
在现代深度学习框架中,您仅需实现前向传递,而框架将处理后向传递,因此大多数深度学习工程师无需理会后向传递的细节。我就不写向后传播了。
原文出处:https://www.cnblogs.com/siguamatrix/p/12523600.html
-
循环神经网络python实现
2018-11-28 19:24:12使用循环神经网络(RNN)实现简易的二进制加法器,利用python中numpy包实现。 -
elman神经网络 python实现_神经网络的python实现
2020-11-23 21:44:28首先实现的是普通神经网络,区别于卷积神经网络,也就是输入层-隐含层-输出层的NN。由于比较简单,只需要numpy这个库就可以。简单说一下为什么numpy这么强,主要是因为许多数学运算如矩阵点乘,自己写函数可以要用到... -
python numpy 从零实现循环神经网络
2019-11-24 15:34:051.Basic RNN 我们来看一下下面的循环神经网络的图, ...循环神经网络可以看作是单元的重复,首先要实现单个时间步的计算,下图描述了RNN单元的单个时间步的操作。 def rnn_cell(xt,a_prev,parameters): Wax... -
纯Python和PyTorch对比实现循环神经网络RNN及反向传播
2018-12-15 16:30:52本文使用纯 Python 和 PyTorch 对比实现循环神经网络RNN及其反向传播 相关 原理和详细解释, 请参考: 循环神经网络RNNCell单元详解及反向传播的梯度求导 https://blog.csdn.net/oBrightLamp/article/details/85015325... -
纯Python和PyTorch对比实现循环神经网络RNNCell及反向传播
2018-12-15 16:31:46摘要 本文使用纯 Python 和 PyTorch 对比实现循环神经网络RNNCell单元及其反向传播 相关 原理和详细解释, 请参考: 循环神经网络RNNCell单元详解及反向传播的梯度求导 ...正文 import torch import numpy as np ... -
循环神经网络教程第四部分-用Python和Theano实现GRU/LSTM循环神经网络
2017-02-03 16:28:54作者:徐志强 ... 来源:知乎 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 ...本篇教程的代码在Github上。...循环神经网络教程第二部分-用python,numpy,theano实现一个RNN -
python实现LSTM神经网络模型
2018-03-09 11:22:58参考... ''' 用tensorflow实现递归循环网络(LSTM) ''' from __future__ import print_function import tensorflow as tf from tensorflow.contrib import rnn #导入MINIST数据... -
纯Python和PyTorch对比实现循环神经网络LSTM及反向传播
2018-12-18 16:44:45摘要 本文使用纯 Python 和 PyTorch 对比实现循环神经网络LSTM及其反向传播. 相关 配套代码, 请参考文章 : 长短期记忆网络LSTMCell单元详解及反向传播的梯度求导 文章索引 : ...正文 1. LSTMCell 类 ... -
python实现最简单循环神经网络(RNNs)
2017-11-10 11:08:13Recurrent Neural Networks(RNNs) 的模型: 上图中红色部分是输入向量。文本、单词、数据都是输入,在网络里都以...y = rnn.step(x) # x为输入向量,y为输出向量RNNs神经网络由神经元组成, python 代码神经元的