【Pytorch神经网络实战案例】22 基于Cora数据集实现图注意力神经网络GAT的论文分类
注意力機制的特點是,它的輸入向量長度可變,通過將注意力集中在最相關(guān)的部分來做出決定。注意力機制結(jié)合RNN或者CNN的方法。
1 實戰(zhàn)描述
【主要目的:將注意力機制用在圖神經(jīng)網(wǎng)絡(luò)中,完成圖注意力神經(jīng)網(wǎng)絡(luò)的結(jié)構(gòu)和搭建】
1.1 實現(xiàn)目的
有一個記錄論文信息的數(shù)據(jù)集,數(shù)據(jù)集里面含有每一篇論文的關(guān)鍵詞以及分類信息,同時還有論文間互相引用的信息。搭建AI模型,對數(shù)據(jù)集中的論文信息進行分析,使模型學(xué)習(xí)已有論文的分類特征,以便預(yù)測出未知分類的論文類別。
1.2 圖注意力網(wǎng)絡(luò)圖
圖注意力網(wǎng)絡(luò)(GraphAttention Network,GAT)在GCN的基礎(chǔ)上添加了一個隱藏的自注意力(self-attention)層。通過疊加Self-attention層,在卷積過程中可將不同的權(quán)重分配給鄰域內(nèi)的不同頂點,同時處理不同大小的鄰域。
在實際計算時,自注意力機制可以使用多套權(quán)重同時進行計算,并且彼此之間不共享權(quán)重,能夠使頂點確定知識的相關(guān)性,是否可忽略。
?2 代碼編寫
本次要構(gòu)建的圖網(wǎng)絡(luò)
2.1 代碼實戰(zhàn):引入基礎(chǔ)模塊,設(shè)置運行環(huán)境----Cora_GAT.py(第1部分)
from pathlib import Path # 引入提升路徑的兼容性 # 引入矩陣運算的相關(guān)庫 import numpy as np import pandas as pd from scipy.sparse import coo_matrix,csr_matrix,diags,eye # 引入深度學(xué)習(xí)框架庫 import torch from torch import nn import torch.nn.functional as F # 引入繪圖庫 import matplotlib.pyplot as plt import os os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"# 1.1 導(dǎo)入基礎(chǔ)模塊,并設(shè)置運行環(huán)境 # 輸出計算資源情況 device = torch.device('cuda')if torch.cuda.is_available() else torch.device('cpu') print(device) # 輸出 cuda# 輸出樣本路徑 path = Path('./data/cora') print(path) # 輸出 cuda輸出結(jié)果:
2.2 代碼實現(xiàn):讀取并解析論文數(shù)據(jù)----Cora_GAT.py(第2部分)
# 1.2 讀取并解析論文數(shù)據(jù) # 讀取論文內(nèi)容數(shù)據(jù),將其轉(zhuǎn)化為數(shù)據(jù) paper_features_label = np.genfromtxt(path/'cora.content',dtype=np.str_) # 使用Path對象的路徑構(gòu)造,實例化的內(nèi)容為cora.content。path/'cora.content'表示路徑為'data/cora/cora.content'的字符串 print(paper_features_label,np.shape(paper_features_label)) # 打印數(shù)據(jù)集內(nèi)容與數(shù)據(jù)的形狀# 取出數(shù)據(jù)集中的第一列:論文ID papers = paper_features_label[:,0].astype(np.int32) print("論文ID序列:",papers) # 輸出所有論文ID # 論文重新編號,并將其映射到論文ID中,實現(xiàn)論文的統(tǒng)一管理 paper2idx = {k:v for v,k in enumerate(papers)}# 將數(shù)據(jù)中間部分的字標(biāo)簽取出,轉(zhuǎn)化成矩陣 features = csr_matrix(paper_features_label[:,1:-1],dtype=np.float32) print("字標(biāo)簽矩陣的形狀:",np.shape(features)) # 字標(biāo)簽矩陣的形狀# 將數(shù)據(jù)的最后一項的文章分類屬性取出,轉(zhuǎn)化為分類的索引 labels = paper_features_label[:,-1] lbl2idx = { k:v for v,k in enumerate(sorted(np.unique(labels)))} labels = [lbl2idx[e] for e in labels] print("論文類別的索引號:",lbl2idx,labels[:5])輸出:
2.3 讀取并解析論文關(guān)系數(shù)據(jù)
載入論文的關(guān)系數(shù)據(jù),將數(shù)據(jù)中用論文ID表示的關(guān)系轉(zhuǎn)化成重新編號后的關(guān)系,將每篇論文當(dāng)作一個頂點,論文間的引用關(guān)系作為邊,這樣論文的關(guān)系數(shù)據(jù)就可以用一個圖結(jié)構(gòu)來表示。
?計算該圖結(jié)構(gòu)的鄰接矩陣并將其轉(zhuǎn)化為無向圖鄰接矩陣。
2.3.1 代碼實現(xiàn):轉(zhuǎn)化矩陣----Cora_GAT.py(第3部分)
# 1.3 讀取并解析論文關(guān)系數(shù)據(jù) # 讀取論文關(guān)系數(shù)據(jù),并將其轉(zhuǎn)化為數(shù)據(jù) edges = np.genfromtxt(path/'cora.cites',dtype=np.int32) # 將數(shù)據(jù)集中論文的引用關(guān)系以數(shù)據(jù)的形式讀入 print(edges,np.shape(edges)) # 轉(zhuǎn)化為新編號節(jié)點間的關(guān)系:將數(shù)據(jù)集中論文ID表示的關(guān)系轉(zhuǎn)化為重新編號后的關(guān)系 edges = np.asarray([paper2idx[e] for e in edges.flatten()],np.int32).reshape(edges.shape) print("新編號節(jié)點間的對應(yīng)關(guān)系:",edges,edges.shape) # 計算鄰接矩陣,行與列都是論文個數(shù):由論文引用關(guān)系所表示的圖結(jié)構(gòu)生成鄰接矩陣。 adj = coo_matrix((np.ones(edges.shape[0]), (edges[:, 0], edges[:, 1])),shape=(len(labels), len(labels)), dtype=np.float32) # 生成無向圖對稱矩陣:將有向圖的鄰接矩陣轉(zhuǎn)化為無向圖的鄰接矩陣。Tip:轉(zhuǎn)化為無向圖的原因:主要用于對論文的分類,論文的引用關(guān)系主要提供單個特征之間的關(guān)聯(lián),故更看重是不是有關(guān)系,所以無向圖即可。 adj_long = adj.multiply(adj.T < adj) adj = adj_long + adj_long.T輸出:
2.4 代碼實現(xiàn):加工圖結(jié)構(gòu)的矩陣數(shù)據(jù)----Cora_GAT.py(第4部分)
# 1.4 加工圖結(jié)構(gòu)的矩陣數(shù)據(jù) def normalize_adj(mx):rowsum = np.array(mx.sum(1))r_inv = np.power(rowsum,-0.5).flatten()r_inv[np.isinf(r_inv)] = 0.0r_mat_inv = diags(r_inv)return mx.dot(r_mat_inv).transpose().dot(r_mat_inv) # 兌成歸一化拉普拉斯矩陣實現(xiàn)鄰接矩陣的轉(zhuǎn)化adj = normalize_adj(adj + eye(adj.shape[0])) # 對鄰接矩陣進行轉(zhuǎn)化對稱歸一化拉普拉斯矩陣轉(zhuǎn)化2.5 將數(shù)據(jù)轉(zhuǎn)化為張量,并分配運算資源
將加工好的圖結(jié)構(gòu)矩陣數(shù)據(jù)轉(zhuǎn)為PyTorch支持的張量類型,并將其分成3份,分別用來進行訓(xùn)練、測試和驗證。
2.5.1?代碼實現(xiàn):將數(shù)據(jù)轉(zhuǎn)化為張量,并分配運算資源----Cora_GAT.py(第5部分)
# 1.5 將數(shù)據(jù)轉(zhuǎn)化為張量,并分配運算資源 adj = torch.FloatTensor(adj.todense()) # 節(jié)點間關(guān)系 todense()方法將其轉(zhuǎn)換回稠密矩陣。 features = torch.FloatTensor(features.todense()) # 節(jié)點自身的特征 labels = torch.LongTensor(labels) # 對每個節(jié)點的分類標(biāo)簽# 劃分數(shù)據(jù)集 n_train = 200 # 訓(xùn)練數(shù)據(jù)集大小 n_val = 300 # 驗證數(shù)據(jù)集大小 n_test = len(features) - n_train - n_val # 測試數(shù)據(jù)集大小 np.random.seed(34) idxs = np.random.permutation(len(features)) # 將原有的索引打亂順序# 計算每個數(shù)據(jù)集的索引 idx_train = torch.LongTensor(idxs[:n_train]) # 根據(jù)指定訓(xùn)練數(shù)據(jù)集的大小并劃分出其對應(yīng)的訓(xùn)練數(shù)據(jù)集索引 idx_val = torch.LongTensor(idxs[n_train:n_train+n_val])# 根據(jù)指定驗證數(shù)據(jù)集的大小并劃分出其對應(yīng)的驗證數(shù)據(jù)集索引 idx_test = torch.LongTensor(idxs[n_train+n_val:])# 根據(jù)指定測試數(shù)據(jù)集的大小并劃分出其對應(yīng)的測試數(shù)據(jù)集索引# 分配運算資源 adj = adj.to(device) features = features.to(device) labels = labels.to(device) idx_train = idx_train.to(device) idx_val = idx_val.to(device) idx_test = idx_test.to(device)2.6 代碼實現(xiàn):定義Mish激活函數(shù)與圖注意力層類----Cora_GAT.py(第6部分)
# 1.6 定義Mish激活函數(shù)與圖注意力層類 def mish(x): # 性能優(yōu)于RElu函數(shù)return x * (torch.tanh(F.softplus(x))) # 圖注意力層類 class GraphAttentionLayer(nn.Module): # 圖注意力層# 初始化def __init__(self,in_features,out_features,dropout=0.6):super(GraphAttentionLayer, self).__init__()self.dropout = dropoutself.in_features = in_features # 定義輸入特征維度self.out_features = out_features # 定義輸出特征維度self.W = nn.Parameter(torch.zeros(size=(in_features,out_features)))nn.init.xavier_uniform_(self.W) # 初始化全連接權(quán)重self.a = nn.Parameter(torch.zeros(size=(2 * out_features,1)))nn.init.xavier_uniform_(self.a) # 初始化注意力權(quán)重def forward(self,input,adj):h = torch.mm(input,self.W) # 全連接處理N = h.size()[0]# 對全連接后的特征數(shù)據(jù)分別進行基于批次維度和特征維度的復(fù)制,并將復(fù)制結(jié)果連接在一起。# 這種操作使得頂點中的特征數(shù)據(jù)進行了充分的排列組合,結(jié)果中的每行信息都包含兩個頂點特征。接下來的注意力機制便是基于每對頂點特征進行計算的。a_input = torch.cat([h.repeat(1,N).view(N * N ,-1),h.repeat(N,1)],dim=1).view(N,-1,2 * self.out_features) # 主要功能將頂點特征兩兩搭配,連接在一起,生成數(shù)據(jù)形狀[N,N,2 * self.out_features]e = mish(torch.matmul(a_input,self.a).squeeze(2)) # 計算注意力zero_vec = -9e15 * torch.ones_like(e) # 初始化最小值:該值用于填充被過濾掉的特征對象atenion。如果在過濾時,直接對過濾排的特征賦值為0,那么模型會無法收斂。attention = torch.where(adj>0,e,zero_vec) # 過濾注意力 :按照鄰接矩陣中大于0的邊對注意力結(jié)果進行過濾,使注意力按照圖中的頂點配對的范圍進行計算。attention = F.softmax(attention,dim=1) # 對注意力分數(shù)進行歸一化:使用F.Sofmax()函數(shù)對最終的注意力機制進行歸一化,得到注意力分數(shù)(總和為1)。attention = F.dropout(attention,self.dropout,training=self.training)h_prime = torch.matmul(attention,h) # 使用注意力處理特征:將最終的注意力作用到全連接的結(jié)果上以完成計算。return mish(h_prime)2.7 代碼實現(xiàn):搭建圖注意力模型----Cora_GAT.py(第7部分)
# 1.7 搭建圖注意力模型 class GAT(nn.Module):# 圖注意力模型類def __init__(self,nfeat,nclasses,nhid,dropout,nheads): # 圖注意力模型類的初始化方法,支持多套注意力機制同時運算,其參數(shù)nheads用于指定注意力的計算套數(shù)。super(GAT, self).__init__()# 注意力層self.attentions = [GraphAttentionLayer(nfeat,nhid,dropout) for _ in range(nheads)] # 按照指定的注意力套數(shù)生成多套注意力層for i , attention in enumerate(self.attentions): # 將注意力層添加到模型self.add_module('attention_{}'.format(i),attention)# 輸出層self.out_att = GraphAttentionLayer(nhid * nheads,nclasses,dropout)def forward(self,x,adj): # 定義正向傳播方法x = torch.cat([att(x, adj) for att in self.attentions], dim=1)return self.out_att(x, adj)n_labels = labels.max().item() + 1 # 獲取分類個數(shù)7 n_features = features.shape[1] # 獲取節(jié)點特征維度 1433 print(n_labels,n_features) # 輸出7與1433def accuracy(output,y): # 定義函數(shù)計算準(zhǔn)確率return (output.argmax(1) == y).type(torch.float32).mean().item()### 定義函數(shù)來實現(xiàn)模型的訓(xùn)練過程。與深度學(xué)習(xí)任務(wù)不同,圖卷積在訓(xùn)練時需要傳入樣本間的關(guān)系數(shù)據(jù)。 # 因為該關(guān)系數(shù)據(jù)是與節(jié)點數(shù)相等的方陣,所以傳入的樣本數(shù)也要與節(jié)點數(shù)相同,在計算loss值時,可以通過索引從總的運算結(jié)果中取出訓(xùn)練集的結(jié)果。 def step(): # 定義函數(shù)來訓(xùn)練模型 Tip:在圖卷積任務(wù)中,無論是用模型進行預(yù)測還是訓(xùn)練,都需要將全部的圖結(jié)構(gòu)方陣輸入model.train()optimizer.zero_grad()output = model(features,adj) # 將全部數(shù)據(jù)載入模型,只用訓(xùn)練數(shù)據(jù)計算損失loss = F.cross_entropy(output[idx_train],labels[idx_train])acc = accuracy(output[idx_train],labels[idx_train]) # 計算準(zhǔn)確率loss.backward()optimizer.step()return loss.item(),accdef evaluate(idx): # 定義函數(shù)來評估模型 Tip:在圖卷積任務(wù)中,無論是用模型進行預(yù)測還是訓(xùn)練,都需要將全部的圖結(jié)構(gòu)方陣輸入model.eval()output = model(features, adj) # 將全部數(shù)據(jù)載入模型,用指定索引評估模型結(jié)果loss = F.cross_entropy(output[idx], labels[idx]).item()return loss, accuracy(output[idx], labels[idx])2.8?Ranger優(yōu)化器
圖卷積神經(jīng)網(wǎng)絡(luò)的層數(shù)不宜過多,一般在3層左右即可。本例將實現(xiàn)一個3層的圖卷積神經(jīng)網(wǎng)絡(luò),每層的維度變化如圖9-15所示。
使用循環(huán)語句訓(xùn)練模型,并將模型結(jié)果可視化。
2.8.1 代碼實現(xiàn):用Ranger優(yōu)化器訓(xùn)練模型并可視化結(jié)果----Cora_GAT.py(第8部分)
# 1.8 使用Ranger優(yōu)化器訓(xùn)練模型并可視化 model = GAT(n_features, n_labels, 16,0.1,8).to(device) # 向GAT傳入的后3個參數(shù)分別代表輸出維度(16)、Dropout的丟棄率(0.1)、注意力的計算套數(shù)(8)from tqdm import tqdm from Cora_ranger import * # 引入Ranger優(yōu)化器 optimizer = Ranger(model.parameters()) # 使用Ranger優(yōu)化器# 訓(xùn)練模型 epochs = 1000 print_steps = 50 train_loss, train_acc = [], [] val_loss, val_acc = [], [] for i in tqdm(range(epochs)):tl,ta = step()train_loss = train_loss + [tl]train_acc = train_acc + [ta]if (i+1) % print_steps == 0 or i == 0:tl,ta = evaluate(idx_train)vl,va = evaluate(idx_val)val_loss = val_loss + [vl]val_acc = val_acc + [va]print(f'{i + 1:6d}/{epochs}: train_loss={tl:.4f}, train_acc={ta:.4f}' + f', val_loss={vl:.4f}, val_acc={va:.4f}')# 輸出最終結(jié)果 final_train, final_val, final_test = evaluate(idx_train), evaluate(idx_val), evaluate(idx_test) print(f'Train : loss={final_train[0]:.4f}, accuracy={final_train[1]:.4f}') print(f'Validation: loss={final_val[0]:.4f}, accuracy={final_val[1]:.4f}') print(f'Test : loss={final_test[0]:.4f}, accuracy={final_test[1]:.4f}')# 可視化訓(xùn)練過程 fig, axes = plt.subplots(1, 2, figsize=(15,5)) ax = axes[0] axes[0].plot(train_loss[::print_steps] + [train_loss[-1]], label='Train') axes[0].plot(val_loss, label='Validation') axes[1].plot(train_acc[::print_steps] + [train_acc[-1]], label='Train') axes[1].plot(val_acc, label='Validation') for ax,t in zip(axes, ['Loss', 'Accuracy']): ax.legend(), ax.set_title(t, size=15)# 輸出模型的預(yù)測結(jié)果 output = model(features, adj) samples = 10 idx_sample = idx_test[torch.randperm(len(idx_test))[:samples]] # 將樣本標(biāo)簽與預(yù)測結(jié)果進行比較 idx2lbl = {v:k for k,v in lbl2idx.items()} df = pd.DataFrame({'Real': [idx2lbl[e] for e in labels[idx_sample].tolist()],'Pred': [idx2lbl[e] for e in output[idx_sample].argmax(1).tolist()]}) print(df)2.7 程序輸出匯總
2.7.1 訓(xùn)練過程?
2.7.2 訓(xùn)練結(jié)果
3 代碼匯總
3.1 Cora_GAT.py
from pathlib import Path # 引入提升路徑的兼容性 # 引入矩陣運算的相關(guān)庫 import numpy as np import pandas as pd from scipy.sparse import coo_matrix,csr_matrix,diags,eye # 引入深度學(xué)習(xí)框架庫 import torch from torch import nn import torch.nn.functional as F # 引入繪圖庫 import matplotlib.pyplot as plt import os os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"# 1.1 導(dǎo)入基礎(chǔ)模塊,并設(shè)置運行環(huán)境 # 輸出計算資源情況 device = torch.device('cuda')if torch.cuda.is_available() else torch.device('cpu') print(device) # 輸出 cuda# 輸出樣本路徑 path = Path('./data/cora') print(path) # 輸出 cuda# 1.2 讀取并解析論文數(shù)據(jù) # 讀取論文內(nèi)容數(shù)據(jù),將其轉(zhuǎn)化為數(shù)據(jù) paper_features_label = np.genfromtxt(path/'cora.content',dtype=np.str_) # 使用Path對象的路徑構(gòu)造,實例化的內(nèi)容為cora.content。path/'cora.content'表示路徑為'data/cora/cora.content'的字符串 print(paper_features_label,np.shape(paper_features_label)) # 打印數(shù)據(jù)集內(nèi)容與數(shù)據(jù)的形狀# 取出數(shù)據(jù)集中的第一列:論文ID papers = paper_features_label[:,0].astype(np.int32) print("論文ID序列:",papers) # 輸出所有論文ID # 論文重新編號,并將其映射到論文ID中,實現(xiàn)論文的統(tǒng)一管理 paper2idx = {k:v for v,k in enumerate(papers)}# 將數(shù)據(jù)中間部分的字標(biāo)簽取出,轉(zhuǎn)化成矩陣 features = csr_matrix(paper_features_label[:,1:-1],dtype=np.float32) print("字標(biāo)簽矩陣的形狀:",np.shape(features)) # 字標(biāo)簽矩陣的形狀# 將數(shù)據(jù)的最后一項的文章分類屬性取出,轉(zhuǎn)化為分類的索引 labels = paper_features_label[:,-1] lbl2idx = { k:v for v,k in enumerate(sorted(np.unique(labels)))} labels = [lbl2idx[e] for e in labels] print("論文類別的索引號:",lbl2idx,labels[:5])# 1.3 讀取并解析論文關(guān)系數(shù)據(jù) # 讀取論文關(guān)系數(shù)據(jù),并將其轉(zhuǎn)化為數(shù)據(jù) edges = np.genfromtxt(path/'cora.cites',dtype=np.int32) # 將數(shù)據(jù)集中論文的引用關(guān)系以數(shù)據(jù)的形式讀入 print(edges,np.shape(edges)) # 轉(zhuǎn)化為新編號節(jié)點間的關(guān)系:將數(shù)據(jù)集中論文ID表示的關(guān)系轉(zhuǎn)化為重新編號后的關(guān)系 edges = np.asarray([paper2idx[e] for e in edges.flatten()],np.int32).reshape(edges.shape) print("新編號節(jié)點間的對應(yīng)關(guān)系:",edges,edges.shape) # 計算鄰接矩陣,行與列都是論文個數(shù):由論文引用關(guān)系所表示的圖結(jié)構(gòu)生成鄰接矩陣。 adj = coo_matrix((np.ones(edges.shape[0]), (edges[:, 0], edges[:, 1])),shape=(len(labels), len(labels)), dtype=np.float32) # 生成無向圖對稱矩陣:將有向圖的鄰接矩陣轉(zhuǎn)化為無向圖的鄰接矩陣。Tip:轉(zhuǎn)化為無向圖的原因:主要用于對論文的分類,論文的引用關(guān)系主要提供單個特征之間的關(guān)聯(lián),故更看重是不是有關(guān)系,所以無向圖即可。 adj_long = adj.multiply(adj.T < adj) adj = adj_long + adj_long.T# 1.4 加工圖結(jié)構(gòu)的矩陣數(shù)據(jù) def normalize_adj(mx):rowsum = np.array(mx.sum(1))r_inv = np.power(rowsum,-0.5).flatten()r_inv[np.isinf(r_inv)] = 0.0r_mat_inv = diags(r_inv)return mx.dot(r_mat_inv).transpose().dot(r_mat_inv) # 兌成歸一化拉普拉斯矩陣實現(xiàn)鄰接矩陣的轉(zhuǎn)化adj = normalize_adj(adj + eye(adj.shape[0])) # 對鄰接矩陣進行轉(zhuǎn)化對稱歸一化拉普拉斯矩陣轉(zhuǎn)化# 1.5 將數(shù)據(jù)轉(zhuǎn)化為張量,并分配運算資源 adj = torch.FloatTensor(adj.todense()) # 節(jié)點間關(guān)系 todense()方法將其轉(zhuǎn)換回稠密矩陣。 features = torch.FloatTensor(features.todense()) # 節(jié)點自身的特征 labels = torch.LongTensor(labels) # 對每個節(jié)點的分類標(biāo)簽# 劃分數(shù)據(jù)集 n_train = 200 # 訓(xùn)練數(shù)據(jù)集大小 n_val = 300 # 驗證數(shù)據(jù)集大小 n_test = len(features) - n_train - n_val # 測試數(shù)據(jù)集大小 np.random.seed(34) idxs = np.random.permutation(len(features)) # 將原有的索引打亂順序# 計算每個數(shù)據(jù)集的索引 idx_train = torch.LongTensor(idxs[:n_train]) # 根據(jù)指定訓(xùn)練數(shù)據(jù)集的大小并劃分出其對應(yīng)的訓(xùn)練數(shù)據(jù)集索引 idx_val = torch.LongTensor(idxs[n_train:n_train+n_val])# 根據(jù)指定驗證數(shù)據(jù)集的大小并劃分出其對應(yīng)的驗證數(shù)據(jù)集索引 idx_test = torch.LongTensor(idxs[n_train+n_val:])# 根據(jù)指定測試數(shù)據(jù)集的大小并劃分出其對應(yīng)的測試數(shù)據(jù)集索引# 分配運算資源 adj = adj.to(device) features = features.to(device) labels = labels.to(device) idx_train = idx_train.to(device) idx_val = idx_val.to(device) idx_test = idx_test.to(device)# 1.6 定義Mish激活函數(shù)與圖注意力層類 def mish(x): # 性能優(yōu)于RElu函數(shù)return x * (torch.tanh(F.softplus(x))) # 圖注意力層類 class GraphAttentionLayer(nn.Module): # 圖注意力層# 初始化def __init__(self,in_features,out_features,dropout=0.6):super(GraphAttentionLayer, self).__init__()self.dropout = dropoutself.in_features = in_features # 定義輸入特征維度self.out_features = out_features # 定義輸出特征維度self.W = nn.Parameter(torch.zeros(size=(in_features,out_features)))nn.init.xavier_uniform_(self.W) # 初始化全連接權(quán)重self.a = nn.Parameter(torch.zeros(size=(2 * out_features,1)))nn.init.xavier_uniform_(self.a) # 初始化注意力權(quán)重def forward(self,input,adj):h = torch.mm(input,self.W) # 全連接處理N = h.size()[0]# 對全連接后的特征數(shù)據(jù)分別進行基于批次維度和特征維度的復(fù)制,并將復(fù)制結(jié)果連接在一起。# 這種操作使得頂點中的特征數(shù)據(jù)進行了充分的排列組合,結(jié)果中的每行信息都包含兩個頂點特征。接下來的注意力機制便是基于每對頂點特征進行計算的。a_input = torch.cat([h.repeat(1,N).view(N * N ,-1),h.repeat(N,1)],dim=1).view(N,-1,2 * self.out_features) # 主要功能將頂點特征兩兩搭配,連接在一起,生成數(shù)據(jù)形狀[N,N,2 * self.out_features]e = mish(torch.matmul(a_input,self.a).squeeze(2)) # 計算注意力zero_vec = -9e15 * torch.ones_like(e) # 初始化最小值:該值用于填充被過濾掉的特征對象atenion。如果在過濾時,直接對過濾排的特征賦值為0,那么模型會無法收斂。attention = torch.where(adj>0,e,zero_vec) # 過濾注意力 :按照鄰接矩陣中大于0的邊對注意力結(jié)果進行過濾,使注意力按照圖中的頂點配對的范圍進行計算。attention = F.softmax(attention,dim=1) # 對注意力分數(shù)進行歸一化:使用F.Sofmax()函數(shù)對最終的注意力機制進行歸一化,得到注意力分數(shù)(總和為1)。attention = F.dropout(attention,self.dropout,training=self.training)h_prime = torch.matmul(attention,h) # 使用注意力處理特征:將最終的注意力作用到全連接的結(jié)果上以完成計算。return mish(h_prime)# 1.7 搭建圖注意力模型 class GAT(nn.Module):# 圖注意力模型類def __init__(self,nfeat,nclasses,nhid,dropout,nheads): # 圖注意力模型類的初始化方法,支持多套注意力機制同時運算,其參數(shù)nheads用于指定注意力的計算套數(shù)。super(GAT, self).__init__()# 注意力層self.attentions = [GraphAttentionLayer(nfeat,nhid,dropout) for _ in range(nheads)] # 按照指定的注意力套數(shù)生成多套注意力層for i , attention in enumerate(self.attentions): # 將注意力層添加到模型self.add_module('attention_{}'.format(i),attention)# 輸出層self.out_att = GraphAttentionLayer(nhid * nheads,nclasses,dropout)def forward(self,x,adj): # 定義正向傳播方法x = torch.cat([att(x, adj) for att in self.attentions], dim=1)return self.out_att(x, adj)n_labels = labels.max().item() + 1 # 獲取分類個數(shù)7 n_features = features.shape[1] # 獲取節(jié)點特征維度 1433 print(n_labels,n_features) # 輸出7與1433def accuracy(output,y): # 定義函數(shù)計算準(zhǔn)確率return (output.argmax(1) == y).type(torch.float32).mean().item()### 定義函數(shù)來實現(xiàn)模型的訓(xùn)練過程。與深度學(xué)習(xí)任務(wù)不同,圖卷積在訓(xùn)練時需要傳入樣本間的關(guān)系數(shù)據(jù)。 # 因為該關(guān)系數(shù)據(jù)是與節(jié)點數(shù)相等的方陣,所以傳入的樣本數(shù)也要與節(jié)點數(shù)相同,在計算loss值時,可以通過索引從總的運算結(jié)果中取出訓(xùn)練集的結(jié)果。 def step(): # 定義函數(shù)來訓(xùn)練模型 Tip:在圖卷積任務(wù)中,無論是用模型進行預(yù)測還是訓(xùn)練,都需要將全部的圖結(jié)構(gòu)方陣輸入model.train()optimizer.zero_grad()output = model(features,adj) # 將全部數(shù)據(jù)載入模型,只用訓(xùn)練數(shù)據(jù)計算損失loss = F.cross_entropy(output[idx_train],labels[idx_train])acc = accuracy(output[idx_train],labels[idx_train]) # 計算準(zhǔn)確率loss.backward()optimizer.step()return loss.item(),accdef evaluate(idx): # 定義函數(shù)來評估模型 Tip:在圖卷積任務(wù)中,無論是用模型進行預(yù)測還是訓(xùn)練,都需要將全部的圖結(jié)構(gòu)方陣輸入model.eval()output = model(features, adj) # 將全部數(shù)據(jù)載入模型,用指定索引評估模型結(jié)果loss = F.cross_entropy(output[idx], labels[idx]).item()return loss, accuracy(output[idx], labels[idx])# 1.8 使用Ranger優(yōu)化器訓(xùn)練模型并可視化 model = GAT(n_features, n_labels, 16,0.1,8).to(device) # 向GAT傳入的后3個參數(shù)分別代表輸出維度(16)、Dropout的丟棄率(0.1)、注意力的計算套數(shù)(8)from tqdm import tqdm from Cora_ranger import * # 引入Ranger優(yōu)化器 optimizer = Ranger(model.parameters()) # 使用Ranger優(yōu)化器# 訓(xùn)練模型 epochs = 1000 print_steps = 50 train_loss, train_acc = [], [] val_loss, val_acc = [], [] for i in tqdm(range(epochs)):tl,ta = step()train_loss = train_loss + [tl]train_acc = train_acc + [ta]if (i+1) % print_steps == 0 or i == 0:tl,ta = evaluate(idx_train)vl,va = evaluate(idx_val)val_loss = val_loss + [vl]val_acc = val_acc + [va]print(f'{i + 1:6d}/{epochs}: train_loss={tl:.4f}, train_acc={ta:.4f}' + f', val_loss={vl:.4f}, val_acc={va:.4f}')# 輸出最終結(jié)果 final_train, final_val, final_test = evaluate(idx_train), evaluate(idx_val), evaluate(idx_test) print(f'Train : loss={final_train[0]:.4f}, accuracy={final_train[1]:.4f}') print(f'Validation: loss={final_val[0]:.4f}, accuracy={final_val[1]:.4f}') print(f'Test : loss={final_test[0]:.4f}, accuracy={final_test[1]:.4f}')# 可視化訓(xùn)練過程 fig, axes = plt.subplots(1, 2, figsize=(15,5)) ax = axes[0] axes[0].plot(train_loss[::print_steps] + [train_loss[-1]], label='Train') axes[0].plot(val_loss, label='Validation') axes[1].plot(train_acc[::print_steps] + [train_acc[-1]], label='Train') axes[1].plot(val_acc, label='Validation') for ax,t in zip(axes, ['Loss', 'Accuracy']): ax.legend(), ax.set_title(t, size=15)# 輸出模型的預(yù)測結(jié)果 output = model(features, adj) samples = 10 idx_sample = idx_test[torch.randperm(len(idx_test))[:samples]] # 將樣本標(biāo)簽與預(yù)測結(jié)果進行比較 idx2lbl = {v:k for k,v in lbl2idx.items()} df = pd.DataFrame({'Real': [idx2lbl[e] for e in labels[idx_sample].tolist()],'Pred': [idx2lbl[e] for e in output[idx_sample].argmax(1).tolist()]}) print(df)3.2?Cora_ranger.py
#Ranger deep learning optimizer - RAdam + Lookahead combined. #https://github.com/lessw2020/Ranger-Deep-Learning-Optimizer#Ranger has now been used to capture 12 records on the FastAI leaderboard.#This version = 9.3.19 #Credits: #RAdam --> https://github.com/LiyuanLucasLiu/RAdam #Lookahead --> rewritten by lessw2020, but big thanks to Github @LonePatient and @RWightman for ideas from their code. #Lookahead paper --> MZhang,G Hinton https://arxiv.org/abs/1907.08610#summary of changes: #full code integration with all updates at param level instead of group, moves slow weights into state dict (from generic weights), #supports group learning rates (thanks @SHolderbach), fixes sporadic load from saved model issues. #changes 8/31/19 - fix references to *self*.N_sma_threshold; #changed eps to 1e-5 as better default than 1e-8.import math import torch from torch.optim.optimizer import Optimizer, required import itertools as itclass Ranger(Optimizer):def __init__(self, params, lr=1e-3, alpha=0.5, k=6, N_sma_threshhold=5, betas=(.95,0.999), eps=1e-5, weight_decay=0):#parameter checksif not 0.0 <= alpha <= 1.0:raise ValueError(f'Invalid slow update rate: {alpha}')if not 1 <= k:raise ValueError(f'Invalid lookahead steps: {k}')if not lr > 0:raise ValueError(f'Invalid Learning Rate: {lr}')if not eps > 0:raise ValueError(f'Invalid eps: {eps}')#parameter comments:# beta1 (momentum) of .95 seems to work better than .90...#N_sma_threshold of 5 seems better in testing than 4.#In both cases, worth testing on your dataset (.90 vs .95, 4 vs 5) to make sure which works best for you.#prep defaults and init torch.optim basedefaults = dict(lr=lr, alpha=alpha, k=k, step_counter=0, betas=betas, N_sma_threshhold=N_sma_threshhold, eps=eps, weight_decay=weight_decay)super().__init__(params,defaults)#adjustable thresholdself.N_sma_threshhold = N_sma_threshhold#now we can get to work...#removed as we now use step from RAdam...no need for duplicate step counting#for group in self.param_groups:# group["step_counter"] = 0#print("group step counter init")#look ahead paramsself.alpha = alphaself.k = k #radam buffer for stateself.radam_buffer = [[None,None,None] for ind in range(10)]#self.first_run_check=0#lookahead weights#9/2/19 - lookahead param tensors have been moved to state storage. #This should resolve issues with load/save where weights were left in GPU memory from first load, slowing down future runs.#self.slow_weights = [[p.clone().detach() for p in group['params']]# for group in self.param_groups]#don't use grad for lookahead weights#for w in it.chain(*self.slow_weights):# w.requires_grad = Falsedef __setstate__(self, state):print("set state called")super(Ranger, self).__setstate__(state)def step(self, closure=None):loss = None#note - below is commented out b/c I have other work that passes back the loss as a float, and thus not a callable closure. #Uncomment if you need to use the actual closure...#if closure is not None:#loss = closure()#Evaluate averages and grad, update param tensorsfor group in self.param_groups:for p in group['params']:if p.grad is None:continuegrad = p.grad.data.float()if grad.is_sparse:raise RuntimeError('Ranger optimizer does not support sparse gradients')p_data_fp32 = p.data.float()state = self.state[p] #get state dict for this paramif len(state) == 0: #if first time to run...init dictionary with our desired entries#if self.first_run_check==0:#self.first_run_check=1#print("Initializing slow buffer...should not see this at load from saved model!")state['step'] = 0state['exp_avg'] = torch.zeros_like(p_data_fp32)state['exp_avg_sq'] = torch.zeros_like(p_data_fp32)#look ahead weight storage now in state dict state['slow_buffer'] = torch.empty_like(p.data)state['slow_buffer'].copy_(p.data)else:state['exp_avg'] = state['exp_avg'].type_as(p_data_fp32)state['exp_avg_sq'] = state['exp_avg_sq'].type_as(p_data_fp32)#begin computations exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']beta1, beta2 = group['betas']#compute variance mov avgexp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)#compute mean moving avgexp_avg.mul_(beta1).add_(1 - beta1, grad)state['step'] += 1buffered = self.radam_buffer[int(state['step'] % 10)]if state['step'] == buffered[0]:N_sma, step_size = buffered[1], buffered[2]else:buffered[0] = state['step']beta2_t = beta2 ** state['step']N_sma_max = 2 / (1 - beta2) - 1N_sma = N_sma_max - 2 * state['step'] * beta2_t / (1 - beta2_t)buffered[1] = N_smaif N_sma > self.N_sma_threshhold:step_size = math.sqrt((1 - beta2_t) * (N_sma - 4) / (N_sma_max - 4) * (N_sma - 2) / N_sma * N_sma_max / (N_sma_max - 2)) / (1 - beta1 ** state['step'])else:step_size = 1.0 / (1 - beta1 ** state['step'])buffered[2] = step_sizeif group['weight_decay'] != 0:p_data_fp32.add_(-group['weight_decay'] * group['lr'], p_data_fp32)if N_sma > self.N_sma_threshhold:denom = exp_avg_sq.sqrt().add_(group['eps'])p_data_fp32.addcdiv_(-step_size * group['lr'], exp_avg, denom)else:p_data_fp32.add_(-step_size * group['lr'], exp_avg)p.data.copy_(p_data_fp32)#integrated look ahead...#we do it at the param level instead of group levelif state['step'] % group['k'] == 0:slow_p = state['slow_buffer'] #get access to slow param tensorslow_p.add_(self.alpha, p.data - slow_p) #(fast weights - slow weights) * alphap.data.copy_(slow_p) #copy interpolated weights to RAdam param tensorreturn loss總結(jié)
以上是生活随笔為你收集整理的【Pytorch神经网络实战案例】22 基于Cora数据集实现图注意力神经网络GAT的论文分类的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Pytorch神经网络基础理论篇】 0
- 下一篇: 【Pytorch神经网络基础理论篇】 0