numpy實(shí)現(xiàn)RNN原理實(shí)現(xiàn)
首先說(shuō)明代碼只是幫助理解,并未寫(xiě)出梯度下降部分,默認(rèn)參數(shù)已經(jīng)被固定,不影響理解。代碼主要實(shí)現(xiàn)RNN原理,只使用numpy庫(kù),不可用于GPU加速。
import numpy as np class 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]))
到此這篇關(guān)于numpy實(shí)現(xiàn)RNN原理實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)numpy實(shí)現(xiàn)RNN內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解Python如何實(shí)現(xiàn)輸出顏色字體到終端界面
在終端中,輸出的字體總是單一顏色的,黑底白字。但是在一些場(chǎng)景并不能很好的滿(mǎn)足輸出的需求。本文為大家介紹了Python如何實(shí)現(xiàn)輸出顏色字體到終端界面中,需要的可以參考一下2022-12-12python學(xué)習(xí)之panda數(shù)據(jù)分析核心支持庫(kù)
這篇文章主要給大家介紹了關(guān)于python學(xué)習(xí)之panda數(shù)據(jù)分析核心支持庫(kù)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05Python實(shí)現(xiàn)人臉識(shí)別的詳細(xì)圖文教程
人臉識(shí)別是人工智能的一個(gè)重要應(yīng)用,下面這篇文章主要給大家介紹了關(guān)于Python實(shí)現(xiàn)人臉識(shí)別的相關(guān)資料,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08