內容太多,撿重要的講。
在分類問題中,通常用離散的數值表示類別,這里存在兩個問題。1.輸出值的范圍不確定,很難判斷值的意義。2.真實標簽是離散值,這些離散值與不確定的范圍的輸出值之間的誤差難以衡量。
softmax運算符解決了這兩個問題。它把輸出值變成了值為正且和為1的概率分布。
對於一個分類問題,假設有a個特征,b個樣本,c個輸出,單層的全連接網絡,那么有a*b個w(權重),c個b(偏差)。
為了提升計算效率,常對小批量數據做矢量計算。softmax回歸的矢量計算表達式如下。
計算loss用交叉熵損失函數,如下:
最后講講softmax的簡潔實現:
import torch from torch import nn from torch.nn import init import numpy as np import sys sys.path.append("/home/kesci/input") import d2lzh1981 as d2l from collections import OrderedDict batch_size = 256 train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size) num_inputs = 784 num_outputs = 10 class LinearNet(nn.Module): def __init__(self, num_inputs, num_outputs): super(LinearNet, self).__init__() self.linear = nn.Linear(num_inputs, num_outputs) def forward(self, x): # x 的形狀: (batch, 1, 28, 28) y = self.linear(x.view(x.shape[0], -1)) return y class FlattenLayer(nn.Module): def __init__(self): super(FlattenLayer, self).__init__() def forward(self, x): # x 的形狀: (batch, *, *, ...) return x.view(x.shape[0], -1) net = nn.Sequential( # FlattenLayer(), # LinearNet(num_inputs, num_outputs) OrderedDict([ ('flatten', FlattenLayer()), ('linear', nn.Linear(num_inputs, num_outputs))]) init.normal_(net.linear.weight, mean=0, std=0.01) #參數初始化 init.constant_(net.linear.bias, val=0) loss = nn.CrossEntropyLoss() optimizer = torch.optim.SGD(net.parameters(), lr=0.1) num_epochs = 5 d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, None, None, optimizer)
代碼摘自平台。