时间:2021-05-22
首先说明代码只是帮助理解,并未写出梯度下降部分,默认参数已经被固定,不影响理解。代码主要实现RNN原理,只使用numpy库,不可用于GPU加速。
import numpy as npclass Rnn(): def __init__(self, input_size, hidden_size, num_layers, bidirectional=False): self.input_size = input_size self.hidden_size = hidden_size self.num_layers = num_layers self.bidirectional = bidirectional def feed(self, x): ''' :param x: [seq, batch_size, embedding] :return: out, hidden ''' # x.shape [sep, batch, feature] # hidden.shape [hidden_size, batch] # Whh0.shape [hidden_size, hidden_size] Wih0.shape [hidden_size, feature] # Whh1.shape [hidden_size, hidden_size] Wih1.size [hidden_size, hidden_size] out = [] x, hidden = np.array(x), [np.zeros((self.hidden_size, x.shape[1])) for i in range(self.num_layers)] Wih = [np.random.random((self.hidden_size, self.hidden_size)) for i in range(1, self.num_layers)] Wih.insert(0, np.random.random((self.hidden_size, x.shape[2]))) Whh = [np.random.random((self.hidden_size, self.hidden_size)) for i in range(self.num_layers)] time = x.shape[0] for i in range(time): hidden[0] = np.tanh((np.dot(Wih[0], np.transpose(x[i, ...], (1, 0))) + np.dot(Whh[0], hidden[0]) )) for i in range(1, self.num_layers): hidden[i] = np.tanh((np.dot(Wih[i], hidden[i-1]) + np.dot(Whh[i], hidden[i]) )) out.append(hidden[self.num_layers-1]) return np.array(out), np.array(hidden)def sigmoid(x): return 1.0/(1.0 + 1.0/np.exp(x))if __name__ == '__main__': rnn = Rnn(1, 5, 4) input = np.random.random((6, 2, 1)) out, h = rnn.feed(input) print(f'seq is {input.shape[0]}, batch_size is {input.shape[1]} ', 'out.shape ', out.shape, ' h.shape ', h.shape) # print(sigmoid(np.random.random((2, 3)))) # # element-wise multiplication # print(np.array([1, 2])*np.array([2, 1]))到此这篇关于numpy实现RNN原理实现的文章就介绍到这了,更多相关numpy实现RNN内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
目前我的工作是将NumPy引入到Pyston中(一款Dropbox实现的Python编译器/解释器)。在工作过程中,我深入接触了NumPy源码,了解其实现并提交
方法文件session实现文件:memcachedsession.php实现原理(也是PHP内部session的实现原理):1.先判断客户端有没有session
在进行物体检测的groundtruthboxesannotations包围框坐标数据整理时,需要实现这样的功能:numpy里面,对于N*4的数组,要实现对于每一
linspace可以用来实现相同间隔的采样;numpy.linspace(start,stop,num=50,endpoint=True,retstep=Fal
本文实例为大家分享了Android实现图片加载进度提示的具体代码,供大家参考,具体内容如下先上图:实现原理:第一个控件的实现原理是重写ImageView的onD