欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

pyTorch深度學(xué)習(xí)softmax實(shí)現(xiàn)解析

 更新時(shí)間:2021年09月30日 11:24:32   作者:算法菜鳥飛高高  
這篇文章主要介紹了pytorch深度學(xué)習(xí)中對softmax實(shí)現(xiàn)進(jìn)行了詳細(xì)解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步

用PyTorch實(shí)現(xiàn)linear模型

模擬數(shù)據(jù)集

num_inputs = 2 #feature number
num_examples = 1000 #訓(xùn)練樣本個(gè)數(shù)
true_w = torch.tensor([[2],[-3.4]]) #真實(shí)的權(quán)重值
true_b = torch.tensor(4.2) #真實(shí)的bias
samples = torch.normal(0,1,(num_examples,num_inputs))
noise = torch.normal(0,0.01,(num_examples,1))
labels = samples.matmul(true_w) + true_b + noise

定義模型

class LinearNet(nn.Module):
	def __init__(self,in_features):
		super().__init__()
		self.fc = nn.Linear(in_features=2,out_features=1)
	def forward(self,t):
		t = self.fc(t)
		return t

加載數(shù)據(jù)集

import torch.utils.data as Data
dataset = Data.TensorDataset(samples,labels)#類似于zip,把兩個(gè)張量打包
data_loader = Data.DataLoader(dataset,batch_size=100,shuffle=True)

optimizer

network = LinearNet(2)
optimizer = optim.SGD(network.paramters(),lr=0.05)

模型訓(xùn)練

for epoch in range(10):
    total_loss = 0
    for data,label in data_loader:
        predict = network(data)
        loss = F.mse_loss(predict,label)
        total_loss += loss.item()
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    print(
        'epoch',epoch,
        'loss',total_loss,
        'weight',network.weight,
        'bias',network.bias
    )

softmax回歸模型

sotfmax主要用于分類任務(wù)。regression最終得到的是一個(gè)scalar,根據(jù)input中的feature線性相加得到一個(gè)output。分類任務(wù)的結(jié)果是一個(gè)類別,是離散的。
假設(shè)現(xiàn)在有一批圖片是2 * 2大小的灰度圖片,這樣圖片中的每隔二像素用一個(gè)標(biāo)量表示就行了。這批圖片一種是三類小動(dòng)物,第一類是小狗,第二類是小貓,第三類是小兔子。
每張圖片總共4個(gè)像素點(diǎn),我們可以看作是4個(gè)feature,假設(shè)這三類小動(dòng)物的圖片線性可分,每一類對應(yīng)一組weight和一個(gè)bias。

在這里插入圖片描述

可以根據(jù)輸出值較大的來決定哪一類,可這樣有個(gè)問題,首先輸出值沒有明確的意義,且可能是實(shí)數(shù)范圍。其次,不好衡量輸出值與真實(shí)值之間的差距。所以采用softmax操作,將三個(gè)輸出值轉(zhuǎn)化成概率值,這樣輸出結(jié)果滿足概率分布。label采用one-hot編碼,相當(dāng)于對應(yīng)類別的概率是1,這樣就可以用cross_entropy來計(jì)算loss。

Fashion-MNIST

本次學(xué)習(xí)softmax模型采用torchvision.datasets中的Fashion-MNIST。

import torchvision
import torchvision.transforms as transforms
train_set = torchvision.datasets.FashionMNIST(
	root='./data',
	train=True,
	download=True,
	transform=transforms.ToTensor()
)

transforms.ToTensor()將尺寸為(H x W x C)且數(shù)據(jù)位于(0,255)的PIL圖片或者數(shù)據(jù)類型為np.uint8的NumPy數(shù)組轉(zhuǎn)換為尺寸為C x H x W且數(shù)據(jù)類型為torch.float32且位于(0.0,1.0)的Tensor

len(train_set),len(test_set)
> (60000,10000)

展示一下數(shù)據(jù)集中的圖片

import matplotlib.pyplot as plt
plt.figure(figsize=(10,10))
for i,(image,lable) in enumerate(train_set,start=1):
	plt.subplot(1,10,i)
	plt.imshow(image.squeeze())
	plt.title(train_set.classes[lable])
	plt.axis('off')
	if i == 10:
		break
plt.show()

在這里插入圖片描述

train_loader = torch.utils.data.DataLoader(train_set,batch_size=100,shuffle=True,num_workers=4)
test_loader = torch.utils.data.DataLoader(test_set,batch_size=100,shuffle=False,num_workers=1)

cross_entropy

def net(samples,w,b):
	samples = samples.flatten(start_dim=1) #將c,h,w三個(gè)軸展成一個(gè)feature軸,長度為28 * 28
	samples = torch.exp(samples)#全體元素取以e為底的指數(shù)
	partial_sum = samples.sum(dim=1,keepdim=True) 
	samples = samples / partial_sum #歸一化,得概率,這里還應(yīng)用了廣播機(jī)制
	return samples.matmul(w) + b	

在這里插入圖片描述

i表示label對應(yīng)的種類,pi為真實(shí)種類的預(yù)測概率,log是以e為底的對數(shù)
這里gather函數(shù)的作用,就是在predict上取到對應(yīng)label的概率值,注意負(fù)號不能丟,pytorch中的cross_entropy對輸入先進(jìn)行一次softmax操作,以保證輸入都是正的。

模型的實(shí)現(xiàn)

def net(samples,w,b):
	samples = samples.flatten(start_dim=1) #將c,h,w三個(gè)軸展成一個(gè)feature軸,長度為28 * 28
	samples = torch.exp(samples)#全體元素取以e為底的指數(shù)
	partial_sum = samples.sum(dim=1,keepdim=True) 
	samples = samples / partial_sum #歸一化,得概率,這里還應(yīng)用了廣播機(jī)制
	return samples.matmul(w) + b	

利用PyTorch簡易實(shí)現(xiàn)softmax

import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as Data
import torchvision.transforms as transforms
import torch.optim as optim
import torch.nn.init as init
class SoftmaxNet(nn.Module):
    def __init__(self,in_features,out_features):
        super().__init__()
        self.fc = nn.Linear(in_features=in_features,out_features=out_features)
    def forward(self,t):
        t = t.flatten(start_dim=1)
        t = self.fc(t)
        return t
train_set = torchvision.datasets.FashionMNIST(
    root='E:\project\python\jupyterbook\data',
    train=True,
    download=True,
    transform=transforms.ToTensor()
)
test_set = torchvision.datasets.FashionMNIST(
    root='E:\project\python\jupyterbook\data',
    train=False,
    download=True,
    transform=transforms.ToTensor()
)
train_loader = Data.DataLoader(
    train_set,
    batch_size=100,
    shuffle=True,
    #num_workers=2
)
test_loader = Data.DataLoader(
    test_set,
    batch_size=100,
    shuffle=False,
    #num_workers=2
)
@torch.no_grad()
def get_correct_nums(predict,labels):
    return predict.argmax(dim=1).eq(labels).sum().item()
@torch.no_grad()
def evaluate(test_loader,net,total_num):
    correct = 0
    for image,label in test_loader:
        predict = net(image)
        correct += get_correct_nums(predict,label)
        pass
    return correct / total_num
network = SoftmaxNet()
optimizer = optim.SGD(network.parameters(),lr=0.05)
for epoch in range(10):
    total_loss = 0
    total_correct = 0
    for image,label in train_loader:
        predict = network(image)
        loss = F.cross_entropy(predict,label)
        total_loss += loss.item()
        total_correct += get_correct_nums(predict,label)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        pass
    print(
        'epoch',epoch,
        'loss',total_loss,
        'train_acc',total_correct / len(train_set),
        'test_acc',evaluate(test_loader,network,len(test_set))
    )

以上就是pytorch深度學(xué)習(xí)softmax實(shí)現(xiàn)解析的詳細(xì)內(nèi)容,更多關(guān)于pytorch深度學(xué)習(xí)的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python中列表和元組的使用方法和區(qū)別詳解

    Python中列表和元組的使用方法和區(qū)別詳解

    這篇文章主要介紹了Python中列表和元組的使用方法和區(qū)別詳解的相關(guān)資料,需要的朋友可以參考下
    2016-07-07
  • Python使用multiprocessing實(shí)現(xiàn)多進(jìn)程的詳細(xì)步驟記錄

    Python使用multiprocessing實(shí)現(xiàn)多進(jìn)程的詳細(xì)步驟記錄

    multiprocessing包是Python中的多進(jìn)程管理包,與threading.Thread類似,它可以利用multiprocessing.Process對象來創(chuàng)建一個(gè)進(jìn)程,下面這篇文章主要給大家介紹了關(guān)于Python使用multiprocessing實(shí)現(xiàn)多進(jìn)程的詳細(xì)步驟,需要的朋友可以參考下
    2024-08-08
  • python如何解決指定代碼段超時(shí)程序卡死

    python如何解決指定代碼段超時(shí)程序卡死

    這篇文章主要介紹了python如何解決指定代碼段超時(shí)程序卡死,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • 如何使用pytorch實(shí)現(xiàn)LocallyConnected1D

    如何使用pytorch實(shí)現(xiàn)LocallyConnected1D

    由于LocallyConnected1D是Keras中的函數(shù),為了用pytorch實(shí)現(xiàn)LocallyConnected1D并在960×33的數(shù)據(jù)集上進(jìn)行訓(xùn)練和驗(yàn)證,本文分步驟給大家介紹如何使用pytorch實(shí)現(xiàn)LocallyConnected1D,感興趣的朋友一起看看吧
    2023-09-09
  • Python協(xié)程實(shí)踐分享

    Python協(xié)程實(shí)踐分享

    這篇文章主要分享的是Python協(xié)程實(shí)踐,協(xié)程簡單來說就是一個(gè)更加輕量級的線程,并且不由操作系統(tǒng)內(nèi)核管理,完全由程序所控制,下文相關(guān)介紹需要的朋友可以參考一下
    2022-05-05
  • Python中threading模塊的Lock和RLock區(qū)別詳解

    Python中threading模塊的Lock和RLock區(qū)別詳解

    這篇文章主要介紹了Python中threading模塊的Lock和RLock區(qū)別詳解,Lock鎖是Python的原始鎖,在鎖定時(shí)不屬于任何一個(gè)線程,在調(diào)用了 lock.acquire() 方法后,進(jìn)入鎖定狀態(tài),lock.release()方法可以解鎖,底層是通過一個(gè)函數(shù)來實(shí)現(xiàn)的,需要的朋友可以參考下
    2023-09-09
  • 淺談tensorflow之內(nèi)存暴漲問題

    淺談tensorflow之內(nèi)存暴漲問題

    今天小編就為大家分享一篇淺談tensorflow之內(nèi)存暴漲問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02
  • 將python程序打包成DLL的三種方式

    將python程序打包成DLL的三種方式

    這篇文章主要介紹了將python程序打包成DLL的三種方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-02-02
  • 使用python對多個(gè)txt文件中的數(shù)據(jù)進(jìn)行篩選的方法

    使用python對多個(gè)txt文件中的數(shù)據(jù)進(jìn)行篩選的方法

    今天小編就為大家分享一篇使用python對多個(gè)txt文件中的數(shù)據(jù)進(jìn)行篩選的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • 對Python3之進(jìn)程池與回調(diào)函數(shù)的實(shí)例詳解

    對Python3之進(jìn)程池與回調(diào)函數(shù)的實(shí)例詳解

    今天小編就為大家分享一篇對Python3之進(jìn)程池與回調(diào)函數(shù)的實(shí)例詳解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-01-01

最新評論