首页 > 其他分享 >囚徒_mnist

囚徒_mnist

时间:2023-11-18 19:56:26浏览次数:29  
标签:key img label train mnist file dataset 囚徒


#囚徒 mnist
try:
import urllib.request
except ImportError:
raise ImportError('You should use Python 3.x')
from ast import Not
import os.path
import gzip
import pickle
import os
import numpy as np
url_base = 'http://yann.lecun.com/exdb/mnist/'
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'
}
dataset_dir = os.path.dirname(os.path.abspath(__file__)) #dataset文件夹路径
save_file = dataset_dir + "/mnist.pkl" #保存pcl的路径
train_num = 60000
test_num = 10000
img_dim = (1, 28, 28)
img_size = 784
#所有的file_name是dataset文件下的压缩文件,就是上述key_file字典中的值
def _download(file_name):
file_path = dataset_dir + "/" + file_name
if os.path.exists(file_path):
return
print("Downloading " + file_name + " ... ")
urllib.request.urlretrieve(url_base + file_name, file_path)
print("Done")
def download_mnist():
for v in key_file.values():
_download(v)
#加载标签
def _load_label(file_name):
file_path = dataset_dir + "/" + file_name
print("Converting " + file_name + " to NumPy Array ...")
with gzip.open(file_path, 'rb') as f:
labels = np.frombuffer(f.read(), np.uint8, offset=8)
print("Done")
return labels
#加载数据
def _load_img(file_name):
file_path = dataset_dir + "/" + file_name
print("Converting " + file_name + " to NumPy Array ...")
with gzip.open(file_path, 'rb') as f:
data = np.frombuffer(f.read(), np.uint8, offset=16) #转化为NumPy数组
data = data.reshape(-1, img_size)
print("Done")
return data
#调用函数转化为np数组
def _convert_numpy():
dataset = {}
dataset['train_img'] = _load_img(key_file['train_img'])
dataset['train_label'] = _load_label(key_file['train_label'])
dataset['test_img'] = _load_img(key_file['test_img'])
dataset['test_label'] = _load_label(key_file['test_label'])
return dataset
##将训练数组和测试数组写入pkl,存储下来
def init_mnist():
download_mnist()
dataset = _convert_numpy()
print("Creating pickle file ...")
with open(save_file, 'wb') as f:
pickle.dump(dataset, f, -1)
print("Done!") #存储pkl
def _change_one_hot_label(X):
T = np.zeros((X.size, 10))
for idx, row in enumerate(T):
row[X[idx]] = 1
return T
def load_mnist(normalize=True, flatten=True, one_hot_label=False):
"""读入MNIST数据集
Parameters
----------
normalize : 将图像的像素值正规化为0.0~1.0
one_hot_label :
one_hot_label为True的情况下,标签作为one-hot数组返回
one-hot数组是指[0,0,1,0,0,0,0,0,0,0]这样的数组
flatten : 是否将图像展开为一维数组
Returns
-------
(训练图像, 训练标签), (测试图像, 测试标签)
"""
#如果路径下pkl文件不存在,则执行函数,将写入并保存 pkl
if not os.path.exists(save_file):
init_mnist()
#加载pkl
with open(save_file, 'rb') as f:
dataset = pickle.load(f)
#将图像的像素值正规化为0.0~1.0
if normalize:
for key in ('train_img', 'test_img'):
dataset[key] = dataset[key].astype(np.float32)
dataset[key] /= 255.0
#将标签作为one-hot数组返回
if one_hot_label:
dataset['train_label'] = _change_one_hot_label(dataset['train_label'])
dataset['test_label'] = _change_one_hot_label(dataset['test_label'])
#将图像展开为一维数组
if not flatten:
for key in ('train_img', 'test_img'):
dataset[key] = dataset[key].reshape(-1, 1, 28, 28) #转换成一列
return (dataset['train_img'], dataset['train_label']), (dataset['test_img'], dataset['test_label'])
if __name__ == '__main__':
init_mnist()

标签:key,img,label,train,mnist,file,dataset,囚徒
From: https://www.cnblogs.com/qt-pyq/p/17840996.html

相关文章

  • 囚徒4.0_12
    #囚徒4.0_12importnumpyasnpdefAND(x1,x2):x=np.array([x1,x2])w=np.array([0.5,0.5])b=-0.7temp=np.sum(x*w)+biftemp>0:return1else:return0defOR(x1,x2):x=np.array([x1,x2])w=np.array([1,1])b=-0.5temp=np.sum(x*w)+biftemp>0:return1e......
  • 囚徒_风云云检测算法改进
    functionmask=code(ref_b2,ref_b3,ref_b4,ref_b5,tmp_7,tmp_9,tmp_13,tmp_15,SC,height,mask_lan)%算法实现%此处提供详细说明sz=size(ref_b2);temp=ref_b4*0;temp(temp~=-999.0)=1;raio=ref_b3./ref_b2;%可信矩阵准备mat_15=T_mat(tmp_15,224,228,"lt");mat_9=T_m......
  • 囚徒4.0_13_梯度
    囚徒4.0_13_梯度这是是关于求取梯度的#coding:utf-8importnumpyasnpimportmatplotlib.pylabaspltfrommpl_toolkits.mplot3dimportAxes3D#非批处理梯度求取(1,2)(x1,x2)def_numerical_gradient_no_batch(f,x):h=1e-4#0.0001grad=np.zeros_like(x)#对x进......
  • 囚徒4.1_12_数值微分近似
    数值微分近似#囚徒4.0_13_数值微分近似importnumpyasnpimportmatplotlib.pylabasplt#求数值微分导数defnumerical_diff(f,x):h=1e-4#0.0001return(f(x+h)-f(x-h))/(2*h)#函数deffunction_1(x):return0.01*x**2+0.1*xdeftangent_line(f,x):d......
  • 深度学习算法原理实现——自写神经网络识别mnist手写数字和训练模型
    代码来自:https://weread.qq.com/web/reader/33f32c90813ab71c6g018fffkd3d322001ad3d9446802347《python深度学习》fromtensorflow.keras.datasetsimportmnistfromtensorflow.kerasimportoptimizersimporttensorflowastfimportnumpyasnpclassNaiveDense:d......
  • python深度学习——一个简单的全连接神经网络,预测mnist手写数字
    代码来自《python深度学习》第二章:fromtensorflow.keras.datasetsimportmnistfromtensorflowimportkerasfromtensorflow.kerasimportlayers(train_images,train_labels),(test_images,test_labels)=mnist.load_data()print(train_images.shape)print(len(trai......
  • 零基础机器学习数字识别MNIST(on going)
    本人之前并未涉及机器学习,但是在嵌入式中都会涉及视觉,借校内比赛从零学习,进行MNIST数字识别模型的搭建。随着学习进度更新,每天更新。2023-11-1521:38:55星期三一、环境搭建进行本模型的搭建,需要以下内容:Python环境:利用Anaconda管理开源机器学习平台:PyTorch或Tensorf......
  • CNN --入门MNIST识别
    Smiling&Weeping----下次你撑伞低头看水洼,就会想起我说雨是神的烟花。 简介:主要是看刘二大人的视频讲解:https://www.bilibili.com/video/BV1Y7411d7Ys/?spm_id_from=333.337.search-card.all.click题目及提......
  • 记录编写并训练测试经典数据集mnist
    importtensorflowastfmnist=tf.keras.datasets.mnist(x_train,y_train),(x_test,y_test)=mnist.load_data()x_train,x_test=x_train/255.0,x_test/255.0model=tf.keras.models.Sequential([tf.keras.layers.Flatten(input_shape=(28,28)),tf.......
  • Mnist数据集分类任务试用
    学习方法边用边学,torch只是个工具,用起来,查的过程才是学习的过程直接上案例来学习,先跑起来,遇到问题就地解决使用jupiter的方式,来实现查看torch版本importtorchprint(torch.__version__)1、拿到数据集frompathlibimportPathimportrequestsDATA_PATH=Path("data")......