MNISTデータセットをCSVファイルに変換してみました
28ピクセル x 28ピクセル=784の列からなる内容が理解できたらと思ったのですが
1列目がラベル2列から785列までが訓練用のデータ
それが6万行
テストは1元行続いています
import csv
import urllib,urllib.request
import os.path
url_base = 'http://yann.lecun.com/exdb/mnist/' # ①
# 辞書オブジェクトdictで訓練用、訓練ラベル用、テスト用、テストラベル用gzファイルを
# key():各要素のキー(key)に対してforループ処理用にセット
# 他にvalueに対してのforループ処理(value())
# keyとvalueに対してのforループ処理(items())がある
key_file = { # ②
'train_img':'train-images-idx3-ubyte.gz',
'train_label':'train-labels-idx1-ubyte.gz',
'test_img':'t10k-images-idx3-ubyte.gz',
'test_label':'t10k-labels-idx1-ubyte.gz'
}
# データセットの保存場所を絶対パスすで指定
# key_fileとdataset_dirを関連付ける
dataset_dir = os.path.dirname(os.path.abspath(__file__)) # ③
# 辞書オブジェクトdictで訓練用、訓練ラベル用、テスト用、テストラベル用gzファイルを
# key():各要素のキー(key)に対してforループ処理用にセット
# 他にvalueに対してのforループ処理(value())
# keyとvalueに対してのforループ処理(items())がある
key_file = { # ②
'train_img':'train-images-idx3-ubyte.gz',
'train_label':'train-labels-idx1-ubyte.gz',
'test_img':'t10k-images-idx3-ubyte.gz',
'test_label':'t10k-labels-idx1-ubyte.gz'
}
# データセットの保存場所を絶対パスすで指定
# key_fileとdataset_dirを関連付ける
dataset_dir = os.path.dirname(os.path.abspath(__file__)) # ③
def _download(filename):
file_path = dataset_dir + '/' + filename
if os.path.exists(file_path):
return print('already exist')
print('Downloading ' + filename + ' ...')
urllib.request.urlretrieve(url_base + filename, file_path) #ダウンロードURLと保存先の指定
print('Done')
file_path = dataset_dir + '/' + filename
if os.path.exists(file_path):
return print('already exist')
print('Downloading ' + filename + ' ...')
urllib.request.urlretrieve(url_base + filename, file_path) #ダウンロードURLと保存先の指定
print('Done')
# データセットforループ処理
def download_mnist():
for v in key_file.values():
_download(v)
def download_mnist():
for v in key_file.values():
_download(v)
# 実行
download_mnist()
download_mnist()
# mnistデータファイルをcsvファイルに変換する
# 別に意味はなく784列のそれぞれの内容が分かればと思ってやりました
def convert(imgf, labelf, outf, n):
f = open(imgf, "rb")
o = open(outf, "w")
l = open(labelf, "rb")
# 別に意味はなく784列のそれぞれの内容が分かればと思ってやりました
def convert(imgf, labelf, outf, n):
f = open(imgf, "rb")
o = open(outf, "w")
l = open(labelf, "rb")
f.read(16)
l.read(8)
images = []
l.read(8)
images = []
for i in range(n):
image = [ord(l.read(1))]
for j in range(28*28):
image.append(ord(f.read(1)))
images.append(image)
image = [ord(l.read(1))]
for j in range(28*28):
image.append(ord(f.read(1)))
images.append(image)
for image in images:
o.write(",".join(str(pix) for pix in image)+"\n")
f.close()
o.close()
l.close()
o.write(",".join(str(pix) for pix in image)+"\n")
f.close()
o.close()
l.close()
convert("train-images.idx3-ubyte", "train-labels.idx1-ubyte",
"mnist_train.csv", 60000)
convert("t10k-images.idx3-ubyte", "t10k-labels.idx1-ubyte",
"mnist_test.csv", 10000)
"mnist_train.csv", 60000)
convert("t10k-images.idx3-ubyte", "t10k-labels.idx1-ubyte",
"mnist_test.csv", 10000)
