Python轉(zhuǎn)為C語言并編譯生成二進制文件的教程詳解
本教程以DGL版本的GCN為例,其他也相似。
1、安裝cython、gcc:
sudo apt install cython gcc -y
2、安裝DGL、PyTorch:
pip3 install torch torchvision torchaudio pip install dgl -f https://data.dgl.ai/wheels/cu117/repo.html pip install dglgo -f https://data.dgl.ai/wheels-test/repo.html
3、編寫gcn.py。注意添加# cython: language_level=3,不然默認用的是python2:
# cython: language_level=3 import torch import torch.nn as nn import torch.nn.functional as F import dgl from dgl.data import CoraGraphDataset from dgl.nn import GraphConv # 定義 GCN 模型 class GCN(nn.Module): def __init__(self, in_feats, h_feats, num_classes): super(GCN, self).__init__() self.conv1 = GraphConv(in_feats, h_feats) self.conv2 = GraphConv(h_feats, num_classes) def forward(self, g, in_feat): h = self.conv1(g, in_feat) h = F.relu(h) h = self.conv2(g, h) return h if __name__ == "__main__": # 加載數(shù)據(jù)集 dataset = CoraGraphDataset() g = dataset[0] # 創(chuàng)建模型實例 model = GCN(g.ndata['feat'].shape[1], 16, dataset.num_classes) # 定義損失函數(shù)和優(yōu)化器 optimizer = torch.optim.Adam(model.parameters(), lr=0.01) criterion = nn.CrossEntropyLoss() # 訓練模型 for epoch in range(200): logits = model(g, g.ndata['feat']) loss = criterion(logits[g.ndata['train_mask']], g.ndata['label'][g.ndata['train_mask']]) optimizer.zero_grad() loss.backward() optimizer.step() if epoch % 10 == 0: print(f'Epoch {epoch}, Loss: {loss.item()}') # 測試模型 model.eval() with torch.no_grad(): logits = model(g, g.ndata['feat']) _, predicted = torch.max(logits[g.ndata['test_mask']], 1) correct = (predicted == g.ndata['label'][g.ndata['test_mask']]).sum().item() acc = correct / len(predicted) print(f'Accuracy: {acc:.4f}')
4、使用cython將Python轉(zhuǎn)為C語言,此時會生成一個gcn.c文件。注意要加--embed:
cython gcn.py --embed
5、然后使用 C 編譯器來編譯gcn.c文件,此時會生成一個gcn.o文件:
gcc -c gcn.c `python3-config --includes` `python3-config --ldflags` -o gcn.o
6、鏈接生成可執(zhí)行文件,此時會生成一個gcn可執(zhí)行文件。注意這里-L后面改成你的路徑:
gcc gcn.o -L/home/sxf/anaconda3/envs/dgl/lib -lpython3.9 -o gcn
7、運行二進制可執(zhí)行文件:
./gcn
8、如果報錯:error while loading shared libraries: libpython3.9.so.1.0: cannot open shared object file: No such file or directory。就把這個so文件的路徑包含進來,再重新執(zhí)行步驟7。注意這里后面改成你的路徑:
export LD_LIBRARY_PATH=/home/sxf/anaconda3/envs/dgl/lib/:$LD_LIBRARY_PATH
9、最終效果:
注意:如果你有多個自定義的py文件要import進來,那么自定義的幾個py文件需要轉(zhuǎn)為so庫文件,來被主文件調(diào)用。而如果只有一個py文件,就沒有這個問題了。
到此這篇關(guān)于Python轉(zhuǎn)為C語言并編譯生成二進制文件的教程詳解的文章就介紹到這了,更多相關(guān)Python轉(zhuǎn)C語言內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一文向您詳細介紹指令 python -m pip install的用法和功能
通過本文的介紹,我們詳細了解了python -m pip install命令的用法和功能,從基本用法到安裝特定版本的包、從其他源安裝包、升級和卸載包,再到使用requirements.txt管理依賴,我們逐步深入了解了pip的強大功能,感興趣的朋友跟隨小編一起看看吧2024-07-07django 文件上傳功能的相關(guān)實例代碼(簡單易懂)
這篇文章主要介紹了django 文件上傳功能的相關(guān)實例代碼,代碼簡單易懂,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2020-01-01Python多維/嵌套字典數(shù)據(jù)無限遍歷的實現(xiàn)
下面小編就為大家?guī)硪黄狿ython多維/嵌套字典數(shù)據(jù)無限遍歷的實現(xiàn)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-11-11Python 中下劃線的幾種用法(_、_xx、xx_、__xx、__xx__)
本文主要介紹了Python 中下劃線的幾種用法(_、_xx、xx_、__xx、__xx__),詳細的介紹了這幾種下劃線的用處,具有一定的參考價值,感興趣的可以了解一下2023-09-09