Pytorch學(xué)習(xí)筆記(一)

一蝗罗、線性回歸模型使用Pytorch的簡(jiǎn)潔實(shí)現(xiàn)

生成數(shù)據(jù)集

num_inputs = 2

num_examples = 1000

true_w = [2, -3.4]

true_b = 4.2

features = torch.tensor(np.random.normal(0, 1, (num_examples, num_inputs)), dtype=torch.float)

labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b

labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float)

讀取數(shù)據(jù)集

import torch.utils.data as Data

batch_size = 10

# combine featues and labels of dataset

dataset = Data.TensorDataset(features, labels)

# put dataset into DataLoader

data_iter = Data.DataLoader(

? ? ? ? ? ? ? ? ? ? ? ? ? ? dataset=dataset,? ? ? ? ? ? # torch TensorDataset format

? ? ? ? ? ? ? ? ? ? ? ? ? ? batch_size=batch_size,? ? ? # mini batch size

? ? ? ? ? ? ? ? ? ? ? ? ? ? shuffle=True,? ? ? ? ? ? ? # whether shuffle the data or not

? ? ? ? ? ? ? ? ? ? ? ? ? ? num_workers=2,? ? ? ? ? ? ? # read data in multithreading

? ? ? ? ? ? ? ? ? ? ? ? ? ? )

定義模型

class LinearNet(nn.Module):

? ? def __init__(self, n_feature):

? ? ? ? super(LinearNet, self).__init__()? ? ? # call father function to init

? ? ? ? self.linear = nn.Linear(n_feature, 1)? # function prototype: `torch.nn.Linear(in_features, out_features, bias=True)`

? ? def forward(self, x):

? ? ? ? y = self.linear(x)

? ? ? ? return y

net = LinearNet(num_inputs)

初始化模型參數(shù)

from torch.nn import init

init.normal_(net[0].weight, mean=0.0, std=0.01)

init.constant_(net[0].bias, val=0.0)?

定義損失函數(shù)和優(yōu)化函數(shù)

loss=nn.MSELoss()

import torch.optim as optim

optimizer = optim.SGD(net.parameters(), lr=0.03)? # built-in random gradient descent function

print(optimizer)

訓(xùn)練

num_epochs = 3

for epoch in range(1, num_epochs + 1):

? ? for X, y in data_iter:

? ? ? ? output = net(X)

? ? ? ? l = loss(output, y.view(-1, 1))

? ? ? ? optimizer.zero_grad() # reset gradient, equal to net.zero_grad()

? ? ? ? l.backward()

? ? ? ? optimizer.step()

? ? print('epoch %d, loss: %f' % (epoch, l.item()))

dense = net[0]

二、循環(huán)神經(jīng)網(wǎng)絡(luò)的pytorch簡(jiǎn)潔實(shí)現(xiàn)

nn.RNN

我們使用Pytorch中的nn.RNN來(lái)構(gòu)造循環(huán)神經(jīng)網(wǎng)絡(luò)隆敢。

重點(diǎn)關(guān)注nn.RNN的以下幾個(gè)構(gòu)造函數(shù)參數(shù):

input_size?- The number of expected features in the input x

hidden_size?– The number of features in the hidden state h

nonlinearity?– The non-linearity to use. Can be either 'tanh' or 'relu'. Default: 'tanh'

batch_first?– If True, then the input and output tensors are provided as (batch_size, num_steps, input_size). Default: False

這里的batch_first決定了輸入的形狀洞焙,我們使用默認(rèn)的參數(shù)False,對(duì)應(yīng)的輸入形狀是 (num_steps, batch_size, input_size)。

forward函數(shù)的參數(shù)為:

input?of shape (num_steps, batch_size, input_size): tensor containing the features of the input sequence.

h_0?of shape (num_layers * num_directions, batch_size, hidden_size): tensor containing the initial hidden state for each element in the batch. Defaults to zero if not provided. If the RNN is bidirectional, num_directions should be 2, else it should be 1.

forward函數(shù)的返回值是:

output?of shape (num_steps, batch_size, num_directions * hidden_size): tensor containing the output features (h_t) from the last layer of the RNN, for each t.

h_n?of shape (num_layers * num_directions, batch_size, hidden_size): tensor containing the hidden state for t = num_steps.

定義模型

RNN模型的構(gòu)造

class RNNModel(nn.Module):

? ? def __init__(self, rnn_layer, vocab_size):

? ? ? ? super(RNNModel, self).__init__()

? ? ? ? self.rnn = rnn_layer

? ? ? ? self.hidden_size = rnn_layer.hidden_size * (2 if rnn_layer.bidirectional else 1)

? ? ? ? self.vocab_size = vocab_size

? ? ? ? self.dense = nn.Linear(self.hidden_size, vocab_size)

? ? def forward(self, inputs, state):

? ? ? ? # inputs.shape: (batch_size, num_steps)

? ? ? ? X = to_onehot(inputs, vocab_size)

? ? ? ? X = torch.stack(X)? # X.shape: (num_steps, batch_size, vocab_size)

? ? ? ? hiddens, state = self.rnn(X, state)

? ? ? ? hiddens = hiddens.view(-1, hiddens.shape[-1])? # hiddens.shape: (num_steps * batch_size, hidden_size)

? ? ? ? output = self.dense(hiddens)

? ? ? ? return output, state

預(yù)測(cè)函數(shù)的構(gòu)造

def predict_rnn_pytorch(prefix, num_chars, model, vocab_size, device, idx_to_char,

? ? ? ? ? ? ? ? ? ? ? ? char_to_idx):

? ? state = None

? ? output = [char_to_idx[prefix[0]]]? # output記錄prefix加上預(yù)測(cè)的num_chars個(gè)字符

? ? for t in range(num_chars + len(prefix) - 1):

? ? ? ? X = torch.tensor([output[-1]], device=device).view(1, 1)

? ? ? ? (Y, state) = model(X, state)? # 前向計(jì)算不需要傳入模型參數(shù)

? ? ? ? if t < len(prefix) - 1:

? ? ? ? ? ? output.append(char_to_idx[prefix[t + 1]])

? ? ? ? else:

? ? ? ? ? ? output.append(Y.argmax(dim=1).item())

? ? return ''.join([idx_to_char[i] for i in output])

訓(xùn)練函數(shù)的構(gòu)造

def train_and_predict_rnn_pytorch(model, num_hiddens, vocab_size, device,

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? corpus_indices, idx_to_char, char_to_idx,

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? num_epochs, num_steps, lr, clipping_theta,

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? batch_size, pred_period, pred_len, prefixes):

? ? loss = nn.CrossEntropyLoss()

? ? optimizer = torch.optim.Adam(model.parameters(), lr=lr)

? ? model.to(device)

? ? for epoch in range(num_epochs):

? ? ? ? l_sum, n, start = 0.0, 0, time.time()

? ? ? ? data_iter = d2l.data_iter_consecutive(corpus_indices, batch_size, num_steps, device) # 相鄰采樣

? ? ? ? state = None

? ? ? ? for X, Y in data_iter:

? ? ? ? ? ? if state is not None:

? ? ? ? ? ? ? ? # 使用detach函數(shù)從計(jì)算圖分離隱藏狀態(tài)

? ? ? ? ? ? ? ? if isinstance (state, tuple): # LSTM, state:(h, c)

? ? ? ? ? ? ? ? ? ? state[0].detach_()

? ? ? ? ? ? ? ? ? ? state[1].detach_()

? ? ? ? ? ? ? ? else:

? ? ? ? ? ? ? ? ? ? state.detach_()

? ? ? ? (output, state) = model(X, state) # output.shape: (num_steps * batch_size, vocab_size)

? ? ? ? ? ? y = torch.flatten(Y.T)

? ? ? ? ? ? l = loss(output, y.long())


? ? ? ? ? ? optimizer.zero_grad()

? ? ? ? ? ? l.backward()

? ? ? ? ? ? grad_clipping(model.parameters(), clipping_theta, device)

? ? ? ? ? ? optimizer.step()

? ? ? ? ? ? l_sum += l.item() * y.shape[0]

? ? ? ? ? ? n += y.shape[0]

? ? ? ? if (epoch + 1) % pred_period == 0:

? ? ? ? ? ? print('epoch %d, perplexity %f, time %.2f sec' % (

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? epoch + 1, math.exp(l_sum / n), time.time() - start))

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? for prefix in prefixes:

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print(' -', predict_rnn_pytorch(

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? prefix, pred_len, model, vocab_size, device, idx_to_char,

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? char_to_idx))

訓(xùn)練函數(shù)

num_epochs, batch_size, lr, clipping_theta = 250, 32, 1e-3, 1e-2

pred_period, pred_len, prefixes = 50, 50, ['分開', '不分開']

train_and_predict_rnn_pytorch(model, num_hiddens, vocab_size, device,

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? corpus_indices, idx_to_char, char_to_idx,

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? num_epochs, num_steps, lr, clipping_theta,

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? batch_size, pred_period, pred_len, prefixes)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末室奏,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子辕坝,更是在濱河造成了極大的恐慌窍奋,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,941評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件酱畅,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡江场,警方通過查閱死者的電腦和手機(jī)纺酸,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)址否,“玉大人餐蔬,你說我怎么就攤上這事∮痈剑” “怎么了樊诺?”我有些...
    開封第一講書人閱讀 165,345評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)音同。 經(jīng)常有香客問我词爬,道長(zhǎng),這世上最難降的妖魔是什么权均? 我笑而不...
    開封第一講書人閱讀 58,851評(píng)論 1 295
  • 正文 為了忘掉前任顿膨,我火速辦了婚禮锅锨,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘恋沃。我一直安慰自己必搞,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,868評(píng)論 6 392
  • 文/花漫 我一把揭開白布囊咏。 她就那樣靜靜地躺著恕洲,像睡著了一般。 火紅的嫁衣襯著肌膚如雪梅割。 梳的紋絲不亂的頭發(fā)上研侣,一...
    開封第一講書人閱讀 51,688評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音炮捧,去河邊找鬼庶诡。 笑死,一個(gè)胖子當(dāng)著我的面吹牛咆课,可吹牛的內(nèi)容都是我干的末誓。 我是一名探鬼主播,決...
    沈念sama閱讀 40,414評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼书蚪,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼喇澡!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起殊校,我...
    開封第一講書人閱讀 39,319評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤晴玖,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后为流,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體呕屎,經(jīng)...
    沈念sama閱讀 45,775評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評(píng)論 3 336
  • 正文 我和宋清朗相戀三年敬察,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了秀睛。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,096評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡莲祸,死狀恐怖蹂安,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情锐帜,我是刑警寧澤田盈,帶...
    沈念sama閱讀 35,789評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站缴阎,受9級(jí)特大地震影響允瞧,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,437評(píng)論 3 331
  • 文/蒙蒙 一瓷式、第九天 我趴在偏房一處隱蔽的房頂上張望替饿。 院中可真熱鬧,春花似錦贸典、人聲如沸视卢。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)据过。三九已至,卻和暖如春妒挎,著一層夾襖步出監(jiān)牢的瞬間绳锅,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評(píng)論 1 271
  • 我被黑心中介騙來(lái)泰國(guó)打工酝掩, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留鳞芙,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,308評(píng)論 3 372
  • 正文 我出身青樓期虾,卻偏偏與公主長(zhǎng)得像原朝,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子镶苞,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,037評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容