高端網(wǎng)站制作效果好/收錄網(wǎng)
🍨 本文為[🔗365天深度學(xué)習(xí)訓(xùn)練營(yíng)學(xué)習(xí)記錄博客
?
🍦 參考文章:365天深度學(xué)習(xí)訓(xùn)練營(yíng)
?
🍖 原作者:[K同學(xué)啊 | 接輔導(dǎo)、項(xiàng)目定制]\n🚀 文章來(lái)源:[K同學(xué)的學(xué)習(xí)圈子](https://www.yuque.com/mingtian-fkmxf/zxwb45)
一、加載數(shù)據(jù)?
import torch
import torch.nn as nn
import torchvision
from torchvision import transforms, datasets
import os,PIL,pathlib,warningswarnings.filterwarnings("ignore") #忽略警告信息device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)import pandas as pd# 加載自定義中文數(shù)據(jù)
train_data = pd.read_csv('D:/train.csv', sep='\t', header=None)
print(train_data)
?二、構(gòu)造數(shù)據(jù)迭代器
# 構(gòu)造數(shù)據(jù)集迭代器
def coustom_data_iter(texts, labels):for x, y in zip(texts, labels):yield x, yx = train_data[0].values[:]
#多類(lèi)標(biāo)簽的one-hot展開(kāi)
y = train_data[1].values[:]
print(x,"\n",y)
yield x, y
:使用 yield
關(guān)鍵字,將每次迭代得到的 (x, y)
元組作為迭代器的輸出。yield
的作用類(lèi)似于 return
,但不同之處在于它會(huì)暫停函數(shù)的執(zhí)行,并將結(jié)果發(fā)送給調(diào)用方,但函數(shù)的狀態(tài)會(huì)被保留,以便下次調(diào)用時(shí)從上次離開(kāi)的地方繼續(xù)執(zhí)行。?
?三、構(gòu)建詞典
from gensim.models.word2vec import Word2Vec
import numpy as np# 訓(xùn)練 Word2Vec 淺層神經(jīng)網(wǎng)絡(luò)模型
w2v = Word2Vec(vector_size=100, #是指特征向量的維度,默認(rèn)為100。min_count=3) #可以對(duì)字典做截?cái)? 詞頻少于min_count次數(shù)的單詞會(huì)被丟棄掉, 默認(rèn)值為5。w2v.build_vocab(x)
w2v.train(x, total_examples=w2v.corpus_count, epochs=20)
Word2Vec可以直接訓(xùn)練模型,一步到位。這里分了三步
-
Word2Vec(vector_size=100, min_count=3)
: 創(chuàng)建了一個(gè)Word2Vec對(duì)象,設(shè)置了詞向量的維度為100,同時(shí)設(shè)置了詞頻最小值為3,即只有在訓(xùn)練語(yǔ)料中出現(xiàn)次數(shù)不少于3次的詞才會(huì)被考慮。 -
w2v.build_vocab(x)
: 使用 build_vocab 方法根據(jù)輸入的文本數(shù)據(jù) x 構(gòu)建詞典。build_vocab 方法會(huì)統(tǒng)計(jì)輸入文本中每個(gè)詞匯出現(xiàn)的次數(shù),并按照詞頻從高到低的順序?qū)⒃~匯加入詞典中。 -
w2v.train(x, total_examples=w2v.corpus_count, epochs=20)
: 訓(xùn)練Word2Vec模型,其中:
x
是訓(xùn)練數(shù)據(jù)。total_examples=w2v.corpus_count:
total_examples 參數(shù)指定了訓(xùn)練時(shí)使用的文本數(shù)量,這里使用的是 w2v.corpus_count 屬性,表示輸入文本的數(shù)量epochs=20
指定了訓(xùn)練的輪數(shù),每輪對(duì)整個(gè)數(shù)據(jù)集進(jìn)行一次訓(xùn)練。
# 將文本轉(zhuǎn)化為向量
def average_vec(text):vec = np.zeros(100).reshape((1, 100))for word in text:try:vec += w2v.wv[word].reshape((1, 100))except KeyError:continuereturn vec# 將詞向量保存為 Ndarray
x_vec = np.concatenate([average_vec(z) for z in x])# 保存 Word2Vec 模型及詞向量
w2v.save('w2v_model.pkl')
這段代碼逐步完成了將文本轉(zhuǎn)化為詞向量的過(guò)程,并保存了Word2Vec模型及詞向量。
-
average_vec(text)
: 這個(gè)函數(shù)接受一個(gè)文本列表作為輸入,并返回一個(gè)平均詞向量。它首先創(chuàng)建了一個(gè)形狀為(1, 100)
的全零NumPy數(shù)組vec
,用于存儲(chǔ)文本的詞向量的累加和。然后,它遍歷文本中的每個(gè)詞,嘗試從已經(jīng)訓(xùn)練好的Word2Vec模型中獲取詞向量,如果詞在模型中存在,則將其詞向量加到vec
中。如果詞不在模型中(KeyError異常),則跳過(guò)該詞。最后,返回詞向量的平均值。 -
x_vec = np.concatenate([average_vec(z) for z in x])
: 這一行代碼使用列表推導(dǎo)式,對(duì)數(shù)據(jù)集中的每個(gè)文本z
調(diào)用average_vec
函數(shù),得到文本的詞向量表示。然后,使用np.concatenate
函數(shù)將這些詞向量連接成一個(gè)大的NumPy數(shù)組x_vec
。這個(gè)數(shù)組的形狀是(樣本數(shù), 100)
,其中樣本數(shù)是數(shù)據(jù)集中文本的數(shù)量。 -
w2v.save('w2v_model.pkl')
: 這一行代碼保存了訓(xùn)練好的Word2Vec模型及詞向量。w2v.save()
方法將整個(gè)Word2Vec模型保存到文件中。
train_iter = coustom_data_iter(x_vec, y)
print(len(x),len(x_vec))
-
train_iter = coustom_data_iter(x_vec, y)
: 這行代碼創(chuàng)建了一個(gè)名為train_iter
的迭代器,用于迭代訓(xùn)練數(shù)據(jù)。它調(diào)用了一個(gè)名為coustom_data_iter
的函數(shù),該函數(shù)接受兩個(gè)參數(shù)x_vec
和y
,分別表示訓(xùn)練樣本的特征和標(biāo)簽。在這個(gè)上下文中,x_vec
是一個(gè)NumPy數(shù)組,包含了訓(xùn)練樣本的特征向量表示,y
是一個(gè)數(shù)組,包含了訓(xùn)練樣本的標(biāo)簽。該迭代器將用于訓(xùn)練模型。 -
print(len(x),len(x_vec))
: 這行代碼打印了訓(xùn)練數(shù)據(jù)的長(zhǎng)度,即x
的長(zhǎng)度和x_vec
的長(zhǎng)度。在這里,len(x)
表示訓(xùn)練樣本的數(shù)量,len(x_vec)
表示每個(gè)樣本的特征向量的長(zhǎng)度(通常表示特征的維度)。這行代碼的目的是用于驗(yàn)證數(shù)據(jù)的準(zhǔn)備是否正確,以及特征向量的維度是否與預(yù)期一致。
?
label_name = list(set(train_data[1].values[:]))
print(label_name)
?四、生成數(shù)據(jù)批次和迭代器
text_pipeline = lambda x: average_vec(x)
label_pipeline = lambda x: label_name.index(x)
print(text_pipeline("你在干嘛"))
print(label_pipeline("Travel-Query"))
-
text_pipeline = lambda x: average_vec(x)
: 這一行定義了一個(gè)名為text_pipeline
的匿名函數(shù)(lambda函數(shù)),它接受一個(gè)參數(shù)x(
文本數(shù)據(jù))。在函數(shù)體內(nèi)部,它調(diào)用了前面定義的average_vec
函數(shù),將文本數(shù)據(jù)x
轉(zhuǎn)換為詞向量的平均值。 -
label_pipeline = lambda x: label_name.index(x)
: 這一行定義了另一個(gè)匿名函數(shù)label_pipeline
,它接受一個(gè)參數(shù)x
,該參數(shù)表示標(biāo)簽數(shù)據(jù)。在函數(shù)體內(nèi)部,它調(diào)用了index
方法來(lái)查找標(biāo)簽在label_name
列表中的索引,并返回該索引值。 -
print(text_pipeline("你在干嘛"))
: 這行代碼調(diào)用了text_pipeline
函數(shù),將字符串 "你在干嘛" 作為參數(shù)傳遞給函數(shù)。函數(shù)會(huì)將這個(gè)文本轉(zhuǎn)換為詞向量的平均值,并打印出來(lái)。 -
print(label_pipeline("Travel-Query"))
: 這行代碼調(diào)用了label_pipeline
函數(shù),將字符串 "Travel-Query" 作為參數(shù)傳遞給函數(shù)。函數(shù)會(huì)在label_name
列表中查找 "Travel-Query" 的索引,并打印出來(lái)。
?
from torch.utils.data import DataLoaderdef collate_batch(batch):label_list, text_list= [], []for (_text, _label) in batch:# 標(biāo)簽列表label_list.append(label_pipeline(_label))# 文本列表processed_text = torch.tensor(text_pipeline(_text), dtype=torch.float32)text_list.append(processed_text)label_list = torch.tensor(label_list, dtype=torch.int64)text_list = torch.cat(text_list)return text_list.to(device),label_list.to(device)# 數(shù)據(jù)加載器,調(diào)用示例
dataloader = DataLoader(train_iter,batch_size=8,shuffle =False,collate_fn=collate_batch)
-
text_pipeline = lambda x: average_vec(x)
: 這行代碼創(chuàng)建了一個(gè)名為text_pipeline
的匿名函數(shù),該函數(shù)接受一個(gè)參數(shù)x
,表示文本數(shù)據(jù)。在這里,text_pipeline
函數(shù)被定義為average_vec(x)
,即調(diào)用之前定義的average_vec
函數(shù),用來(lái)將文本轉(zhuǎn)換為向量表示。 -
label_pipeline = lambda x: label_name.index(x)
: 這行代碼創(chuàng)建了一個(gè)名為label_pipeline
的匿名函數(shù),該函數(shù)接受一個(gè)參數(shù)x
,表示標(biāo)簽數(shù)據(jù)。在這里,label_pipeline
函數(shù)被定義為label_name.index(x)
,即查找x
在label_name
列表中的索引,返回其索引值作為標(biāo)簽的表示。 -
collate_batch(batch)
: 這是一個(gè)自定義的函數(shù),用于處理一個(gè)批次(batch)的數(shù)據(jù)。它接受一個(gè)批次的數(shù)據(jù)作為輸入,并對(duì)數(shù)據(jù)進(jìn)行處理,最后返回處理后的文本和標(biāo)簽列表。 -
在
collate_batch
函數(shù)中:- 首先,創(chuàng)建了兩個(gè)空列表
label_list
和text_list
,用于存儲(chǔ)標(biāo)簽和文本數(shù)據(jù)。 - 然后,對(duì)批次中的每個(gè)樣本進(jìn)行遍歷,提取樣本的文本和標(biāo)簽。
- 對(duì)于標(biāo)簽部分,調(diào)用了
label_pipeline
函數(shù)將標(biāo)簽轉(zhuǎn)換為模型可接受的格式,并添加到label_list
中。 - 對(duì)于文本部分,調(diào)用了
text_pipeline
函數(shù)將文本轉(zhuǎn)換為向量表示,并轉(zhuǎn)換為 PyTorch 張量格式,并添加到text_list
中。 - 最后,將
label_list
轉(zhuǎn)換為 PyTorch 整數(shù)張量格式,將text_list
進(jìn)行拼接并轉(zhuǎn)換為 PyTorch 浮點(diǎn)數(shù)張量格式,并返回這兩個(gè)張量。
- 首先,創(chuàng)建了兩個(gè)空列表
-
dataloader = DataLoader(train_iter, batch_size=8, shuffle=False, collate_fn=collate_batch)
: 這行代碼創(chuàng)建了一個(gè) PyTorch 的數(shù)據(jù)加載器DataLoader
,用于加載訓(xùn)練數(shù)據(jù)。其中參數(shù)說(shuō)明如下:train_iter
是之前定義的用于迭代訓(xùn)練數(shù)據(jù)的迭代器。batch_size=8
指定了每個(gè)批次的樣本數(shù)量為 8。shuffle=False
表示不對(duì)數(shù)據(jù)進(jìn)行洗牌,即不打亂樣本的順序。collate_fn=collate_batch
指定了數(shù)據(jù)加載器在每個(gè)批次加載數(shù)據(jù)時(shí)調(diào)用的數(shù)據(jù)處理函數(shù)為collate_batch
函數(shù),用于處理每個(gè)批次的數(shù)據(jù)。
?
五、構(gòu)建模型
from torch import nnclass TextClassificationModel(nn.Module):def __init__(self, num_class):super(TextClassificationModel, self).__init__()self.fc = nn.Linear(100, num_class)def forward(self, text):return self.fc(text)num_class = len(label_name)
vocab_size = 100000
em_size = 12
model = TextClassificationModel(num_class).to(device)import timedef train(dataloader):model.train() # 切換為訓(xùn)練模式total_acc, train_loss, total_count = 0, 0, 0log_interval = 50start_time = time.time()for idx, (text,label) in enumerate(dataloader):predicted_label = model(text)optimizer.zero_grad() # grad屬性歸零loss = criterion(predicted_label, label) # 計(jì)算網(wǎng)絡(luò)輸出和真實(shí)值之間的差距,label為真實(shí)值loss.backward() # 反向傳播torch.nn.utils.clip_grad_norm_(model.parameters(), 0.1) # 梯度裁剪optimizer.step() # 每一步自動(dòng)更新# 記錄acc與losstotal_acc += (predicted_label.argmax(1) == label).sum().item()train_loss += loss.item()total_count += label.size(0)if idx % log_interval == 0 and idx > 0:elapsed = time.time() - start_timeprint('| epoch {:1d} | {:4d}/{:4d} batches ''| train_acc {:4.3f} train_loss {:4.5f}'.format(epoch, idx,len(dataloader),total_acc/total_count, train_loss/total_count))total_acc, train_loss, total_count = 0, 0, 0start_time = time.time()def evaluate(dataloader):model.eval() # 切換為測(cè)試模式total_acc, train_loss, total_count = 0, 0, 0with torch.no_grad():for idx, (text,label) in enumerate(dataloader):predicted_label = model(text)loss = criterion(predicted_label, label) # 計(jì)算loss值# 記錄測(cè)試數(shù)據(jù)total_acc += (predicted_label.argmax(1) == label).sum().item()train_loss += loss.item()total_count += label.size(0)return total_acc/total_count, train_loss/total_count
六、訓(xùn)練模型
from torch.utils.data.dataset import random_split
from torchtext.data.functional import to_map_style_dataset
# 超參數(shù)
EPOCHS = 10 # epoch
LR = 5 # 學(xué)習(xí)率
BATCH_SIZE = 64 # batch size for trainingcriterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=LR)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1.0, gamma=0.1)
total_accu = None# 構(gòu)建數(shù)據(jù)集
train_iter = coustom_data_iter(train_data[0].values[:], train_data[1].values[:])
train_dataset = to_map_style_dataset(train_iter)split_train_, split_valid_ = random_split(train_dataset,[int(len(train_dataset)*0.8),int(len(train_dataset)*0.2)])train_dataloader = DataLoader(split_train_, batch_size=BATCH_SIZE,shuffle=True, collate_fn=collate_batch)valid_dataloader = DataLoader(split_valid_, batch_size=BATCH_SIZE,shuffle=True, collate_fn=collate_batch)for epoch in range(1, EPOCHS + 1):epoch_start_time = time.time()train(train_dataloader)val_acc, val_loss = evaluate(valid_dataloader)# 獲取當(dāng)前的學(xué)習(xí)率lr = optimizer.state_dict()['param_groups'][0]['lr']if total_accu is not None and total_accu > val_acc:scheduler.step()else:total_accu = val_accprint('-' * 69)print('| epoch {:1d} | time: {:4.2f}s | ''valid_acc {:4.3f} valid_loss {:4.3f} | lr {:4.6f}'.format(epoch,time.time() - epoch_start_time,val_acc,val_loss,lr))print('-' * 69)test_acc, test_loss = evaluate(valid_dataloader)
print('模型準(zhǔn)確率為:{:5.4f}'.format(test_acc))
| epoch 1 | 50/ 152 batches | train_acc 0.732 train_loss 0.02655
| epoch 1 | 100/ 152 batches | train_acc 0.822 train_loss 0.01889
| epoch 1 | 150/ 152 batches | train_acc 0.838 train_loss 0.01798
---------------------------------------------------------------------
| epoch 1 | time: 0.93s | valid_acc 0.812 valid_loss 0.019 | lr 5.000000
---------------------------------------------------------------------
| epoch 2 | 50/ 152 batches | train_acc 0.840 train_loss 0.01745
| epoch 2 | 100/ 152 batches | train_acc 0.843 train_loss 0.01807
| epoch 2 | 150/ 152 batches | train_acc 0.843 train_loss 0.01846
---------------------------------------------------------------------
| epoch 2 | time: 1.01s | valid_acc 0.854 valid_loss 0.020 | lr 5.000000
---------------------------------------------------------------------
| epoch 3 | 50/ 152 batches | train_acc 0.850 train_loss 0.01770
| epoch 3 | 100/ 152 batches | train_acc 0.850 train_loss 0.01675
| epoch 3 | 150/ 152 batches | train_acc 0.859 train_loss 0.01565
---------------------------------------------------------------------
| epoch 3 | time: 0.98s | valid_acc 0.836 valid_loss 0.023 | lr 5.000000
---------------------------------------------------------------------
| epoch 4 | 50/ 152 batches | train_acc 0.898 train_loss 0.00972
| epoch 4 | 100/ 152 batches | train_acc 0.892 train_loss 0.00936
| epoch 4 | 150/ 152 batches | train_acc 0.900 train_loss 0.00948
---------------------------------------------------------------------
| epoch 4 | time: 0.91s | valid_acc 0.879 valid_loss 0.011 | lr 0.500000
---------------------------------------------------------------------
| epoch 5 | 50/ 152 batches | train_acc 0.911 train_loss 0.00679
| epoch 5 | 100/ 152 batches | train_acc 0.899 train_loss 0.00786
| epoch 5 | 150/ 152 batches | train_acc 0.903 train_loss 0.00752
---------------------------------------------------------------------
| epoch 5 | time: 0.91s | valid_acc 0.879 valid_loss 0.010 | lr 0.500000
---------------------------------------------------------------------
| epoch 6 | 50/ 152 batches | train_acc 0.905 train_loss 0.00692
| epoch 6 | 100/ 152 batches | train_acc 0.915 train_loss 0.00595
| epoch 6 | 150/ 152 batches | train_acc 0.910 train_loss 0.00615
---------------------------------------------------------------------
| epoch 6 | time: 0.90s | valid_acc 0.880 valid_loss 0.010 | lr 0.050000
---------------------------------------------------------------------
| epoch 7 | 50/ 152 batches | train_acc 0.907 train_loss 0.00615
| epoch 7 | 100/ 152 batches | train_acc 0.911 train_loss 0.00602
| epoch 7 | 150/ 152 batches | train_acc 0.908 train_loss 0.00632
---------------------------------------------------------------------
| epoch 7 | time: 0.92s | valid_acc 0.881 valid_loss 0.009 | lr 0.050000
---------------------------------------------------------------------
| epoch 8 | 50/ 152 batches | train_acc 0.903 train_loss 0.00656
| epoch 8 | 100/ 152 batches | train_acc 0.915 train_loss 0.00582
| epoch 8 | 150/ 152 batches | train_acc 0.912 train_loss 0.00578
---------------------------------------------------------------------
| epoch 8 | time: 0.93s | valid_acc 0.881 valid_loss 0.009 | lr 0.050000
---------------------------------------------------------------------
| epoch 9 | 50/ 152 batches | train_acc 0.903 train_loss 0.00653
| epoch 9 | 100/ 152 batches | train_acc 0.913 train_loss 0.00595
| epoch 9 | 150/ 152 batches | train_acc 0.914 train_loss 0.00549
---------------------------------------------------------------------
| epoch 9 | time: 0.93s | valid_acc 0.877 valid_loss 0.009 | lr 0.050000
---------------------------------------------------------------------
| epoch 10 | 50/ 152 batches | train_acc 0.911 train_loss 0.00565
| epoch 10 | 100/ 152 batches | train_acc 0.908 train_loss 0.00584
| epoch 10 | 150/ 152 batches | train_acc 0.909 train_loss 0.00604
---------------------------------------------------------------------
| epoch 10 | time: 0.91s | valid_acc 0.878 valid_loss 0.009 | lr 0.005000
---------------------------------------------------------------------
模型準(zhǔn)確率為:0.8781
七、測(cè)試指定數(shù)據(jù)?
def predict(text, text_pipeline):with torch.no_grad():text = torch.tensor(text_pipeline(text), dtype=torch.float32)print(text.shape)output = model(text)return output.argmax(1).item()# ex_text_str = "隨便播放一首專(zhuān)輯閣樓里的佛里的歌"
ex_text_str = "還有雙鴨山到淮陰的汽車(chē)票嗎13號(hào)的"model = model.to("cpu")print("該文本的類(lèi)別是:%s" %label_name[predict(ex_text_str, text_pipeline)])