【Pytorch神经网络实战案例】22 基于Cora数据集实现图注意力神经网络GAT的论文分类
注意力機制的特點是,它的輸入向量長度可變,通過將注意力集中在最相關的部分來做出決定。注意力機制結合RNN或者CNN的方法。
1 實戰描述
【主要目的:將注意力機制用在圖神經網絡中,完成圖注意力神經網絡的結構和搭建】
1.1 實現目的
有一個記錄論文信息的數據集,數據集里面含有每一篇論文的關鍵詞以及分類信息,同時還有論文間互相引用的信息。搭建AI模型,對數據集中的論文信息進行分析,使模型學習已有論文的分類特征,以便預測出未知分類的論文類別。
1.2 圖注意力網絡圖
圖注意力網絡(GraphAttention Network,GAT)在GCN的基礎上添加了一個隱藏的自注意力(self-attention)層。通過疊加Self-attention層,在卷積過程中可將不同的權重分配給鄰域內的不同頂點,同時處理不同大小的鄰域。
在實際計算時,自注意力機制可以使用多套權重同時進行計算,并且彼此之間不共享權重,能夠使頂點確定知識的相關性,是否可忽略。
?2 代碼編寫
本次要構建的圖網絡
2.1 代碼實戰:引入基礎模塊,設置運行環境----Cora_GAT.py(第1部分)
from pathlib import Path # 引入提升路徑的兼容性 # 引入矩陣運算的相關庫 import numpy as np import pandas as pd from scipy.sparse import coo_matrix,csr_matrix,diags,eye # 引入深度學習框架庫 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 導入基礎模塊,并設置運行環境 # 輸出計算資源情況 device = torch.device('cuda')if torch.cuda.is_available() else torch.device('cpu') print(device) # 輸出 cuda# 輸出樣本路徑 path = Path('./data/cora') print(path) # 輸出 cuda輸出結果:
2.2 代碼實現:讀取并解析論文數據----Cora_GAT.py(第2部分)
# 1.2 讀取并解析論文數據 # 讀取論文內容數據,將其轉化為數據 paper_features_label = np.genfromtxt(path/'cora.content',dtype=np.str_) # 使用Path對象的路徑構造,實例化的內容為cora.content。path/'cora.content'表示路徑為'data/cora/cora.content'的字符串 print(paper_features_label,np.shape(paper_features_label)) # 打印數據集內容與數據的形狀# 取出數據集中的第一列:論文ID papers = paper_features_label[:,0].astype(np.int32) print("論文ID序列:",papers) # 輸出所有論文ID # 論文重新編號,并將其映射到論文ID中,實現論文的統一管理 paper2idx = {k:v for v,k in enumerate(papers)}# 將數據中間部分的字標簽取出,轉化成矩陣 features = csr_matrix(paper_features_label[:,1:-1],dtype=np.float32) print("字標簽矩陣的形狀:",np.shape(features)) # 字標簽矩陣的形狀# 將數據的最后一項的文章分類屬性取出,轉化為分類的索引 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 讀取并解析論文關系數據
載入論文的關系數據,將數據中用論文ID表示的關系轉化成重新編號后的關系,將每篇論文當作一個頂點,論文間的引用關系作為邊,這樣論文的關系數據就可以用一個圖結構來表示。
?計算該圖結構的鄰接矩陣并將其轉化為無向圖鄰接矩陣。
2.3.1 代碼實現:轉化矩陣----Cora_GAT.py(第3部分)
# 1.3 讀取并解析論文關系數據 # 讀取論文關系數據,并將其轉化為數據 edges = np.genfromtxt(path/'cora.cites',dtype=np.int32) # 將數據集中論文的引用關系以數據的形式讀入 print(edges,np.shape(edges)) # 轉化為新編號節點間的關系:將數據集中論文ID表示的關系轉化為重新編號后的關系 edges = np.asarray([paper2idx[e] for e in edges.flatten()],np.int32).reshape(edges.shape) print("新編號節點間的對應關系:",edges,edges.shape) # 計算鄰接矩陣,行與列都是論文個數:由論文引用關系所表示的圖結構生成鄰接矩陣。 adj = coo_matrix((np.ones(edges.shape[0]), (edges[:, 0], edges[:, 1])),shape=(len(labels), len(labels)), dtype=np.float32) # 生成無向圖對稱矩陣:將有向圖的鄰接矩陣轉化為無向圖的鄰接矩陣。Tip:轉化為無向圖的原因:主要用于對論文的分類,論文的引用關系主要提供單個特征之間的關聯,故更看重是不是有關系,所以無向圖即可。 adj_long = adj.multiply(adj.T < adj) adj = adj_long + adj_long.T輸出:
2.4 代碼實現:加工圖結構的矩陣數據----Cora_GAT.py(第4部分)
# 1.4 加工圖結構的矩陣數據 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) # 兌成歸一化拉普拉斯矩陣實現鄰接矩陣的轉化adj = normalize_adj(adj + eye(adj.shape[0])) # 對鄰接矩陣進行轉化對稱歸一化拉普拉斯矩陣轉化2.5 將數據轉化為張量,并分配運算資源
將加工好的圖結構矩陣數據轉為PyTorch支持的張量類型,并將其分成3份,分別用來進行訓練、測試和驗證。
2.5.1?代碼實現:將數據轉化為張量,并分配運算資源----Cora_GAT.py(第5部分)
# 1.5 將數據轉化為張量,并分配運算資源 adj = torch.FloatTensor(adj.todense()) # 節點間關系 todense()方法將其轉換回稠密矩陣。 features = torch.FloatTensor(features.todense()) # 節點自身的特征 labels = torch.LongTensor(labels) # 對每個節點的分類標簽# 劃分數據集 n_train = 200 # 訓練數據集大小 n_val = 300 # 驗證數據集大小 n_test = len(features) - n_train - n_val # 測試數據集大小 np.random.seed(34) idxs = np.random.permutation(len(features)) # 將原有的索引打亂順序# 計算每個數據集的索引 idx_train = torch.LongTensor(idxs[:n_train]) # 根據指定訓練數據集的大小并劃分出其對應的訓練數據集索引 idx_val = torch.LongTensor(idxs[n_train:n_train+n_val])# 根據指定驗證數據集的大小并劃分出其對應的驗證數據集索引 idx_test = torch.LongTensor(idxs[n_train+n_val:])# 根據指定測試數據集的大小并劃分出其對應的測試數據集索引# 分配運算資源 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 代碼實現:定義Mish激活函數與圖注意力層類----Cora_GAT.py(第6部分)
# 1.6 定義Mish激活函數與圖注意力層類 def mish(x): # 性能優于RElu函數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) # 初始化全連接權重self.a = nn.Parameter(torch.zeros(size=(2 * out_features,1)))nn.init.xavier_uniform_(self.a) # 初始化注意力權重def forward(self,input,adj):h = torch.mm(input,self.W) # 全連接處理N = h.size()[0]# 對全連接后的特征數據分別進行基于批次維度和特征維度的復制,并將復制結果連接在一起。# 這種操作使得頂點中的特征數據進行了充分的排列組合,結果中的每行信息都包含兩個頂點特征。接下來的注意力機制便是基于每對頂點特征進行計算的。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) # 主要功能將頂點特征兩兩搭配,連接在一起,生成數據形狀[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的邊對注意力結果進行過濾,使注意力按照圖中的頂點配對的范圍進行計算。attention = F.softmax(attention,dim=1) # 對注意力分數進行歸一化:使用F.Sofmax()函數對最終的注意力機制進行歸一化,得到注意力分數(總和為1)。attention = F.dropout(attention,self.dropout,training=self.training)h_prime = torch.matmul(attention,h) # 使用注意力處理特征:將最終的注意力作用到全連接的結果上以完成計算。return mish(h_prime)2.7 代碼實現:搭建圖注意力模型----Cora_GAT.py(第7部分)
# 1.7 搭建圖注意力模型 class GAT(nn.Module):# 圖注意力模型類def __init__(self,nfeat,nclasses,nhid,dropout,nheads): # 圖注意力模型類的初始化方法,支持多套注意力機制同時運算,其參數nheads用于指定注意力的計算套數。super(GAT, self).__init__()# 注意力層self.attentions = [GraphAttentionLayer(nfeat,nhid,dropout) for _ in range(nheads)] # 按照指定的注意力套數生成多套注意力層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 # 獲取分類個數7 n_features = features.shape[1] # 獲取節點特征維度 1433 print(n_labels,n_features) # 輸出7與1433def accuracy(output,y): # 定義函數計算準確率return (output.argmax(1) == y).type(torch.float32).mean().item()### 定義函數來實現模型的訓練過程。與深度學習任務不同,圖卷積在訓練時需要傳入樣本間的關系數據。 # 因為該關系數據是與節點數相等的方陣,所以傳入的樣本數也要與節點數相同,在計算loss值時,可以通過索引從總的運算結果中取出訓練集的結果。 def step(): # 定義函數來訓練模型 Tip:在圖卷積任務中,無論是用模型進行預測還是訓練,都需要將全部的圖結構方陣輸入model.train()optimizer.zero_grad()output = model(features,adj) # 將全部數據載入模型,只用訓練數據計算損失loss = F.cross_entropy(output[idx_train],labels[idx_train])acc = accuracy(output[idx_train],labels[idx_train]) # 計算準確率loss.backward()optimizer.step()return loss.item(),accdef evaluate(idx): # 定義函數來評估模型 Tip:在圖卷積任務中,無論是用模型進行預測還是訓練,都需要將全部的圖結構方陣輸入model.eval()output = model(features, adj) # 將全部數據載入模型,用指定索引評估模型結果loss = F.cross_entropy(output[idx], labels[idx]).item()return loss, accuracy(output[idx], labels[idx])2.8?Ranger優化器
圖卷積神經網絡的層數不宜過多,一般在3層左右即可。本例將實現一個3層的圖卷積神經網絡,每層的維度變化如圖9-15所示。
使用循環語句訓練模型,并將模型結果可視化。
2.8.1 代碼實現:用Ranger優化器訓練模型并可視化結果----Cora_GAT.py(第8部分)
# 1.8 使用Ranger優化器訓練模型并可視化 model = GAT(n_features, n_labels, 16,0.1,8).to(device) # 向GAT傳入的后3個參數分別代表輸出維度(16)、Dropout的丟棄率(0.1)、注意力的計算套數(8)from tqdm import tqdm from Cora_ranger import * # 引入Ranger優化器 optimizer = Ranger(model.parameters()) # 使用Ranger優化器# 訓練模型 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}')# 輸出最終結果 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}')# 可視化訓練過程 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)# 輸出模型的預測結果 output = model(features, adj) samples = 10 idx_sample = idx_test[torch.randperm(len(idx_test))[:samples]] # 將樣本標簽與預測結果進行比較 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 訓練過程?
2.7.2 訓練結果
3 代碼匯總
3.1 Cora_GAT.py
from pathlib import Path # 引入提升路徑的兼容性 # 引入矩陣運算的相關庫 import numpy as np import pandas as pd from scipy.sparse import coo_matrix,csr_matrix,diags,eye # 引入深度學習框架庫 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 導入基礎模塊,并設置運行環境 # 輸出計算資源情況 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 讀取并解析論文數據 # 讀取論文內容數據,將其轉化為數據 paper_features_label = np.genfromtxt(path/'cora.content',dtype=np.str_) # 使用Path對象的路徑構造,實例化的內容為cora.content。path/'cora.content'表示路徑為'data/cora/cora.content'的字符串 print(paper_features_label,np.shape(paper_features_label)) # 打印數據集內容與數據的形狀# 取出數據集中的第一列:論文ID papers = paper_features_label[:,0].astype(np.int32) print("論文ID序列:",papers) # 輸出所有論文ID # 論文重新編號,并將其映射到論文ID中,實現論文的統一管理 paper2idx = {k:v for v,k in enumerate(papers)}# 將數據中間部分的字標簽取出,轉化成矩陣 features = csr_matrix(paper_features_label[:,1:-1],dtype=np.float32) print("字標簽矩陣的形狀:",np.shape(features)) # 字標簽矩陣的形狀# 將數據的最后一項的文章分類屬性取出,轉化為分類的索引 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 讀取并解析論文關系數據 # 讀取論文關系數據,并將其轉化為數據 edges = np.genfromtxt(path/'cora.cites',dtype=np.int32) # 將數據集中論文的引用關系以數據的形式讀入 print(edges,np.shape(edges)) # 轉化為新編號節點間的關系:將數據集中論文ID表示的關系轉化為重新編號后的關系 edges = np.asarray([paper2idx[e] for e in edges.flatten()],np.int32).reshape(edges.shape) print("新編號節點間的對應關系:",edges,edges.shape) # 計算鄰接矩陣,行與列都是論文個數:由論文引用關系所表示的圖結構生成鄰接矩陣。 adj = coo_matrix((np.ones(edges.shape[0]), (edges[:, 0], edges[:, 1])),shape=(len(labels), len(labels)), dtype=np.float32) # 生成無向圖對稱矩陣:將有向圖的鄰接矩陣轉化為無向圖的鄰接矩陣。Tip:轉化為無向圖的原因:主要用于對論文的分類,論文的引用關系主要提供單個特征之間的關聯,故更看重是不是有關系,所以無向圖即可。 adj_long = adj.multiply(adj.T < adj) adj = adj_long + adj_long.T# 1.4 加工圖結構的矩陣數據 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) # 兌成歸一化拉普拉斯矩陣實現鄰接矩陣的轉化adj = normalize_adj(adj + eye(adj.shape[0])) # 對鄰接矩陣進行轉化對稱歸一化拉普拉斯矩陣轉化# 1.5 將數據轉化為張量,并分配運算資源 adj = torch.FloatTensor(adj.todense()) # 節點間關系 todense()方法將其轉換回稠密矩陣。 features = torch.FloatTensor(features.todense()) # 節點自身的特征 labels = torch.LongTensor(labels) # 對每個節點的分類標簽# 劃分數據集 n_train = 200 # 訓練數據集大小 n_val = 300 # 驗證數據集大小 n_test = len(features) - n_train - n_val # 測試數據集大小 np.random.seed(34) idxs = np.random.permutation(len(features)) # 將原有的索引打亂順序# 計算每個數據集的索引 idx_train = torch.LongTensor(idxs[:n_train]) # 根據指定訓練數據集的大小并劃分出其對應的訓練數據集索引 idx_val = torch.LongTensor(idxs[n_train:n_train+n_val])# 根據指定驗證數據集的大小并劃分出其對應的驗證數據集索引 idx_test = torch.LongTensor(idxs[n_train+n_val:])# 根據指定測試數據集的大小并劃分出其對應的測試數據集索引# 分配運算資源 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激活函數與圖注意力層類 def mish(x): # 性能優于RElu函數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) # 初始化全連接權重self.a = nn.Parameter(torch.zeros(size=(2 * out_features,1)))nn.init.xavier_uniform_(self.a) # 初始化注意力權重def forward(self,input,adj):h = torch.mm(input,self.W) # 全連接處理N = h.size()[0]# 對全連接后的特征數據分別進行基于批次維度和特征維度的復制,并將復制結果連接在一起。# 這種操作使得頂點中的特征數據進行了充分的排列組合,結果中的每行信息都包含兩個頂點特征。接下來的注意力機制便是基于每對頂點特征進行計算的。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) # 主要功能將頂點特征兩兩搭配,連接在一起,生成數據形狀[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的邊對注意力結果進行過濾,使注意力按照圖中的頂點配對的范圍進行計算。attention = F.softmax(attention,dim=1) # 對注意力分數進行歸一化:使用F.Sofmax()函數對最終的注意力機制進行歸一化,得到注意力分數(總和為1)。attention = F.dropout(attention,self.dropout,training=self.training)h_prime = torch.matmul(attention,h) # 使用注意力處理特征:將最終的注意力作用到全連接的結果上以完成計算。return mish(h_prime)# 1.7 搭建圖注意力模型 class GAT(nn.Module):# 圖注意力模型類def __init__(self,nfeat,nclasses,nhid,dropout,nheads): # 圖注意力模型類的初始化方法,支持多套注意力機制同時運算,其參數nheads用于指定注意力的計算套數。super(GAT, self).__init__()# 注意力層self.attentions = [GraphAttentionLayer(nfeat,nhid,dropout) for _ in range(nheads)] # 按照指定的注意力套數生成多套注意力層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 # 獲取分類個數7 n_features = features.shape[1] # 獲取節點特征維度 1433 print(n_labels,n_features) # 輸出7與1433def accuracy(output,y): # 定義函數計算準確率return (output.argmax(1) == y).type(torch.float32).mean().item()### 定義函數來實現模型的訓練過程。與深度學習任務不同,圖卷積在訓練時需要傳入樣本間的關系數據。 # 因為該關系數據是與節點數相等的方陣,所以傳入的樣本數也要與節點數相同,在計算loss值時,可以通過索引從總的運算結果中取出訓練集的結果。 def step(): # 定義函數來訓練模型 Tip:在圖卷積任務中,無論是用模型進行預測還是訓練,都需要將全部的圖結構方陣輸入model.train()optimizer.zero_grad()output = model(features,adj) # 將全部數據載入模型,只用訓練數據計算損失loss = F.cross_entropy(output[idx_train],labels[idx_train])acc = accuracy(output[idx_train],labels[idx_train]) # 計算準確率loss.backward()optimizer.step()return loss.item(),accdef evaluate(idx): # 定義函數來評估模型 Tip:在圖卷積任務中,無論是用模型進行預測還是訓練,都需要將全部的圖結構方陣輸入model.eval()output = model(features, adj) # 將全部數據載入模型,用指定索引評估模型結果loss = F.cross_entropy(output[idx], labels[idx]).item()return loss, accuracy(output[idx], labels[idx])# 1.8 使用Ranger優化器訓練模型并可視化 model = GAT(n_features, n_labels, 16,0.1,8).to(device) # 向GAT傳入的后3個參數分別代表輸出維度(16)、Dropout的丟棄率(0.1)、注意力的計算套數(8)from tqdm import tqdm from Cora_ranger import * # 引入Ranger優化器 optimizer = Ranger(model.parameters()) # 使用Ranger優化器# 訓練模型 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}')# 輸出最終結果 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}')# 可視化訓練過程 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)# 輸出模型的預測結果 output = model(features, adj) samples = 10 idx_sample = idx_test[torch.randperm(len(idx_test))[:samples]] # 將樣本標簽與預測結果進行比較 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總結
以上是生活随笔為你收集整理的【Pytorch神经网络实战案例】22 基于Cora数据集实现图注意力神经网络GAT的论文分类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Pytorch神经网络基础理论篇】 0
- 下一篇: 【Pytorch神经网络基础理论篇】 0