日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人工智能 > 卷积神经网络 >内容正文

卷积神经网络

【Pytorch神经网络实战案例】20 基于Cora数据集实现图卷积神经网络论文分类

發布時間:2024/7/5 卷积神经网络 82 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Pytorch神经网络实战案例】20 基于Cora数据集实现图卷积神经网络论文分类 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1 案例說明(圖卷積神經網絡)

CORA數據集里面含有每一篇論文的關鍵詞以及分類信息,同時還有論文間互相引用的信息。搭建AI模型,對數據集中的論文信息進行分析,根據已有論文的分類特征,從而預測出未知分類的論文類別。

1.1 使用圖卷積神經網絡的特點

使用圖神經網絡來實現分類。與深度學習模型的不同之處在于,圖神經網通會利用途文本身特征和論文間的關系特征進行處理,僅需要少量樣本即可達到很好的效果。

cora數據集2022年-深度學習文檔類資源-CSDN下載CORA數據集是由機器學習的論文整理而來的,記錄每篇論文用到的關鍵詞,以及論文之間互相引用的關系。C更多下載資源、學習資料請訪問CSDN下載頻道.https://download.csdn.net/download/qq_39237205/85059035

1.2 CORA數據集

CORA數據集是由機器學習的論文整理而來的,記錄每篇論文用到的關鍵詞,以及論文之間互相引用的關系。

1.2.1 CORA的內容

CORA數據集中的論文共分為7類:基于案例、遺傳算法、神經網絡、概率方法、強化學習、規則學習、理論。

1.2.2 CORA的組成

數據集中共有2708篇論文,每一篇論文都引用或至少被一篇其他論文所引用。整個語料庫共有2708篇論文。同時,又將所有論文中的詞干、停止詞、低頻詞刪除,留下1433個關鍵詞,作為論文的個體特征。

1.2.3 CORA數據集的文件與結構說明

(1)content文件格式的論文說明:

<paper-id><word-attributes><class-label>

每行的第一個條目包含論文的唯一字符串ID,隨后用一個二進制值指示詞匯表中的每個單詞在紙張中存在(由1表示)或不存在(由0表示)。行中的最后一項包含紙張的類標簽。

(2)cites文件包含了語料庫的引文圖,每一行用以下格式描述一個鏈接:

?<id ofreferencepaper><id ofreference paper>

每行包含兩個紙張ID。第一個條目是被引用論文的ID,第二個ID代表包含引用的論文。鏈接的方向是從右向左的。如果一行用“paper2 paper1”表示,那么其中連接為“paper2->paper1”

2 代碼編寫

2.1 代碼實戰:引入基礎模塊,設置運行環境----Cora_GNN.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_GNN.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_GNN.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 加工圖結構的矩陣數據

對圖結構的矩陣數據進行加工,使其更好地表現出圖結構特征,并參與神經網絡的模型計算。

2.4.1?加工圖結構的矩陣數據的步驟

1、對每個節點的特征數據進行歸一化處理。
2、為鄰接矩陣的對角線補1:因為在分類任務中,鄰接矩陣主要作用是通過論文間的關聯來幫助節點分類。對于對角線上的節點,表示的意義是自己與自己的關聯。將對角線節點設為1(自環圖)、表明節點也會幫助到分類任務。
3、對補1后的鄰接矩陣進行歸一化處理。

2.4.2 代碼實現:加工圖結構的矩陣數據----Cora_GNN.py(第4部分)

# 1.4 加工圖結構的矩陣數據 def normalize(mx): # 定義函數,對矩陣的數據進行歸一化處理rowsum = np.array(mx.sum(1)) # 計算每一篇論文的字數==>02 對A中的邊數求和,計算出矩陣A的度矩陣D^的特征向量r_inv = (rowsum ** -1).flatten() # 取總字數的倒數==>03 對矩陣A的度矩陣D^的特征向量求逆,并得到D^逆的特征向量r_inv[np.isinf(r_inv)] = 0.0 # 將NaN值取為0r_mat_inv = diags(r_inv) # 將總字數的倒數變為對角矩陣===》對圖結構的度矩陣求逆==>04 D^逆的特征向量轉化為對角矩陣,得到D^逆mx = r_mat_inv.dot(mx) # 左乘一個矩陣,相當于每個元素除以總數===》對每個論文頂點的邊進行歸一化處理==>05 計算D^逆與A加入自環(對角線為1)的鄰接矩陣所得A^的點積,得到拉普拉斯矩陣。return mx # 對features矩陣進行歸一化處理(每行總和為1) features = normalize(features) #在函數normalize()中,分為兩步對鄰接矩陣進行處理。1、將每篇論文總字數的倒數變成對角矩陣。該操作相當于對圖結構的度矩陣求逆。2、用度矩陣的逆左乘鄰接矩陣,相當于對圖中每個論文頂點的邊進行歸一化處理。 # 對鄰接矩陣的對角線添1,將其變為自循環圖,同時對其進行歸一化處理 adj = normalize(adj + eye(adj.shape[0])) # 對角線補1==>01實現加入自環的鄰接矩陣A

2.5 將數據轉化為張量,并分配運算資源

將加工好的圖結構矩陣數據轉為PyTorch支持的張量類型,并將其分成3份,分別用來進行訓練、測試和驗證。

2.5.1?代碼實現:將數據轉化為張量,并分配運算資源----Cora_GNN.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 圖卷積

圖卷積的本質是維度變換,即將每個含有in維的節點特征數據變換成含有out維的節點特征數據。

圖卷積的操作將輸入的節點特征、權重參數、加工后的鄰接矩陣三者放在一起執行點積運算。

權重參數是個in×out大小的矩陣,其中in代表輸入節點的特征維度、out代表最終要輸出的特征維度。將權重參數在維度變換中的功能當作一個全連接網絡的權重來理解,只不過在圖卷積中,它會比全連接網絡多了執行節點關系信息的點積運算。

?如上圖所示,列出全連接網絡和圖卷積網絡在忽略偏置后的關系。從中可以很清晰地看出,圖卷積網絡其實就是在全連接網絡基礎之上增加了節點關系信息。

2.6.1 代碼實現:定義Mish激活函數與圖卷積操作類----Cora_GNN.py(第6部分)

在上圖的所示的算法基礎增加偏置,定義GraphConvolution類

# 1.6 定義Mish激活函數與圖卷積操作類 def mish(x): # 性能優于RElu函數return x * (torch.tanh(F.softplus(x))) # 圖卷積類 class GraphConvolution(nn.Module):def __init__(self,f_in,f_out,use_bias = True,activation=mish):# super(GraphConvolution, self).__init__()super().__init__()self.f_in = f_inself.f_out = f_outself.use_bias = use_biasself.activation = activationself.weight = nn.Parameter(torch.FloatTensor(f_in, f_out))self.bias = nn.Parameter(torch.FloatTensor(f_out)) if use_bias else Noneself.initialize_weights()def initialize_weights(self):# 對參數進行初始化if self.activation is None: # 初始化權重nn.init.xavier_uniform_(self.weight)else:nn.init.kaiming_uniform_(self.weight, nonlinearity='leaky_relu')if self.use_bias:nn.init.zeros_(self.bias)def forward(self,input,adj): # 實現模型的正向處理流程support = torch.mm(input,self.weight) # 節點特征與權重點積:torch.mm()實現矩陣的相乘,僅支持二位矩陣。若是多維矩則使用torch.matmul()output = torch.mm(adj,support) # 將加工后的鄰接矩陣放入點積運算if self.use_bias:output.add_(self.bias) # 加入偏置if self.activation is not None:output = self.activation(output) # 激活函數處理return output

2.7 搭建多層圖卷積

定義GCN類將GraphConvolution類完成的圖卷積層疊加起來,形成多層圖卷積網絡。同時,為該網絡模型實現訓練和評估函數。

2.7.1 代碼實現:多層圖卷積----Cora_GNN.py(第7部分)

# 1.7 搭建多層圖卷積網絡模型 class GCN(nn.Module):def __init__(self, f_in, n_classes, hidden=[16], dropout_p=0.5): # 實現多層圖卷積網絡,該網的搭建方法與全連接網絡的搭建一致,只是將全連接層轉化成GraphConvolution所實現的圖卷積層# super(GCN, self).__init__()super().__init__()layers = []# 根據參數構建多層網絡for f_in, f_out in zip([f_in] + hidden[:-1], hidden):# python 在list上的“+=”的重載函數是extend()函數,而不是+# layers = [GraphConvolution(f_in, f_out)] + layerslayers += [GraphConvolution(f_in, f_out)]self.layers = nn.Sequential(*layers)self.dropout_p = dropout_p# 構建輸出層self.out_layer = GraphConvolution(f_out, n_classes, activation=None)def forward(self, x, adj): # 實現前向處理過程for layer in self.layers:x = layer(x,adj)# 函數方式調用dropout():必須指定模型的運行狀態,即Training標志,這樣可減少很多麻煩F.dropout(x,self.dropout_p,training=self.training,inplace=True)return self.out_layer(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_GNN.py(第8部分)

# 1.8 使用Ranger優化器訓練模型并可視化 model = GCN(n_features, n_labels, hidden=[16, 32, 16]).to(device)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.3 驗證結果

2.8 結論

從訓練結果中可以看出,該模型具有很好的擬合能力。值得一提的是,圖卷積模型所使用的訓練樣本非常少,只使用了2708個樣本中的200個進行訓練。因為加入了樣本間的關系信息,所以模型對樣本量的依賴大幅下降。這也正是圖神經網絡模型的優勢。

3 代碼匯總

3.1 Cora_GNN.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(mx): # 定義函數,對矩陣的數據進行歸一化處理rowsum = np.array(mx.sum(1)) # 計算每一篇論文的字數==>02 對A中的邊數求和,計算出矩陣A的度矩陣D^的特征向量r_inv = (rowsum ** -1).flatten() # 取總字數的倒數==>03 對矩陣A的度矩陣D^的特征向量求逆,并得到D^逆的特征向量r_inv[np.isinf(r_inv)] = 0.0 # 將NaN值取為0r_mat_inv = diags(r_inv) # 將總字數的倒數變為對角矩陣===》對圖結構的度矩陣求逆==>04 D^逆的特征向量轉化為對角矩陣,得到D^逆mx = r_mat_inv.dot(mx) # 左乘一個矩陣,相當于每個元素除以總數===》對每個論文頂點的邊進行歸一化處理==>05 計算D^逆與A加入自環(對角線為1)的鄰接矩陣所得A^的點積,得到拉普拉斯矩陣。return mx # 對features矩陣進行歸一化處理(每行總和為1) features = normalize(features) #在函數normalize()中,分為兩步對鄰接矩陣進行處理。1、將每篇論文總字數的倒數變成對角矩陣。該操作相當于對圖結構的度矩陣求逆。2、用度矩陣的逆左乘鄰接矩陣,相當于對圖中每個論文頂點的邊進行歸一化處理。 # 對鄰接矩陣的對角線添1,將其變為自循環圖,同時對其進行歸一化處理 adj = normalize(adj + eye(adj.shape[0])) # 對角線補1==>01實現加入自環的鄰接矩陣A# 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 GraphConvolution(nn.Module):def __init__(self,f_in,f_out,use_bias = True,activation=mish):# super(GraphConvolution, self).__init__()super().__init__()self.f_in = f_inself.f_out = f_outself.use_bias = use_biasself.activation = activationself.weight = nn.Parameter(torch.FloatTensor(f_in, f_out))self.bias = nn.Parameter(torch.FloatTensor(f_out)) if use_bias else Noneself.initialize_weights()def initialize_weights(self):# 對參數進行初始化if self.activation is None: # 初始化權重nn.init.xavier_uniform_(self.weight)else:nn.init.kaiming_uniform_(self.weight, nonlinearity='leaky_relu')if self.use_bias:nn.init.zeros_(self.bias)def forward(self,input,adj): # 實現模型的正向處理流程support = torch.mm(input,self.weight) # 節點特征與權重點積:torch.mm()實現矩陣的相乘,僅支持二位矩陣。若是多維矩則使用torch.matmul()output = torch.mm(adj,support) # 將加工后的鄰接矩陣放入點積運算if self.use_bias:output.add_(self.bias) # 加入偏置if self.activation is not None:output = self.activation(output) # 激活函數處理return output# 1.7 搭建多層圖卷積網絡模型 class GCN(nn.Module):def __init__(self, f_in, n_classes, hidden=[16], dropout_p=0.5): # 實現多層圖卷積網絡,該網的搭建方法與全連接網絡的搭建一致,只是將全連接層轉化成GraphConvolution所實現的圖卷積層# super(GCN, self).__init__()super().__init__()layers = []# 根據參數構建多層網絡for f_in, f_out in zip([f_in] + hidden[:-1], hidden):# python 在list上的“+=”的重載函數是extend()函數,而不是+# layers = [GraphConvolution(f_in, f_out)] + layerslayers += [GraphConvolution(f_in, f_out)]self.layers = nn.Sequential(*layers)self.dropout_p = dropout_p# 構建輸出層self.out_layer = GraphConvolution(f_out, n_classes, activation=None)def forward(self, x, adj): # 實現前向處理過程for layer in self.layers:x = layer(x,adj)# 函數方式調用dropout():必須指定模型的運行狀態,即Training標志,這樣可減少很多麻煩F.dropout(x,self.dropout_p,training=self.training,inplace=True)return self.out_layer(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 = GCN(n_features, n_labels, hidden=[16, 32, 16]).to(device)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神经网络实战案例】20 基于Cora数据集实现图卷积神经网络论文分类的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。