do = torch.nn.Dropout()
print(do) # ได้ Dropout(p=0.5, inplace=False)
do = torch.nn.Dropout(0.2)
print(do) # ได้ Dropout(p=0.2, inplace=False)
bn = torch.nn.BatchNorm1d(5)
print(bn) # ได้ BatchNorm1d(5, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
print(bn.weight) # ได้ Parameter containing: tensor([1., 1., 1., 1., 1.], requires_grad=True)
print(bn.bias) # ได้ Parameter containing: tensor([0., 0., 0., 0., 0.], requires_grad=True)
bn = torch.nn.BatchNorm1d(5,affine=0)
print(bn) # ได้ BatchNorm1d(5, eps=1e-05, momentum=0.1, affine=0, track_running_stats=True)
print(bn.weight) # ได้ None
print(bn.bias) # ได้ None
do = torch.nn.Dropout()
print(do.training) # ได้ True
do.eval()
print(do.training) # ได้ False
do.train()
print(do.training) # ได้ True
seq = torch.nn.Sequential(torch.nn.Dropout(),torch.nn.BatchNorm1d(10))
print(seq[0].training,seq[1].training) # ได้ True True
seq.eval()
print(seq[0].training,seq[1].training) # ได้ False False
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(8)
z = np.arange(5).repeat(80)
r = np.random.normal(z+1,0.35)
t = np.random.normal(1,1,400)
x = r*np.cos(t)
y = r*np.sin(t)
X = np.array([x,y]).T
plt.scatter(x,y,c=z,edgecolor='k',cmap='rainbow')
plt.show()
import torch
relu = torch.nn.ReLU()
ha_entropy = torch.nn.CrossEntropyLoss()
class Prasat(torch.nn.Sequential):
def __init__(self,m,eta=0.01,dropout=0,bn=0):
super(Prasat,self).__init__()
nm = len(m)
for i in range(1,nm):
lin = torch.nn.Linear(m[i-1],m[i])
torch.nn.init.kaiming_normal_(lin.weight)
lin.bias.data.fill_(0)
self.add_module('lin%d'%i,lin)
if(i<nm-1):
if(bn): # สร้างชั้นแบตช์นอร์ม
self.add_module('bano%d'%i,torch.nn.BatchNorm1d(m[i]))
if(dropout): # สร้างชั้นดรอปเอาต์
self.add_module('droa%d'%i,torch.nn.Dropout(dropout))
self.add_module('relu%d'%i,relu)
self.opt = torch.optim.Adam(self.parameters(),lr=eta)
def rianru(self,X,z,X_truat,z_truat,n_thamsam):
X = torch.Tensor(X)
z = torch.LongTensor(z)
X_truat = torch.Tensor(X_truat)
z_truat = torch.LongTensor(z_truat)
self.entropy = []
self.khanaen_fuek = []
self.khanaen_truat = []
for o in range(n_thamsam):
self.train() # ปรับเป็นโหมดฝึก
a = self(X)
J = ha_entropy(a,z)
J.backward()
self.opt.step()
self.opt.zero_grad()
self.entropy.append(float(J)) # เอนโทรปี
self.eval() # ปรับเป็นโหมดทดสอบ
self.khanaen_fuek.append(self.ha_khanaen_(X,z)) # คะแนนทำนายชุดข้อมูลฝึก
self.khanaen_truat.append(self.ha_khanaen_(X_truat,z_truat)) # คำแนนทำนายชุดข้อมูลตรวจสอบ
def thamnai(self,X):
X = torch.Tensor(X)
return self.thamnai_(X).numpy()
def thamnai_(self,X):
return self(X).argmax(1)
def ha_khanaen_(self,X,z):
return (self.thamnai_(X)==z).numpy().mean()
sumlueak = np.random.permutation(len(z))
X_fuek,X_truat = X[sumlueak[:320]],X[sumlueak[320:]]
z_fuek,z_truat = z[sumlueak[:320]],z[sumlueak[320:]]
plt.figure(figsize=(6,9))
ax1 = plt.subplot(311)
ax1.set_title(u'เอนโทรปีไขว้',family='Tahoma',size=12)
ax2 = plt.subplot(312)
ax2.set_title(u'ความแม่นในการทำนายชุดข้อมูลฝึก',family='Tahoma',size=12)
ax3 = plt.subplot(313)
ax3.set_title(u'ความแม่นในการทำนายชุดข้อมูลตรวจสอบ',family='Tahoma',size=12)
for dropout in [0,1]:
for bn in [0,1]:
prasat = Prasat([2,300,300,300,5],eta=0.005,dropout=dropout*0.2,bn=bn)
prasat.rianru(X_fuek,z_fuek,X_truat,z_truat,200)
ls = ['--','-'][bn]
si = ['#55aa66','#aa5588'][dropout]
ax1.plot(prasat.entropy,si,ls=ls)
ax2.plot(prasat.khanaen_fuek,si,ls=ls)
ax3.plot(prasat.khanaen_truat,si,ls=ls)
ax1.legend([u'ไม่มี batchnorm, dropout=0',
u'มี batchnorm, dropout=0',
u'ไม่มี batchnorm, dropout=0.2',
u'มี batchnorm, dropout=0.2'],
prop={'family':'Tahoma','size':15})
plt.tight_layout()
plt.show()
plt.figure()
mx,my = np.meshgrid(np.linspace(x.min(),x.max(),200),np.linspace(y.min(),y.max(),200))
mX = torch.Tensor(np.array([mx.ravel(),my.ravel()]).T)
mz = prasat.thamnai(mX).reshape(200,200)
plt.xlim(x.min(),x.max())
plt.ylim(y.min(),y.max())
plt.scatter(x,y,c=z,edgecolor='k',cmap='rainbow')
plt.contourf(mx,my,mz,alpha=0.2,cmap='rainbow')
plt.show()
ติดตามอัปเดตของบล็อกได้ที่แฟนเพจ