PyTorch深度学习实践概论笔记9练习-​使用kaggle的Otto数据集做多分类​

本文主要是介绍PyTorch深度学习实践概论笔记9练习-​使用kaggle的Otto数据集做多分类​,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在文章PyTorch深度学习实践概论笔记9-SoftMax分类器中刘老师给了一个课后练习题,下载kaggle的Otto数据集做多分类。

0 Overview

先看看官网给的背景介绍。

The Otto Group is one of the world’s biggest e-commerce companies, with subsidiaries in more than 20 countries, including Crate & Barrel (USA), Otto.de (Germany) and 3 Suisses (France). We are selling millions of products worldwide every day, with several thousand products being added to our product line.

奥托集团是世界上最大的电子商务公司之一,在20多个国家拥有子公司,包括美国的Crate & Barrel,德国的Otto.de和法国的3 Suisse。我们每天在全球销售数以百万计的产品,其中有几千种产品加入到我们的产品线中。】

A consistent analysis of the performance of our products is crucial. However, due to our diverse global infrastructure, many identical products get classified differently. Therefore, the quality of our product analysis depends heavily on the ability to accurately cluster similar products. The better the classification, the more insights we can generate about our product range.

对我们产品性能的一致分析是至关重要的。然而,由于我们多元化的全球基础设施,许多相同的产品被分类不同。因此,我们产品分析的质量在很大程度上依赖于对相似产品进行准确聚类的能力。分类越好,我们对产品范围的了解就越多。】

For this competition, we have provided a dataset with 93 features for more than 200,000 products. The objective is to build a predictive model which is able to distinguish between our main product categories. The winning models will be open sourced.

【在这次竞赛中,我们为超过200,000个产品提供了包含93个特性的数据集。我们的目标是建立一个能够区分我们主要产品类别的预测模型。获奖的模型将是开源的。】

1 数据获取

点击官网链接Otto Group Product Classification Challenge | Kaggle可以下载。

2 查看数据

先读取数据,然后查看一下数据情况。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#1.读取数据
otto_data = pd.read_csv("./otto/train.csv")
otto_data.describe()  #8 rows × 94 columns(id  feat_1 ... feat_93)otto_data.shape

train数据集一共61878行95列(包括上述特征和target),94个非字符型特征的简单描述统计结果如上图所示。

由于target是字符型变量,我们画图展示,代码如下:

import seaborn as sns
sns.countplot(otto_data["target"])
plt.show()

target一共9个类别。由于是字符型,定义一个函数将target的类别标签转为index表示,方便后面计算交叉熵,代码如下:

def target2idx(targets):target_idx = []target_labels = ['Class_1', 'Class_2', 'Class_3', 'Class_4', 'Class_5', 'Class_6', 'Class_7', 'Class_8', 'Class_9','Class_10']for target in targets:target_idx.append(target_labels.index(target))return target_idx

3 构建模型

3.1 读取数据

import numpy as np
import pandas as pd
from torch.utils.data import Dataset, DataLoader
import torch
import torch.optim as optim#1.读取数据
class OttoDataset(Dataset):def __init__(self,filepath):data = pd.read_csv(filepath)labels = data['target']self.len = data.shape[0]self.X_data = torch.tensor(np.array(data)[:,1:-1].astype(float))self.y_data = target2idx(labels)def __getitem__(self, index):return self.X_data[index], self.y_data[index]def __len__(self):return self.lenotto_dataset1 = OttoDataset('./otto/train.csv')
otto_dataset2 = OttoDataset('./otto/testn.csv')
train_loader = DataLoader(dataset=otto_dataset1, batch_size=64, shuffle=True, num_workers=2)
test_loader = DataLoader(dataset=otto_dataset2, batch_size=64, shuffle=False, num_workers=2)

3.2 构建模型

#2.构建模型
class OttoNet(torch.nn.Module):def __init__(self):super(OttoNet, self).__init__()self.linear1 = torch.nn.Linear(93, 64)self.linear2 = torch.nn.Linear(64, 32)self.linear3 = torch.nn.Linear(32, 16)self.linear4 = torch.nn.Linear(16, 9)self.relu = torch.nn.ReLU()self.dropout = torch.nn.Dropout(p=0.1)self.softmax = torch.nn.Softmax(dim=1)def forward(self, x):x = x.view(-1,93)x = self.relu(self.linear1(x))x = self.relu(self.linear2(x))x = self.dropout(x)x = self.relu(self.linear3(x))x = self.linear4(x)x = self.softmax(x)return xottomodel = OttoNet()
ottomodel

输出:

OttoNet((linear1): Linear(in_features=93, out_features=64, bias=True)(linear2): Linear(in_features=64, out_features=32, bias=True)(linear3): Linear(in_features=32, out_features=16, bias=True)(linear4): Linear(in_features=16, out_features=9, bias=True)(relu): ReLU()(dropout): Dropout(p=0.1, inplace=False)(softmax): Softmax(dim=1)
)

3.3 构造loss和优化器

#3.loss和优化器
criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(ottomodel.parameters(), lr=0.01, momentum=0.56)

3.4 训练模型

if __name__ == '__main__':for epoch in range(10):running_loss = 0.0for batch, data in enumerate(train_loader):inputs, target = dataoptimizer.zero_grad()outputs = ottomodel(inputs.float())loss = criterion(outputs, target)loss.backward()optimizer.step()running_loss += loss.item()if batch % 500 == 499:print('[%d, %5d] loss: %.3f' % (epoch+1, batch+1, running_loss/300))running_loss = 0.0

输出:

[1,   500] loss: 3.591
[2,   500] loss: 3.011
[3,   500] loss: 2.957
[4,   500] loss: 2.940
[5,   500] loss: 2.902
[6,   500] loss: 2.881
[7,   500] loss: 2.873
[8,   500] loss: 2.800
[9,   500] loss: 2.789
[10,   500] loss: 2.779

3.5 预测

with torch.no_grad():output = []for data in test_loader:inputs,labels = dataoutputs = torch.max(ottomodel(inputs.float()),1)[1]output.extend(outputs.numpy().tolist())

保存结果,并提交至kaggle。

submission = pd.read_csv('./otto/sampleSubmission.csv')#(144368, 10)
submission['target'] = output
submission.to_csv('./otto/submission_result1.csv', index=False)

提交失败,数据的格式不对,查看原因中,碰到相同问题的小伙伴可以告诉我,感谢。

说明:记录学习笔记,如果错误欢迎指正!写文章不易,转载请联系我。

这篇关于PyTorch深度学习实践概论笔记9练习-​使用kaggle的Otto数据集做多分类​的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/404837

相关文章

PHP轻松处理千万行数据的方法详解

《PHP轻松处理千万行数据的方法详解》说到处理大数据集,PHP通常不是第一个想到的语言,但如果你曾经需要处理数百万行数据而不让服务器崩溃或内存耗尽,你就会知道PHP用对了工具有多强大,下面小编就... 目录问题的本质php 中的数据流处理:为什么必不可少生成器:内存高效的迭代方式流量控制:避免系统过载一次性

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。

防止Linux rm命令误操作的多场景防护方案与实践

《防止Linuxrm命令误操作的多场景防护方案与实践》在Linux系统中,rm命令是删除文件和目录的高效工具,但一旦误操作,如执行rm-rf/或rm-rf/*,极易导致系统数据灾难,本文针对不同场景... 目录引言理解 rm 命令及误操作风险rm 命令基础常见误操作案例防护方案使用 rm编程 别名及安全删除

Java使用Javassist动态生成HelloWorld类

《Java使用Javassist动态生成HelloWorld类》Javassist是一个非常强大的字节码操作和定义库,它允许开发者在运行时创建新的类或者修改现有的类,本文将简单介绍如何使用Javass... 目录1. Javassist简介2. 环境准备3. 动态生成HelloWorld类3.1 创建CtC

使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解

《使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解》本文详细介绍了如何使用Python通过ncmdump工具批量将.ncm音频转换为.mp3的步骤,包括安装、配置ffmpeg环... 目录1. 前言2. 安装 ncmdump3. 实现 .ncm 转 .mp34. 执行过程5. 执行结

Java使用jar命令配置服务器端口的完整指南

《Java使用jar命令配置服务器端口的完整指南》本文将详细介绍如何使用java-jar命令启动应用,并重点讲解如何配置服务器端口,同时提供一个实用的Web工具来简化这一过程,希望对大家有所帮助... 目录1. Java Jar文件简介1.1 什么是Jar文件1.2 创建可执行Jar文件2. 使用java

C++统计函数执行时间的最佳实践

《C++统计函数执行时间的最佳实践》在软件开发过程中,性能分析是优化程序的重要环节,了解函数的执行时间分布对于识别性能瓶颈至关重要,本文将分享一个C++函数执行时间统计工具,希望对大家有所帮助... 目录前言工具特性核心设计1. 数据结构设计2. 单例模式管理器3. RAII自动计时使用方法基本用法高级用法