「卷积神经网络」实战 Kaggle 竞赛:树叶分类

简介: 「卷积神经网络」实战 Kaggle 竞赛:树叶分类

导入必要的库。
%matplotlib inline
import random
import torch
from torch import nn
from torch.nn import functional as F
from torchvision import datasets, transforms
import pandas as pd
import matplotlib.pyplot as plt
from d2l import torch as d2l
from PIL import Image
读取训练数据与测试数据,并转化为 NumPy 格式,方便后续实现自定义 Dataset。
train_data = pd.read_csv('./data/train.csv')
test_data = pd.read_csv('./data/test.csv')

train_images = train_data.iloc[:, 0].values
pred_images = test_data.iloc[:, 0].values
train_labels = pd.get_dummies(train_data.iloc[:, 1]).values.argmax(1)
train_labels_header = pd.get_dummies(train_data.iloc[:, 1]).columns.values

n_train = train_images.shape[0]
继承 torch.utils.Dataset 类,自定义树叶分类数据集。
class CLASSIFY_LEAVES(torch.utils.data.Dataset):

def __init__(self, root, images, labels, transform):
    super(CLASSIFY_LEAVES, self).__init__()
    self.root = root
    self.images = images
    if labels is None:
        self.labels = None
    else:
        self.labels = labels
    self.transform = transform
def __getitem__(self, index):
    image_path = self.root + self.images[index]
    image = Image.open(image_path)
    image = self.transform(image)
    if self.labels is None:
        return image
    label = torch.tensor(self.labels[index])
    return image, label
def __len__(self):
    return self.images.shape[0]

def load_data(images, labels, batch_size, train):

aug = []
if (train):
    aug = [transforms.RandomHorizontalFlip(),
           transforms.RandomVerticalFlip(),
           transforms.ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5),
           transforms.ToTensor()]
else:
    aug = [transforms.ToTensor()]
transform = transforms.Compose(aug)
dataset = CLASSIFY_LEAVES('./data/', images, labels, transform=transform)
return torch.utils.data.DataLoader(dataset=dataset, batch_size=batch_size, num_workers=8, shuffle=train)

使用 ResNet-18 网络,并初始化。
net = get_resnet18()

def init_weights(m):

if type(m) == nn.Linear or type(m) == nn.Conv2d:
    nn.init.xavier_uniform_(m.weight)

net.apply(init_weights)
定义训练函数,使用多 GPU 训练。
def accuracy(y_hat, y):

return (y_hat.argmax(1) == y).sum()

def train(net, train_iter, test_iter, num_epochs, lr, devices):

net = nn.DataParallel(net, device_ids = devices).to(devices[0])
optimizer = torch.optim.Adam(net.parameters(), lr=lr)
loss = nn.CrossEntropyLoss()
animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs], legend=['train acc', 'test acc'])
for epoch in range(num_epochs):
    train_loss_tot, train_acc_tot, train_tot = 0, 0, 0
    test_acc_tot, test_tot = 0, 0
    net.train()
    for X, y in train_iter:
        optimizer.zero_grad()
        X, y = X.to(devices[0]), y.to(devices[0])
        y_hat = net(X)
        l = loss(y_hat, y)
        l.backward()
        optimizer.step()
        with torch.no_grad():
            train_loss_tot += l * X.shape[0]
            train_acc_tot += accuracy(y_hat, y)
            train_tot += X.shape[0]
    net.eval()
    with torch.no_grad():
        for X, y in test_iter:
            X, y = X.to(devices[0]), y.to(devices[0])
            test_acc_tot += accuracy(net(X), y)
            test_tot += X.shape[0]
    train_loss = train_loss_tot / train_tot
    train_acc = train_acc_tot / train_tot
    test_acc = test_acc_tot / test_tot
    animator.add(epoch + 1, (train_acc.cpu(), test_acc.cpu()))
    torch.save(net.state_dict(), 'resnet18.params')

随机抽取 15000 个训练数据,以及 3000 个测试数据,并初始化迭代器。
train_slices = random.sample(list(range(n_train)), 15000)
test_slices = list(set(range(n_train)) - set(train_slices))

train_iter = load_data(train_images[train_slices], train_labels[train_slices], 512, train=True)
test_iter = load_data(train_images[test_slices], train_labels[test_slices], 512, train=False)
训练。
train(net, train_iter, test_iter, 10, 0.01, [torch.device('cuda:0'),

                                         torch.device('cuda:1')])

预测,并写入 submission.csv。注意推理仍需要在 GPU 上运行。
pred_iter = load_data(pred_images, None, 256, train=False)

def predict(net, pred_iter):

net.to(torch.device('cuda:0'))
net.eval()
prediction = []
for index, X in enumerate(pred_iter):
    X = X.to('cuda:0')
    prediction.extend(train_labels_header[net(X).argmax(1).cpu()])
test_data['label'] = prediction
test_data.to_csv('./data/submission.csv', index=None)

predict(net, pred_iter)

目录
相关文章
|
8月前
|
机器学习/深度学习 PyTorch TensorFlow
卷积神经网络深度解析:从基础原理到实战应用的完整指南
蒋星熠Jaxonic,深度学习探索者。深耕TensorFlow与PyTorch,分享框架对比、性能优化与实战经验,助力技术进阶。
|
8月前
|
监控 Linux 测试技术
C++零拷贝网络编程实战:从理论到生产环境的性能优化之路
🌟 蒋星熠Jaxonic,技术宇宙中的星际旅人。深耕C++与零拷贝网络编程,从sendfile到DPDK,实战优化服务器性能,毫秒级响应、CPU降60%。分享架构思维,共探代码星辰大海!
|
8月前
|
机器学习/深度学习 数据采集 人工智能
深度学习实战指南:从神经网络基础到模型优化的完整攻略
🌟 蒋星熠Jaxonic,AI探索者。深耕深度学习,从神经网络到Transformer,用代码践行智能革命。分享实战经验,助你构建CV、NLP模型,共赴二进制星辰大海。
|
9月前
|
机器学习/深度学习 人工智能 算法
卷积神经网络深度解析:从基础原理到实战应用的完整指南
蒋星熠Jaxonic带你深入卷积神经网络(CNN)核心技术,从生物启发到数学原理,详解ResNet、注意力机制与模型优化,探索视觉智能的演进之路。
768 11
|
8月前
|
机器学习/深度学习 存储 算法
淘宝图片搜索接口开发实战:从 CNN 特征提取到商品匹配(附避坑手册 + 可复用代码)
本文详解淘宝图片搜索接口开发全流程,涵盖CNN特征提取、商品匹配、参数配置及400/429等高频报错解决方案,附合规避坑指南与可复用代码,助你高效实现图像搜商品功能。
|
9月前
|
机器学习/深度学习 传感器 数据采集
【故障识别】基于CNN-SVM卷积神经网络结合支持向量机的数据分类预测研究(Matlab代码实现)
【故障识别】基于CNN-SVM卷积神经网络结合支持向量机的数据分类预测研究(Matlab代码实现)
544 0
|
9月前
|
机器学习/深度学习 传感器 数据采集
基于贝叶斯优化CNN-LSTM混合神经网络预测(Matlab代码实现)
基于贝叶斯优化CNN-LSTM混合神经网络预测(Matlab代码实现)
1275 0
|
11月前
|
机器学习/深度学习 人工智能 PyTorch
零基础入门CNN:聚AI卷积神经网络核心原理与工业级实战指南
卷积神经网络(CNN)通过局部感知和权值共享两大特性,成为计算机视觉的核心技术。本文详解CNN的卷积操作、架构设计、超参数调优及感受野计算,结合代码示例展示其在图像分类、目标检测等领域的应用价值。
588 7
|
10月前
|
机器学习/深度学习 数据采集 TensorFlow
基于CNN-GRU-Attention混合神经网络的负荷预测方法(Python代码实现)
基于CNN-GRU-Attention混合神经网络的负荷预测方法(Python代码实现)
543 0
|
12月前
|
机器学习/深度学习 数据采集 监控
基于CNN卷积神经网络和GEI步态能量提取的步态识别算法matlab仿真,对比不同角度下的步态识别性能
本项目基于CNN卷积神经网络与GEI步态能量提取技术,实现高效步态识别。算法使用不同角度(0°、45°、90°)的步态数据库进行训练与测试,评估模型在多角度下的识别性能。核心流程包括步态图像采集、GEI特征提取、数据预处理及CNN模型训练与评估。通过ReLU等激活函数引入非线性,提升模型表达能力。项目代码兼容Matlab2022a/2024b,提供完整中文注释与操作视频,助力研究与应用开发。