1.对真实值类别编码:
- y为真实值,有且仅有一个位置值为1,该位置即为该元素真实类别
2.预测值:
- Oi为该元素与类别i匹配的置信度
3.目标函数要求:
- 对于正确类y的置信度Oy要远远大于其他非正确类的置信度Oi,才能使识别到的正确类与错误类具有更明显的差距
4.使用Softmax模型将输出置信度Oi计算转换为输出匹配概率y^i:
文章来源:https://www.toymoban.com/news/detail-804354.html
- y^为n维向量,每个元素非负且和为1
- y^i为元素与类别i匹配的概率
5.使用交叉熵作为损失函数:
文章来源地址https://www.toymoban.com/news/detail-804354.html
- L为真实概率y与预测概率y^的差距
- 分类问题不关心非正确类的预测值,只关心正确类的预测值有多大
6.代码实现:
import sys
import os
import matplotlib.pyplot as plt
import torch
import torchvision
from torchvision import transforms
from torch.utils import data
from d2l import torch as d2l
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
## 读取小批量数据
batch_size = 256
trans = transforms.ToTensor()
#train_iter, test_iter = common.load_fashion_mnist(batch_size) #无法翻墙的,可以参考这种方法取下载数据集
mnist_train = torchvision.datasets.FashionMNIST(
root="../data", train=True, transform=trans, download=True) # 需要网络翻墙,这里数据集会自动下载到项目跟目录的/data目录下
mnist_test = torchvision.datasets.FashionMNIST(
root="../data", train=False, transform=trans, download=True) # 需要网络翻墙,这里数据集会自动下载到项目跟目录的/data目录下
print(len(mnist_train)) # train_iter的长度是235;说明数据被分成了234组大小为256的数据加上最后一组大小不足256的数据
print('11111111')
## 展示部分数据
def get_fashion_mnist_labels(labels): # @save
"""返回Fashion-MNIST数据集的文本标签。"""
text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat',
'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot']
return [text_labels[int(i)] for i in labels]
def show_fashion_mnist(images, labels):
d2l.use_svg_display()
# 这里的_表示我们忽略(不使用)的变量
_, figs = plt.subplots(1, len(images), figsize=(12, 12))
for f, img, lbl in zip(figs, images, labels):
f.imshow(img.view((28, 28)).numpy())
f.set_title(lbl)
f.axes.get_xaxis().set_visible(False)
f.axes.get_yaxis().set_visible(False)
plt.show()
train_data, train_targets = next(iter(data.DataLoader(mnist_train, batch_size=18)))
#展示部分训练数据
show_fashion_mnist(train_data[0:10], train_targets[0:10])
# 初始化模型参数
num_inputs = 784
num_outputs = 10
W = torch.normal(0, 0.01, size=(num_inputs, num_outputs), requires_grad=True)
b = torch.zeros(num_outputs, requires_grad=True)
# 定义模型
def softmax(X):
X_exp = X.exp()
partition = X_exp.sum(dim=1, keepdim=True)
return X_exp / partition # 这里应用了广播机制
def net(X):
return softmax(torch.matmul(X.reshape(-1, num_inputs), W) + b)
# 定义损失函数
y_hat = torch.tensor([[0.1, 0.3, 0.6], [0.3, 0.2, 0.5]])
y = torch.LongTensor([0, 2])
y_hat.gather(1, y.view(-1, 1))
def cross_entropy(y_hat, y):
return - torch.log(y_hat.gather(1, y.view(-1, 1)))
# 计算分类准确率
def accuracy(y_hat, y):
return (y_hat.argmax(dim=1) == y).float().mean().item()
# 计算这个训练集的准确率
def evaluate_accuracy(data_iter, net):
acc_sum, n = 0.0, 0
for X, y in data_iter:
acc_sum += (net(X).argmax(dim=1) == y).float().sum().item()
n += y.shape[0]
return acc_sum / n
num_epochs, lr = 10, 0.1
# 本函数已保存在d2lzh包中方便以后使用
def train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size,
params=None, lr=None, optimizer=None):
for epoch in range(num_epochs):
train_l_sum, train_acc_sum, n = 0.0, 0.0, 0
for X, y in train_iter:
y_hat = net(X)
l = loss(y_hat, y).sum()
# 梯度清零
if params is not None and params[0].grad is not None:
for param in params:
param.grad.data.zero_()
l.backward()
# 执行优化方法
if optimizer is not None:
optimizer.step()
else:
d2l.sgd(params, lr, batch_size)
train_l_sum += l.item()
train_acc_sum += (y_hat.argmax(dim=1) == y).sum().item()
n += y.shape[0]
test_acc = evaluate_accuracy(test_iter, net)
print('epoch %d, loss %.4f, train acc %.3f, test acc %.3f'
% (epoch + 1, train_l_sum / n, train_acc_sum / n, test_acc))
# 训练模型
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
train_ch3(net, train_iter, test_iter, cross_entropy, num_epochs, batch_size, [W, b], lr)
# 预测模型
for X, y in test_iter:
break
true_labels = get_fashion_mnist_labels(y.numpy())
pred_labels = get_fashion_mnist_labels(net(X).argmax(dim=1).numpy())
titles = [true + '\n' + pred for true, pred in zip(true_labels, pred_labels)]
show_fashion_mnist(X[0:9], titles[0:9])
到了这里,关于Softmax回归(多类分类模型)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!