CIFAR10彩色图片识别

P2:CIFAR10彩色图片识别 更具体地说,损失函数loss是由模型的所有权重w经过一系列运算得到的,若某个w的requires_grads为True,则w的所有上层参数(后面层的权重w)的.grad_fn属性中就保存了对应的运算,然后在使用。为全连接层,可以起到特征提取器的作用,最后一层的全连接层也可以认为是输出层,传入参数为输入特征数和输出特征数(输入特征数由特征提取网络计算得到,如果不会计算可以直接运行网络,报错中会提示输入特征数的大小。函数的作用是执行一次优化步骤,通过梯度下降法来更新参数的值。默认值为 1,表示不进行分组卷积。 阅读详情

1.导入数据

原代码在苹果系统里依旧会报错,不能直接下载,这里我依旧采用的是手动下载以后,通过代码导入数据。

import os
import numpy as np
import torch
import torchvision.transforms as transforms
from torch.utils.data import Dataset, DataLoader
import pickle
import matplotlib.pyplot as plt
import torch.nn as nn
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

class CIFAR10Manual(Dataset):
    def __init__(self, root, train=True, transform=None):
        """
        手动加载 CIFAR-10 数据集
        :param root: 数据集文件路径
        :param train: 是否加载训练集(True)还是测试集(False)
        :param transform: 可选的图像预处理方法
        """
        self.root = root
        self.train = train
        self.transform = transform

        # 训练数据文件列表
        if self.train:
            self.data_files = ['data_batch_1', 'data_batch_2', 'data_batch_3', 'data_batch_4', 'data_batch_5']
        else:
            self.data_files = ['test_batch']

        # 加载数据和标签
        self.images = []
        self.labels = []
        for file_name in self.data_files:
            file_path = os.path.join(self.root, file_name)
            with open(file_path, 'rb') as f:
                data_dict = pickle.load(f, encoding='bytes')
                self.images.append(data_dict[b'data'])  # 获取图片数据
                self.labels.extend(data_dict[b'labels'])  # 获取标签
        # 将所有图片数据合并为一个大的数组
        self.images = np.concatenate(self.images)
        self.labels = np.array(self.labels)

        # 将图片数据的形状转换为 [N, 3, 32, 32]
        self.images = self.images.reshape(-1, 3, 32, 32)

        # 转换为 PyTorch tensor
        self.images = torch.tensor(self.images, dtype=torch.float32)
        self.labels = torch.tensor(self.labels, dtype=torch.long)

    def __len__(self):
        return len(self.labels)

    def __getitem__(self, idx):
        # 获取图片和标签
        image = self.images[idx]
        label = self.labels[idx]

        # 如果定义了transform,则对图片进行处理
        if self.transform:
            image = self.transform(image)

        return image, label

# 数据预处理:将数据转换为 tensor 并进行标准化(归一化)
transform = transforms.Compose([
    transforms.ToPILImage(),  # 将 Tensor 转为 PIL Image
    transforms.ToTensor(),  # 然后转换为 Tensor
    # 使用适合 CIFAR-10 的归一化
    transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),  # 归一化
    transforms.ColorJitter(brightness=0.2, contrast=0.2)  # 增加亮度和对比度
])

这里定义了一个类来进行手动导入数据,其中的方法包括导入路径,训练集测试集,以及转换,对数据进行处理转换格式,设置图片以及标签,这里归一化以后又设置了对比度,让彩色图片更清晰一点。

2.加载数据以及显示图像

train_ds = CIFAR10Manual(root='/Users/qiang/PycharmProjects/PythonProject2/cifar-10-batches-py', train=True,
                         transform=transform)
test_ds = CIFAR10Manual(root='/Users/qiang/PycharmProjects/PythonProject2/cifar-10-batches-py', train=False,
                        transform=transform)

# 创建数据加载器
train_dl = DataLoader(train_ds, batch_size=32, shuffle=True)
test_dl = DataLoader(test_ds, batch_size=32, shuffle=False)

# 获取一个批次的数据
imgs, labels = next(iter(train_dl))

# 创建绘图
plt.figure(figsize=(20, 5))

# 循环显示前 20 张图片
for i, img in enumerate(imgs[:20]):
    # 将图像数据从 Tensor 转换为 numpy 数组,并调整轴顺序
    np_img = img.numpy().transpose((1, 2, 0))  # (C, H, W) 转为 (H, W, C)

    # 反归一化:将 [-1, 1] 转回 [0, 1]
    np_img = (np_img + 1) / 2

    # 打印图像的数据范围,帮助调试
    print(np_img.min(), np_img.max())  # 输出图像数据的最小值和最大值

    # 对数据进行裁剪,确保数据范围在 [0, 1] 之间
    np_img = np.clip(np_img, 0, 1)

    # 显示第 i+1 张图像
    plt.subplot(2, 10, i + 1)
    plt.imshow(np_img)  # 直接显示图像
    plt.axis('off')  # 关闭坐标轴

# 显示图像
plt.show()

3.卷积层设置前向传播

num_classes = 10  # 图片的类别数

class Model(nn.Module):
    def __init__(self):
        super().__init__()
        # 特征提取网络
        self.conv1 = nn.Conv2d(3, 64, kernel_size=3)  # 第一层卷积,卷积核大小为3*3
        self.pool1 = nn.MaxPool2d(kernel_size=2)  # 设置池化层,池化核大小为2*2
        self.conv2 = nn.Conv2d(64, 64, kernel_size=3)  # 第二层卷积,卷积核大小为3*3
        self.pool2 = nn.MaxPool2d(kernel_size=2)
        self.conv3 = nn.Conv2d(64, 128, kernel_size=3)  # 第二层卷积,卷积核大小为3*3
        self.pool3 = nn.MaxPool2d(kernel_size=2)

        # 分类网络
        self.fc1 = nn.Linear(512, 256)
        self.fc2 = nn.Linear(256, num_classes)

    # 前向传播
    def forward(self, x):
        x = self.pool1(F.relu(self.conv1(x)))
        x = self.pool2(F.relu(self.conv2(x)))
        x = self.pool3(F.relu(self.conv3(x)))

        x = torch.flatten(x, start_dim=1)

        x = F.relu(self.fc1(x))
        x = self.fc2(x)

        return x

from torchinfo import summary
    # 将模型转移到GPU中(我们模型运行均在GPU中进行)
model = Model().to(device)

summary(model)
loss_fn    = nn.CrossEntropyLoss() # 创建损失函数
learn_rate = 1e-2 # 学习率
opt        = torch.optim.SGD(model.parameters(),lr=learn_rate)

这块代码和手写识别数字基本没有区别,多建了一层卷积池化层。

4.训练测试循环

def train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)  # 训练集的大小,一共60000张图片
    num_batches = len(dataloader)  # 批次数目,1875(60000/32)

    train_loss, train_acc = 0, 0  # 初始化训练损失和正确率

    for X, y in dataloader:  # 获取图片及其标签
        X, y = X.to(device), y.to(device)

        # 计算预测误差
        pred = model(X)  # 网络输出
        loss = loss_fn(pred, y)  # 计算网络输出和真实值之间的差距,targets为真实值,计算二者差值即为损失

        # 反向传播
        optimizer.zero_grad()  # grad属性归零
        loss.backward()  # 反向传播
        optimizer.step()  # 每一步自动更新

        # 记录acc与loss
        train_acc += (pred.argmax(1) == y).type(torch.float).sum().item()
        train_loss += loss.item()

    train_acc /= size
    train_loss /= num_batches

    return train_acc, train_loss

def test(dataloader, model, loss_fn):
    size = len(dataloader.dataset)  # 测试集的大小,一共10000张图片
    num_batches = len(dataloader)  # 批次数目,313(10000/32=312.5,向上取整)
    test_loss, test_acc = 0, 0

    # 当不进行训练时,停止梯度更新,节省计算内存消耗
    with torch.no_grad():
        for imgs, target in dataloader:
            imgs, target = imgs.to(device), target.to(device)

            # 计算loss
            target_pred = model(imgs)
            loss = loss_fn(target_pred, target)

            test_loss += loss.item()
            test_acc += (target_pred.argmax(1) == target).type(torch.float).sum().item()

    test_acc /= size
    test_loss /= num_batches

    return test_acc, test_loss

5.正式训练以及图像绘制

epochs = 10
train_loss = []
train_acc = []
test_loss = []
test_acc = []

for epoch in range(epochs):
    model.train()
    epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, opt)

    model.eval()
    epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)

    train_acc.append(epoch_train_acc)
    train_loss.append(epoch_train_loss)
    test_acc.append(epoch_test_acc)
    test_loss.append(epoch_test_loss)

    template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%,Test_loss:{:.3f}')
    print(template.format(epoch + 1, epoch_train_acc * 100, epoch_train_loss, epoch_test_acc * 100, epoch_test_loss))
print('Done')
import matplotlib.pyplot as plt
#隐藏警告
import warnings
warnings.filterwarnings("ignore")               #忽略警告信息
plt.rcParams['font.sans-serif']    = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False      # 用来正常显示负号
plt.rcParams['figure.dpi']         = 100        #分辨率

epochs_range = range(epochs)

plt.figure(figsize=(12, 3))
plt.subplot(1, 2, 1)

plt.plot(epochs_range, train_acc, label='Training Accuracy')
plt.plot(epochs_range, test_acc, label='Test Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, train_loss, label='Training Loss')
plt.plot(epochs_range, test_loss, label='Test Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

这里训练次数设置的10次,代码第一次运行时建议设置一次,运行的快一点,确定代码没有错误再换成10或者更多次

6.学习遇到的问题(mac系统):

导入数据时依旧需要手动下载然后导入,不能直接下载,需要用更复杂的代码手动导入。(见第一章)

P2CIFAR10彩色图片识别 self.fc1 = nn.Linear(512, 256) ”中的512如何得出在深度学习中,特别是在构建卷积神经网络(CNN)时,确定全连接层(如 nn.Linear)的输入特征数卷积层的输出计算假设我们有一个卷积层,其输出将被展平并用作全连接层的输入。卷积层的输出尺寸取决于以下因素:输入尺寸:原始图像或前一层的输出尺寸。卷积核尺寸:卷积核(或滤波器)的大小。步长(Stride):卷积核移动的步长。填充(Padding):在输入边缘添加的额外零的数量。示例计算。 阅读详情

相关推荐

Pytorch入门|CIFAR10彩色图片识别

环境检查:确保安装了适当的深度学习框架(如TensorFlow或PyTorch),并确认GPU驱动和CUDA版本兼容。内存管理:设置GPU的内存使用限制,防止过度占用导致其他任务失败。

m0_72010245的博客 809

新手小白深度学习第P2周:CIFAR10彩色图片识别

深度学习:CIFA10彩色图片识别

shentianyang0802的博客 2135

基于deepseek+dify+达梦实现自然语言查询数据库

自然语言查询数据库信息

weixin_43974943的博客 1593

week2: 基于pytorch的CIFAR10彩色图片识别实验

CNN 的核心是卷积层和池化层,通过局部感知和参数共享来提取图像特征。大致了解到卷积层利用卷积操作提取特征,包括滤波器的定义、特征图的计算等。CNN 的核心是卷积层和池化层,通过局部感知和参数共享来提取图像特征。大致了解到卷积层利用卷积操作提取特征,包括滤波器的定义、特征图的计算等。卷积池化的推导:卷积操作是将滤波器与输入图像进行卷积运算,通过滑动窗口计算特征图。池化操作是将特征图进行降采样,常用的池化方式包括最大池化和平均池化。实验涉及到数据集的准备、模型构建、训练、评估和结果分析等多个步骤。

weixin_43690449的博客 1129

用AI免费制作30分钟电影:完整工作流与实操解析

AI视频生成技术正大幅降低影视创作门槛,但真正制作一部完整电影并非一键生成,而是涉及剧本、分镜、画面、配音、剪辑的复杂流水线。理解其基本原理,是将文本转化为连续视觉叙事的关键。对于创作者而言,掌握角色一致性控制、素材批量管理、免费额度合理分配等技术价值,能有效避免生成结果崩坏与资源浪费。该能力可广泛应用于短视频创作、独立电影预演、教学演示等场景。本文以30分钟AI电影制作为例,拆解从工具选择到成片输出的全流程,重点分析免费方案下的时间与积分成本,以及最容易翻车的环节,并给出基于实践验证的排查与优化策略。

weixin_29056865的博客 330

CST仿真微带贴片天线学习笔记

谐振频率为3.48GHz,基板采用Rogers RT5880板材,介电常数2.2,损耗角正切0.0009,厚度1.57mm,馈电方式为同轴馈电。

qq_36521926的博客 9433

P2周:CIFAR10彩色图片识别

🍨 本文为[🔗365天深度学习训练营](https://mp.weixin.qq.com/s/rnFa-IeY93EpjVu0yzzjkw) 中的学习记录博客 🍖 原作者:[K同学啊](https://mtyjkh.blog.youkuaiyun.com/)

2401_84957754的博客 1667

使用MATLAB/Simulink搭建一个简化的无人机螺旋桨气动特性模型,并通过仿真验证其基本功能

螺旋桨概述特点:螺旋桨通过旋转产生推力,推动无人机前进或上升。关键参数直径(D):影响推力和功率消耗。螺距(P):定义了螺旋桨每转一圈理论上前进的距离。效率(η):衡量螺旋桨将机械能转化为推力的有效性。应用场景:航拍摄影、农业监测、物流配送等。仿真目标搭建一个简化的无人机螺旋桨气动特性模型,涵盖从电机输入到螺旋桨输出推力的过程。分析不同条件下的系统响应特性(如推力、功率消耗),并探讨优化螺旋桨设计的方法。定义螺旋桨的一些基本物理参数,如直径、螺距、推力系数、功率系数等。使用Constant。

xiaoheshang_123的博客 428

p2 CIFAR10彩色图片识别

p1Pytorch实现mnist手写数字识别链接👇jupyter中报错:Kernel RestartingThe kernel for......appears to have died. It will restart automatically.

qq_42102725的博客 814

Android P车机添加屏幕多指全局自定义手势操作

参照原生状态栏全局下拉手势拦截,实现屏幕全局多指手势响应操作,并对手势进行转换为KeyEvent,以便项目自定义手势行为或应用拦截手势行为。

shusuanly的博客 1252

13、多实例任务(multi instance)

多实例任务,是指一个类型的任务需要循环执行多次,包括串行多实例任务和并行多实例任务。

leyoliu的博客 3203

第P2周学习打卡:CIFAR10彩色图片识别

在深度学习领域,CIFAR10 是一个经典的图像分类数据集。本文结合 PyTorch 框架,从数据加载、模型搭建到训练及结果可视化,构建了一个简单的 CNN 网络用于 CIFAR10 彩色图片识别。通过该项目,可以深入理解图像分类任务中模型的构建及训练流程。通过本次 CIFAR10 彩色图像分类任务:学习了如何用 PyTorch 加载和预处理数据。掌握了 CNN 网络构建及模型前向传播机制。理解了训练循环、损失函数、优化器的作用。学会了如何用 Matplotlib 绘制训练过程曲线。

m0_45033896的博客 807

【Coppeliasim|轨迹规划(三)】机械臂逆解

文章目录一些设置导航点设置添加连接用于碰撞的设置代码实现终端输出 一些设置 导航点设置 关于如何添加设置 dummy 的细节建议参考官方手册,这里不再赘述。 添加连接用于碰撞的设置 按照序号点击(一个是机械臂,一个是所有的物体除了机械臂): 代码实现 getMatrixShiftedAlongZ=function(matrix,localZShift) local m={} for i=1,12,1 do m[i]=matrix[i] end

【人工智障 | 计算鸡视觉 | 机器孩】 1万+

深度学习日志——第P2周:CIFAR10彩色图片识别

深度学习中卷积神经网络的实际运用:pytorch实现多通道RGB的CIFAR10彩色图片识别

2401_83939329的博客 884

环境配置与基础教程:当前大厂主流套路:使用 MLflow 全链路管理 YOLO 实验参数、指标与模型版本

YOLO26与MLflow结合实现高效实验管理 YOLO26通过移除DFL模块和实现无NMS端到端推理,在CPU推理速度上提升43%,同时简化了模型导出流程。MLflow 3.10/3.11版本新增多工作区支持、成本追踪和安全序列化等功能,为机器学习实验提供全生命周期管理。两者结合可解决传统"截图+Excel"式实验管理的痛点,实现参数追踪、指标对比和模型版本控制的自动化。 关键优势: YOLO26架构优化带来显著性能提升 MLflow提供实验到生产的全链路管理 原生集成简化了计算机视觉

ZXSXJ的博客 191

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

训练营P2周:Pytorch实现CIFAR10 彩色图片识别

这是训练营第二周的内容,其中大量的内容可能与第一周是相似的,我建议零基础的小伙伴先去看看Mnist那篇文章浅浅的理解一下,再来阅读这篇。这一篇文章我将会重点集中在上一次没有涉及,或者有变动的部分。相比于上次的实验,这次的模型准确度只有50%左右,其可能的原因是图片复杂,模型很难学习到规律。比如说我们细看飞机这个类别:其中各种飞机差异较大,有的包含机翼,有的只有机头。对于人类来说,我们有大量的经验可以判断,这些都是飞机,但对于CNN来说,其很难学习到相应的规律。

2504_92784755的博客 754

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

第P2周:CIFAR10彩色图片识别

Pytorch入门实战《第P2周:CIFAR10彩色图片识别》

努力学习的大小宝 1269

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

P2:使用pytorch实现CIFAR10彩色图片识别

今天的pytorch的基本用法有:1.torch.utils.data.DataLoader()加载数据2.构建简单的CNN网络对于一般的CNN网络来说,都是由特征提取网络和分类网络构成,其中特征提取网络用于提取图片的特征,分类网络用于将图片进行分类。torch.nn.Conv2d()详解关键参数说明:● in_channels ( int ) – 输入图像中的通道数● out_channels ( int ) – 卷积产生的通道数。

apwpasy的博客 513

深度学习笔记02-Pytorh实现CIFAR10彩色图片识别

本文通过建立卷积神经网络实现CIFAR10数据集的分类

bcxbdzh的博客 1012

深度学习pytorch实战第P2周:CIFAR10彩色图片识别

深度学习第二例,CIFAR10彩色图片识别,全文1W+字,带你领略卷积神经网络之美,让你真正跑通你的第一个pytorch案例

m0_55259388的博客 2446

P2打卡—pytorch实现CIFAR10彩色图片识别

【代码】P2打卡—pytorch实现CIFAR10彩色图片识别。

qq_52649952的博客 888
上一篇: pytorch手写识别学习
下一篇: pytorch天气识别学习
sunboon
博客等级 码龄20年 81粉丝 9原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值