您好,登錄后才能下訂單哦!
這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)利用numpy怎么實(shí)現(xiàn)一個(gè)RNN功能,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
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] # Whh2.shape [hidden_size, hidden_size] Wih2.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怎么實(shí)現(xiàn)一個(gè)RNN功能了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。