PyTorch蒙地卡羅

      在〈PyTorch蒙地卡羅〉中尚無留言

使用 pytorch 計算蒙地卡羅求 $(pi)$ 值運算,效能跟 Tensorflow 差不多。

在 Windows 及 Linux 分別安裝如下套件

#Windows 10
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 --no-cache-dir

#Linux
pip install torch torchvision torchaudio

蒙地卡羅求 $(pi)$ 的 pytorch 版完整程式碼如下

import time
import torch
def dist():
    #points=torch.rand([2, batch]).to(device)# 每次都產生一個陣列,會很慢的
    points=array.uniform_(0, 1)
    d=(points[0].square()+points[1].square()).sqrt()
    idx=torch.where(d<=1)
    #print(idx)
    #print(idx[0].shape[0])
    return idx[0].shape[0]
batch=100_000_000
epoch=500_000
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
array=torch.zeros([2,batch], dtype=torch.float32, device=device)

incircle=0
for e in range(epoch):
    t1=time.time()
    incircle += dist()
    area = incircle * 4  / ((e + 1)*batch)
    t2=time.time()
    print(f'GPU Epoch:{e+1:07,d} : {t2-t1:.5f}秒: pi={area}')

todo

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *