国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

pytorch 把MNIST數據集轉換成圖片和txt的方法

2020-02-23 00:10:16
字體:
來源:轉載
供稿:網友

本文介紹了pytorch 把MNIST數據集轉換成圖片和txt的方法,分享給大家,具體如下:

1.下載Mnist 數據集

import os# third-party libraryimport torchimport torch.nn as nnfrom torch.autograd import Variableimport torch.utils.data as Dataimport torchvisionimport matplotlib.pyplot as plt # torch.manual_seed(1)  # reproducibleDOWNLOAD_MNIST = False # Mnist digits datasetif not(os.path.exists('./mnist/')) or not os.listdir('./mnist/'):  # not mnist dir or mnist is empyt dir  DOWNLOAD_MNIST = True train_data = torchvision.datasets.MNIST(  root='./mnist/',  train=True,                   # this is training data  transform=torchvision.transforms.ToTensor(),  # Converts a PIL.Image or numpy.ndarray to                          # torch.FloatTensor of shape (C x H x W) and normalize in the range [0.0, 1.0]  download=DOWNLOAD_MNIST,)

下載下來的其實可以直接用了,但是我們這邊想把它們轉換成圖片和txt,這樣好看些,為后面用自己的圖片和txt作為準備

2. 保存為圖片和txt

import osfrom skimage import ioimport torchvision.datasets.mnist as mnistimport numpy root = "./mnist/raw/"train_set = (  mnist.read_image_file(os.path.join(root, 'train-images-idx3-ubyte')),  mnist.read_label_file(os.path.join(root, 'train-labels-idx1-ubyte'))) test_set = (  mnist.read_image_file(os.path.join(root,'t10k-images-idx3-ubyte')),  mnist.read_label_file(os.path.join(root,'t10k-labels-idx1-ubyte'))) print("train set:", train_set[0].size())print("test set:", test_set[0].size()) def convert_to_img(train=True):  if(train):    f = open(root + 'train.txt', 'w')    data_path = root + '/train/'    if(not os.path.exists(data_path)):      os.makedirs(data_path)    for i, (img, label) in enumerate(zip(train_set[0], train_set[1])):      img_path = data_path + str(i) + '.jpg'      io.imsave(img_path, img.numpy())      int_label = str(label).replace('tensor(', '')      int_label = int_label.replace(')', '')      f.write(img_path + ' ' + str(int_label) + '/n')    f.close()  else:    f = open(root + 'test.txt', 'w')    data_path = root + '/test/'    if (not os.path.exists(data_path)):      os.makedirs(data_path)    for i, (img, label) in enumerate(zip(test_set[0], test_set[1])):      img_path = data_path + str(i) + '.jpg'      io.imsave(img_path, img.numpy())      int_label = str(label).replace('tensor(', '')      int_label = int_label.replace(')', '')      f.write(img_path + ' ' + str(int_label) + '/n')    f.close() convert_to_img(True)convert_to_img(False)

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林站長站。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 通渭县| 桃江县| 宜章县| 繁昌县| 合作市| 博客| 尖扎县| 秀山| 北碚区| 哈密市| 柯坪县| 临夏市| 抚顺市| 广元市| 东乡县| 乐都县| 巫溪县| 莒南县| 怀来县| 隆林| 武城县| 土默特左旗| 乡城县| 本溪| 麻江县| 大渡口区| 岳普湖县| 宁河县| 龙游县| 龙口市| 石门县| 永吉县| 保定市| 五台县| 邻水| 海盐县| 瓮安县| 牙克石市| 托克逊县| 密山市| 新宾|