????softmax的輸入不需要再做非線性變換,即softmax之前不再需要激活函數(shù)(relu)。
softmax兩個(gè)作用:
1、如果在進(jìn)行softmax前的input有負(fù)數(shù)氧急,通過指數(shù)變換,得到正數(shù)毫深。
2吩坝、使所有類的概率求和為1。
????在多分類問題中哑蔫,標(biāo)簽y的類型是LongTensor钉寝。比如說手寫字符0-9分類問題弧呐,如果y = torch.LongTensor([3]),對(duì)應(yīng)的one-hot是[0,0,0,1,0,0,0,0,0,0].(這里要注意嵌纲,如果使用了one-hot俘枫,標(biāo)簽y的類型是LongTensor,糖尿病數(shù)據(jù)集中的target的類型是FloatTensor)
''' 手寫字符識(shí)別pytorch實(shí)現(xiàn) '''
import torch
from torchvision import transforms, datasets
from torch.utils.data import DataLoader
import torch.nn.functional as F
from tqdm import tqdm
#定義一個(gè)cpu
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# prepare dataset
batch_size = 64
# 圖像預(yù)處理
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))]) #歸一化逮走,兩個(gè)值是均值和方差
train_dataset = datasets.MNIST(root = 'dataset/mnist/', train = True, download = True, transform = transform)
train_loader = DataLoader(train_dataset, shuffle = True, batch_size = batch_size)
test_dataset = datasets.MNIST(root = 'dataset/mnist/', train = False, download = True, transform = transform)
test_loader = DataLoader(test_dataset, shuffle = False, batch_size = batch_size)
# design model using class
class Net(torch.nn.Module):
def __init__(self):
super(Net, self).__init__()
self.l1 = torch.nn.Linear(28*28, 512)
self.l2 = torch.nn.Linear(512, 256)
self.l3 = torch.nn.Linear(256, 128)
self.l4 = torch.nn.Linear(128, 64)
self.l5 = torch.nn.Linear(64, 10)
def forward(self, x):
x = x.view(-1, 784) #將N*1*28*28的圖片轉(zhuǎn)換成N*1*784鸠蚪,-1代表N的值,即自動(dòng)獲取mini_batch
x = F.relu(self.l1(x))
x = F.relu(self.l2(x))
x = F.relu(self.l3(x))
x = F.relu(self.l4(x))
return self.l5(x) # 最后一層不做激活,直接接到softmax
model = Net()
model.to(device)
# construct loss and optimizer
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr = 0.01, momentum = 0.5)
# training cycle forward, backward, update
def train(epoch):
running_loss = 0.0
for batch_idx, data in enumerate(tqdm(train_loader), 0):
inputs, labels = data[0].to(device), data[1].to(device) # 使用gpu訓(xùn)練
optimizer.zero_grad()
#forward + backward + optimize
# 獲得模型預(yù)測(cè)結(jié)果(64, 10)
outputs = model(inputs)
# 交叉熵代價(jià)函數(shù)outputs(64,10),target(64)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if batch_idx % 300 == 299: # 輸出每次的平均loss
print('\n [%d, %5d] loss: %.3f' % (epoch+1, batch_idx+1, running_loss/300))
running_loss = 0.0
def test():
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data[0].to(device), data[1].to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, dim = 1) #并不關(guān)心最大值是多少师溅,用下劃線來存茅信,需要在意的是index,
#dim=1表示輸出所在行的最大值墓臭,若改寫成dim=0則輸出所在列的最大值蘸鲸。
total += labels.size(0) # N*1
correct += (predicted == labels).sum().item() # 張量之間的比較運(yùn)算
print('accuracy on test set: %d %% ' % (100*correct/total))
if __name__ == '__main__':
for epoch in range(10):
train(epoch)
test()