利用torch.nn实现softmax回归Fashion-MNIST数据集上进行训练和测试

利用torch.nn实现softmax回归Fashion-MNIST数据集上进行训练和测试:

1)(2)(3)同上

4)构建模型

  1. num_inputs = 784  
  2. num_outputs = 10  10  
  3.   
  4. 构建模型  
  5. class softmaxnet(torch.nn.Module):  
  6.     def __init__(self, n_features, n_labels):  
  7.         super(softmaxnet, self).__init__()  
  8.         self.linear = torch.nn.Linear(n_features, n_labels)  
  9.   
  10.     def softmax(self, X):  # softmax计算  
  11.         X_exp = X.exp()  对每个元素做指数运算  
  12.         partition = X_exp.sum(dim=1, keepdim=True)  求列和,即对同行元素求和 n*1  
  13.         return X_exp / partition  # broadcast  
  14.   
  15.     def forward(self, x):  
  16.         x_ = x.view((-1, num_inputs))  
  17.         y_ = self.linear(x_)  
  18.         y_hat = self.softmax(y_)  
  19.         return y_hat  

5)损失函数和优化算法

  1. #损失函数和优化方法  
  2. net = softmaxnet(num_inputs, num_outputs)  
  3. lr = 0.3  
  4. loss = torch.nn.CrossEntropyLoss()  
  5. optimizer = torch.optim.SGD(net.parameters(), lr=lr)  

6)构建测试集准确率函数

  1. #测试集的准确度与损失  
  2. def get_test_info(data_iter, net):  
  3.     right_count, all_count = 0.0, 0  
  4.     for x, y in data_iter:  
  5.         y_ = net(x)  
  6.         l = loss(y_, y)  
  7.         right_count += (y_.argmax(dim=1)==y).sum().item()  
  8.         all_count += y.shape[0]  
  9.     return right_count/all_count, l.item() 

7)开始优化并分别输出训练集和测试集的损失和准确率

  1. num_epoch = 20  
  2.   
  3. for epoch in range(num_epoch):  
  4.     train_r_num, train_all_num = 0.0, 0  
  5.     for X, y in train_iter:  
  6.         y_ = net(X)  
  7.         l = loss(y_, y)  
  8.         l.backward()  
  9.         optimizer.step()  
  10.         optimizer.zero_grad()  
  11.         train_r_num += (y_.argmax(dim=1) == y).sum().item()  
  12.         train_all_num += y.shape[0]  
  13.     test_acc, test_ave_loss = get_test_info(test_iter, net)  
  14.     print('epoch %d, train loss %.4f, train acc %.3f' % (epoch+1, l.item(), train_r_num/train_all_num))  
  15.     print('          test loss %.4f, test acc %.3f' % (test_ave_loss, test_acc))  
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
好的,以下是使用torch.nn实现softmax回归Fashion-MNIST数据集进行训练测试,并对结果进行分析的步骤: 首先,导入所需的库和模块: ```python import torch import torch.nn as nn import torch.optim as optim from torchvision import datasets, transforms ``` 然后,加载Fashion-MNIST数据集进行预处理: ```python # 定义数据转换 transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,)) ]) # 加载训练集和测试集 train_dataset = datasets.FashionMNIST(root='./data', train=True, transform=transform, download=True) test_dataset = datasets.FashionMNIST(root='./data', train=False, transform=transform, download=True) # 创建数据加载器 train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=64, shuffle=True) test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=64, shuffle=False) ``` 接下来,定义softmax回归模型: ```python class SoftmaxRegression(nn.Module): def __init__(self, input_dim, num_classes): super(SoftmaxRegression, self).__init__() self.linear = nn.Linear(input_dim, num_classes) def forward(self, x): out = self.linear(x) return out model = SoftmaxRegression(28 * 28, 10) ``` 然后,定义损失函数和优化器: ```python criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.01) ``` 接着,进行模型的训练: ```python num_epochs = 10 for epoch in range(num_epochs): total_loss = 0 for images, labels in train_loader: images = images.view(-1, 28 * 28) # 前向传播 outputs = model(images) loss = criterion(outputs, labels) # 反向传播和优化 optimizer.zero_grad() loss.backward() optimizer.step() total_loss += loss.item() # 打印每个epoch的损失函数值 print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, total_loss)) ``` 最后,对模型进行测试并分析结果: ```python # 在训练集上进行预测 correct_train = 0 total_train = 0 with torch.no_grad(): for images, labels in train_loader: images = images.view(-1, 28 * 28) outputs = model(images) _, train_predicted = torch.max(outputs.data, 1) total_train += labels.size(0) correct_train += (train_predicted == labels).sum().item() train_accuracy = correct_train / total_train # 在测试集上进行预测 correct_test = 0 total_test = 0 with torch.no_grad(): for images, labels in test_loader: images = images.view(-1, 28 * 28) outputs = model(images) _, test_predicted = torch.max(outputs.data, 1) total_test += labels.size(0) correct_test += (test_predicted == labels).sum().item() test_accuracy = correct_test / total_test print('Train Accuracy: {:.2f}%'.format(train_accuracy * 100)) print('Test Accuracy: {:.2f}%'.format(test_accuracy * 100)) ``` 通过以上步骤,我们可以使用torch.nn实现softmax回归模型在Fashion-MNIST数据集进行训练测试,并从loss训练集以及测试集上的准确率等多个角度对结果进行分析。可以观察每个epoch的损失函数逐渐减小,同时计算训练集和测试集上的准确率来评估模型的性能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值