pyTorch深度学习softmax实现解析
用pytorch实现linear模型
模拟数据集
num_inputs = 2 #feature number num_examples = 1000 #训练样本个数 true_w = torch.tensor([[2],[-3.4]]) #真实的权重值 true_b = torch.tensor(4.2) #真实的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
加载数据集
import torch.utils.data as data dataset = data.tensordataset(samples,labels)#类似于zip,把两个张量打包 data_loader = data.dataloader(dataset,batch_size=100,shuffle=true)
optimizer
network = linearnet(2) optimizer = optim.sgd(network.paramters(),lr=0.05)
模型训练
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主要用于分类任务。regression最终得到的是一个scalar,根据input中的feature线性相加得到一个output。分类任务的结果是一个类别,是离散的。
假设现在有一批图片是2 * 2大小的灰度图片,这样图片中的每隔二像素用一个标量表示就行了。这批图片一种是三类小动物,第一类是小狗,第二类是小猫,第三类是小兔子。
每张图片总共4个像素点,我们可以看作是4个feature,假设这三类小动物的图片线性可分,每一类对应一组weight和一个bias。
可以根据输出值较大的来决定哪一类,可这样有个问题,首先输出值没有明确的意义,且可能是实数范围。其次,不好衡量输出值与真实值之间的差距。所以采用softmax操作,将三个输出值转化成概率值,这样输出结果满足概率分布。label采用one-hot编码,相当于对应类别的概率是1,这样就可以用cross_entropy来计算loss。
fashion-mnist
本次学习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)且数据位于(0,255)的pil图片或者数据类型为np.uint8的numpy数组转换为尺寸为c x h x w且数据类型为torch.float32且位于(0.0,1.0)的tensor
len(train_set),len(test_set) > (60000,10000)
展示一下数据集中的图片
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三个轴展成一个feature轴,长度为28 * 28 samples = torch.exp(samples)#全体元素取以e为底的指数 partial_sum = samples.sum(dim=1,keepdim=true) samples = samples / partial_sum #归一化,得概率,这里还应用了广播机制 return samples.matmul(w) + b
i表示label对应的种类,pi为真实种类的预测概率,log是以e为底的对数
这里gather函数的作用,就是在predict上取到对应label的概率值,注意负号不能丢,pytorch中的cross_entropy对输入先进行一次softmax操作,以保证输入都是正的。
模型的实现
def net(samples,w,b): samples = samples.flatten(start_dim=1) #将c,h,w三个轴展成一个feature轴,长度为28 * 28 samples = torch.exp(samples)#全体元素取以e为底的指数 partial_sum = samples.sum(dim=1,keepdim=true) samples = samples / partial_sum #归一化,得概率,这里还应用了广播机制 return samples.matmul(w) + b
利用pytorch简易实现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深度学习softmax实现解析的详细内容,更多关于pytorch深度学习的资料请关注其它相关文章!