print(torch.cuda.is_available()) # ได้ True
torch.backends.cudnn.is_available() # ได้ True
t = torch.cuda.LongTensor([1])
print(t) # ได้ tensor([1], device='cuda:0')
t = torch.randn(3)
print(t) # ได้ tensor([ 0.9278, -0.4722, -0.7108])
print(t.cuda()) # ได้ tensor([ 0.9278, -0.4722, -0.7108], device='cuda:0')
print(t.cuda().cpu()) # ได้ tensor([ 0.9278, -0.4722, -0.7108])
print(t.cpu()) # ได้ tensor([ 0.9278, -0.4722, -0.7108])
print(t.cuda().cuda()) # ได้ tensor([ 0.9278, -0.4722, -0.7108], device='cuda:0')
t = torch.rand(4)
dev = torch.device('cuda')
print(t.to(dev)) # tensor([0.1237, 0.5063, 0.2424, 0.6088], device='cuda:0')
dev = torch.device('cpu')
print(t.to(dev)) # tensor([0.1237, 0.5063, 0.2424, 0.6088])
lin = torch.nn.Linear(3,2)
lin.cuda()
print(lin.weight)
Parameter containing:
tensor([[ 0.0067, -0.5206, 0.4279],
[-0.5000, 0.1692, 0.2832]], device='cuda:0', requires_grad=True)
t = torch.randn([10000,50000]).cuda() # RuntimeError: CUDA error: out of memory
t = torch.randn([10000,20000]).cuda()
t = t.cpu() # หรือแค่พิมพ์ del t ลบทิ้ง
torch.cuda.empty_cache()
torch.Tensor([1])+torch.Tensor([2]).cuda() # RuntimeError
torch.cuda.LongTensor([2]).numpy() # RuntimeError
import numpy as np
import matplotlib.pyplot as plt
import torch
import time
dev = torch.device('cuda')
relu = torch.nn.ReLU()
ha_entropy = torch.nn.CrossEntropyLoss()
khrongkhai = torch.nn.Sequential(
torch.nn.Linear(2,64),
relu,
torch.nn.Linear(64,5))
khrongkhai.to(dev)
x = np.random.uniform(0,12,20000)
y = np.random.uniform(0,4,20000)
X = np.array([x,y]).T
z = (y+np.sin(x)).astype(int)
plt.scatter(x,y,c=z,edgecolor='k',cmap='rainbow',alpha=0.05)
plt.figure()
opt = torch.optim.Adam(khrongkhai.parameters(),lr=0.002)
lis_khanaen = []
X = torch.Tensor(X).to(dev)
z = torch.LongTensor(z).to(dev)
t_roem = time.time()
for o in range(10000):
a = khrongkhai(X)
J = ha_entropy(a,z)
J.backward()
opt.step()
opt.zero_grad()
khanaen = (a.argmax(1)==z).cpu().numpy().mean()
lis_khanaen.append(khanaen)
if(o%500==499):
print('%d ครั้งผ่านไป ใช้เวลาไป %.1f วินาที ทำนายแม่น %.4f'%(o+1,time.time()-t_roem,khanaen))
plt.plot(lis_khanaen)
plt.show()
from torch.utils.data import DataLoader as Dalo
import torchvision.datasets as ds
import torchvision.transforms as tf
relu = torch.nn.ReLU()
ha_entropy = torch.nn.CrossEntropyLoss()
class Plianrup(torch.nn.Module):
def __init__(self,*k):
super(Plianrup,self).__init__()
self.k = k
def forward(self,x):
return x.reshape(x.size()[0],*self.k)
class Prasat(torch.nn.Sequential):
def __init__(self,kwang,m_cnn,m_lin,eta=0.001,dropout=0,bn=0,gpu=0):
super(Prasat,self).__init__()
'''
kwang: ความกว้างของภาพ
m_cnn:
m[0]: จำนวนขาเข้า
m[1]: จำนวนขาออก
m[2]: ขนาดตัวกรอง
m[3]: stride
m[4]: pad
m[5]: ขนาด maxpool
m_lin: ขนาดขาออกของชั้นเชิงเส้นแต่ละชั้น
eta: อัตราการเรียนรู้
dropout: อัตราดรอปเอาต์ในแต่ละชั้น
bn: แทรกแบตช์นอร์มระหว่างแต่ละชั้นหรือไม่
'''
for i,m in enumerate(m_cnn,1):
kwang = np.floor((kwang-m[2]+m[4]*2.)/m[3])+1
c = torch.nn.Conv2d(m[0],m[1],m[2],m[3],m[4])
torch.nn.init.kaiming_normal_(c.weight)
c.bias.data.fill_(0)
self.add_module('c%d'%i,c)
self.add_module('relu_c%d'%i,relu)
if(bn):
self.add_module('bano_c%d'%i,torch.nn.BatchNorm2d(m[1]))
if(m[5]>1):
self.add_module('maxp_c%d'%i,torch.nn.MaxPool2d(m[5]))
kwang = np.floor(kwang/m[5])
if(dropout):
self.add_module('droa_c%d'%i,torch.nn.Dropout(dropout))
self.add_module('o',Plianrup(-1))
m_lin = [int(kwang)**2*m_cnn[-1][1]]+m_lin
nm = len(m_lin)
for i in range(1,nm):
c = torch.nn.Linear(m_lin[i-1],m_lin[i])
torch.nn.init.kaiming_normal_(c.weight)
c.bias.data.fill_(0)
self.add_module('l%d'%i,c)
if(i<nm-1):
if(bn):
self.add_module('bano_l%d'%i,torch.nn.BatchNorm1d(m_lin[i]))
if(dropout):
self.add_module('droa_l%d'%i,torch.nn.Dropout(dropout))
self.add_module('relu_l%d'%i,relu)
# กำหนดว่าจะใช้ GPU หรือ CPU
if(gpu):
self.dev = torch.device('cuda')
self.cuda()
else:
self.dev = torch.device('cpu')
self.opt = torch.optim.Adam(self.parameters(),lr=eta)
def rianru(self,rup_fuek,rup_truat,n_thamsam=500,n_batch=64,n_batch_truat=512,ro=10):
self.khanaen = []
khanaen_sungsut = 0
t_roem = time.time()
for o in range(n_thamsam):
self.train()
for Xb,zb in rup_fuek:
a = self(Xb.to(self.dev))
J = ha_entropy(a,zb.to(self.dev))
J.backward()
self.opt.step()
self.opt.zero_grad()
self.eval()
khanaen = []
for Xb,zb in rup_truat:
khanaen.append(self.thamnai_(Xb.to(self.dev)).cpu()==zb)
khanaen = torch.cat(khanaen).numpy().mean()
self.khanaen.append(khanaen)
print('%d ครั้งผ่านไป ใช้เวลาไป %.1f นาที ทำนายแม่น %.4f'%(o+1,(time.time()-t_roem)/60,khanaen))
if(khanaen>khanaen_sungsut):
khanaen_sungsut = khanaen
maiphoem = 0
else:
maiphoem += 1
if(ro>0 and maiphoem>=ro):
break
def thamnai_(self,X):
return self(X).argmax(1)
folder_cifar10 = 'pytorchdata/cifar'
tran = tf.Compose([
tf.RandomHorizontalFlip(),
tf.ToTensor(),
tf.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))])
rup_fuek = ds.CIFAR10(folder_cifar10,transform=tran,train=1,download=1)
rup_fuek = Dalo(rup_fuek,batch_size=32,shuffle=True)
tran = tf.Compose([
tf.ToTensor(),
tf.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))])
rup_truat = ds.CIFAR10(folder_cifar10,transform=tran,train=0)
rup_truat = Dalo(rup_truat,batch_size=32)
m_cnn = [
[3,64,3,1,1,2],
[64,128,3,1,1,2],
[128,256,3,1,1,2],
[256,512,3,1,1,2],
]
m_lin = [512,64,10]
prasat = Prasat(32,m_cnn,m_lin,eta=0.001,dropout=0.5,bn=1,gpu=1)
prasat.rianru(rup_fuek,rup_truat,ro=5)
plt.plot(prasat.khanaen)
plt.show()
ติดตามอัปเดตของบล็อกได้ที่แฟนเพจ