Pytorch Fashion_MNIST直接离线加载二进制文件到pytorch

说明:Fashion_MNIST直接离线加载二进制文件到pytorch


'''
将4个gz直接加载到pytoch用来训练t10k-images-idx3-ubyte.gzt10k-labels-idx1-ubyte.gztrain-images-idx3-ubyte.gztrain-labels-idx1-ubyte.gz
'''import os
import numpy as np
import gzip
import matplotlib.pyplot as pltimport torch
import torch.utils.data as Data
from torchvision import datasets, transforms
from torch.autograd import Variableimport timedataPath = 'E:/fashion_binary_gz/'# device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")batch_size = 4def load_data(data_folder, data_name, label_name):"""data_folder: 文件目录data_name: 数据文件名label_name:标签数据文件名"""with gzip.open(os.path.join(data_folder,label_name), 'rb') as lbpath: # rb表示的是读取二进制数据y_train = np.frombuffer(lbpath.read(), np.uint8, offset=8)with gzip.open(os.path.join(data_folder,data_name), 'rb') as imgpath:x_train = np.frombuffer(imgpath.read(), np.uint8, offset=16).reshape(len(y_train), 28, 28)return (x_train, y_train)class DealDataset(Data.Dataset):"""读取数据、初始化数据"""def __init__(self, folder, data_name, label_name,transform=None):(train_set, train_labels) = load_data(folder, data_name, label_name) # 其实也可以直接使用torch.load(),读取之后的结果为torch.Tensor形式self.train_set = train_setself.train_labels = train_labelsself.transform = transformdef __getitem__(self, index):img, target = self.train_set[index], int(self.train_labels[index])if self.transform is not None:img = self.transform(img)return img, targetdef __len__(self):return len(self.train_set)# 实例化这个类,然后我们就得到了Dataset类型的数据,记下来就将这个类传给DataLoader,就可以了。
trainDataset = DealDataset(dataPath,"train-images-idx3-ubyte.gz","train-labels-idx1-ubyte.gz",transform=transforms.ToTensor())testDataset = DealDataset(dataPath,"t10k-images-idx3-ubyte.gz","t10k-labels-idx1-ubyte.gz",transform=transforms.ToTensor())# 训练数据和测试数据的装载
train_loader = Data.DataLoader(dataset=trainDataset,batch_size=100, # 一个批次可以认为是一个包,每个包中含有100张图片shuffle=False,
)test_loader = Data.DataLoader(dataset=testDataset,batch_size=100,shuffle=False,
)if __name__ == '__main__':# 这里trainDataset包含:train_labels, train_set等属性;  数据类型均为ndarrayprint(f'trainDataset.train_labels.shape:{trainDataset.train_labels.shape}\n')print(f'trainDataset.train_set.shape:{trainDataset.train_set.shape}\n')# 这里train_loader包含:batch_size、dataset等属性,数据类型分别为int,DealDataset# dataset中又包含train_labels, train_set等属性;  数据类型均为ndarrayprint(f'train_loader.batch_size: {train_loader.batch_size}\n')print(f'train_loader.dataset.train_labels.shape: {train_loader.dataset.train_labels.shape}\n')print(f'train_loader.dataset.train_set.shape: {train_loader.dataset.train_set.shape}\n')dataiter = iter(train_loader)images, labels = dataiter.next()images = images.numpy()classes = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat','Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']# plot the images in the batch, along with the corresponding labelsfig = plt.figure(figsize=(25, 4))for idx in np.arange(batch_size):ax = fig.add_subplot(2, batch_size/2, idx+1, xticks=[], yticks=[])# ax.imshow(np.squeeze(images[idx]), cmap='gray')ax.imshow(np.squeeze(images[idx]), cmap='gray')ax.set_title(classes[labels[idx]])plt.show()

 

运行结果

显示图像

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/350196.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

jQuery选择器种类整理

选择器概念 jQuery选择器是通过标签、属性或者内容对HTML内容进行选择,选择器运行对HTML元素组或者单个元素进行操作。 jQuery选择器使用$符号,等同于jquery,例如: $(“li”) jquery(“li”) 同样等同于javascript中的&#xff1…

jee过滤器应用场景_将涡轮增压器添加到JEE Apps

jee过滤器应用场景我扮演的关键角色之一是在本地社区中传播Akka。 作为讨论的一部分,人们通常会想到的问题/疑问是Akka如何针对编写良好的Java / JEE应用程序提供更好的可伸缩性和并发性。 由于底层硬件/ JVM保持不变,因此参与者模型如何比传统的JEE应用…

mysql 列 随机数_mysql mmp 某字段插入随机数!(说不定那天就忘记了,存下来再说)...

UPDATE 表名 SET 字段名ceiling(rand()*500000500000) WHERE (条件);原文链接:http://blog.csdn.net/bobay/article/details/24797525MMP 上面的只能更新一条UPDATE 表名 SET 字段名cast(rand(checksum(newid()))*(24)1 as int) WHERE (条件);上面的就是每条都更新的…

适用于Java开发人员的Elasticsearch:Elasticsearch生态系统

本文是我们学院课程的一部分,该课程的标题为Java开发人员的Elasticsearch教程 。 在本课程中,我们提供了一系列教程,以便您可以开发自己的基于Elasticsearch的应用程序。 我们涵盖了从安装和操作到Java API集成和报告的广泛主题。 通过我们简…

matplotlib markers的类型

https://matplotlib.org/api/markers_api.html matplotlib markers 所有可能的markers定义如下: marker symbol description "." point "," pixel "o" circle "v" triangle_down "^" triangle_up &…

android实时声音信号波形_Android输出正弦波音频信号(左右声道对称)-阿里云开发者社区...

转载请说明出处!作者:kqw攻城狮出处:个人站 | CSDN需求:左右声道分别输出不同的音频数据,波形要是一个正弦波,左右声道还要对称!对硬件不是很了解,说是要通过音波避障。效果图之前已…

matplotlib color可选

matplotlib color matplotlib中color可用的颜色: cnames { aliceblue: #F0F8FF, antiquewhite: #FAEBD7, aqua: #00FFFF, aquamarine: #7FFFD4, azure: #F0FFFF, beige: #F5F5…

python之scrapy爬取jd和qq招聘信息

1、settings.py文件 # -*- coding: utf-8 -*-# Scrapy settings for jd project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://doc.scrapy.org…

opencl 加速 c语言程序_Win10应用获得面向OpenCL和OpenGL的兼容层

今年早些时候,微软宣布正在努力在Windows 10的Direct3D 12(D3D12)中启用对OpenCL和OpenGL映射层的支持。为了启用映射层,解决设备上没有OpenCL和OpenGL硬件驱动时的兼容性问题,公司目前已经在微软商店中发布了兼容性包。该兼容性包的标题为 &…

matplotlib plt.subplot

matplotlib plt.subplot 用于在一个Figure对象里画多个子图(Axes)。 其调用格式:subplot(numRows, numCols, plotNum),即(行、列、序号)。 图表的整个绘图区域被分成numRows行和numCols列,plotNum参数指定创建的Axes…

javaee和javaee_JavaEE概念简介

javaee和javaee这篇文章旨在阐明J2EE范例中使用的首字母缩写词和概念。 J2EE代表Java to Platform,Entreprise Edition。 它使创建模块化Java应用程序得以部署在应用程序服务器上。 它依赖于Java SE,Java SE是一组Java库的核心,所有Java应用程…

卷boot仅剩余XX空间

参见: https://blog.csdn.net/hnzcdy/article/details/52381844 转载于:https://www.cnblogs.com/lxc1910/p/11102528.html

python多分支结构实例_JS优化多分支结构(经典)

多分支结构的优化有很多好处:既方便代码维护,又可以提升代码执行效率。例如,设计有多个条件,只有当多个条件都成立时,才允许执行特定任务。示例1遵循简单的设计思路,使用多重分支逐个检测这些条件。if (a) …

matplotlib plt.plot

实例1 import matplotlib.pyplot as plta [1, 2, 3, 4] # y 是 a的值,x是各个元素的索引 b [5, 6, 7, 8]plt.figure(demon plot) plt.plot(a, b, r--, label aa) plt.xlabel(this is x) plt.ylabel(this is y) plt.title(this is a demo) plt.legend(locupper l…

使用UAA OAuth2授权服务器–客户端和资源

在上一篇文章中,我介绍了如何使用Cloud Foundry UAA项目启动OAuth2授权服务器,以及如何使用OAuth2授权代码流程中涉及的一些参与者来填充它。 我已经在Digital Ocean网站上找到了这篇文章,在描述OAuth2授权代码流方面做得非常好,…

二分查找思想

二分查找 二分查找思想应用于对有序的数组进行查找操作。 时间复杂度 二分查找也称为折半查找,每次都能将查找区间减半,这种折半特性算法时间复杂度为O(logn)。 mid计算 有两种计算中值mid的方式: m(lh)/2ml(h-l)/2lh可能出现加法溢出&#x…

ad20如何导入库_脱水防锈油如何使用才正确?

导Lead语根据调查了解,很多厂家在使用脱水防锈油的办法不正确而导致防锈效果失效或不明显。那么脱水防锈油应该如何使用才正确呢?中阳润滑油为大家简单讲述如下。脱水防锈油脱水防锈油是由矿物油及脱水、防锈抗氧化等多种添加剂配制而成,既可…

matplotlib  plt.lengend

参考文档 https://www.cnblogs.com/lfri/p/12248629.html 官方文档 https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html matplotlib plt.lengend 作用:用于给图像加图例。 1、语法参数如下: matplotlib.pyplot.legend(*args, **kwargs) 2、…

Python进阶(上下文管理器与with语句)

/*上下文管理器必须有__enter__和__exit__方法*/ class MyResource:def __enter__(self):print(链接资源)return self/*__exit__返回True表示异常只会在__exit__中被捕获,不会继续传递到with语句的之外的except中,如果返回false,则会把异常也…

matplotlib  plt.scatter

https://www.cnblogs.com/lfri/p/12248629.html matplotlib plt.scatter 作用:画散点图 plt.scatter() 参数如下: x,y X和Y是长度相同的数组 s size,点的大小,标量或与数据长度相同的数组 c color,点的颜色,标量或与数据长…