python深度学习入门代码(一)
看的是《深度学习入门:基于 Python 的理论与实现》这本书的配套代码,但是不太看得懂,慢慢看。。。。
mnist.py#该脚本支持从下载MNIST数据集到将这些数据转换成NumPy数组等处理
# coding: utf-8 try: import urllib.request#网页请求 except ImportError:#只有python3支持这个库 raise ImportError('You should use Python 3.x') import os.path#获取文件的属性 import gzip#解压文件 import pickle#用于序列化和反序列化Python对象结构的二进制协议 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__))#获取当前路径 save_file = dataset_dir + "/mnist.pkl" train_num = 60000 test_num = 10000 img_dim = (1, 28, 28) img_size = 784 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)#将缓冲去解释为一维数组 data = data.reshape(-1, img_size)#将数组变为img_size列,总元素个数保持不变,有多少行就变成多少行 print("Done") return data 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 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!") def _change_one_hot_label(X): T = np.zeros((X.size, 10))#给定一个用0填充的数组 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 ------- (训练图像, 训练标签), (测试图像, 测试标签) """ if not os.path.exists(save_file):#文件是否存在 init_mnist() with open(save_file, 'rb') as f:#打开文件 dataset = pickle.load(f)#反序列化对象,将文件中的数据解析为一个python对象 if normalize:#矢量标准化 for key in ('train_img', 'test_img'): dataset[key] = dataset[key].astype(np.float32)#转换数组的数据类型为float32 dataset[key] /= 255.0#像素值正规化 if one_hot_label:#是否为one-hot数组 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()
minis_show.py#划分数据集,查看数据集图片的格式
# coding: utf-8 import sys, os#文件处理 sys.path.append(os.pardir) # 为了导入父目录的文件而进行的设定 import numpy as np#基础数字计算库 from dataset.mnist import load_mnist#自己写的下载数据集的py文件 from PIL import Image#图像库 def img_show(img): pil_img = Image.fromarray(np.uint8(img))#图像格式转化 pil_img.show() (x_train, t_train), (x_test, t_test) = load_mnist(flatten=True, normalize=False)#分出训练集和测试集 img = x_train[0] label = t_train[0] print(label) # 5 print(img.shape) # (784,) img = img.reshape(28, 28) # 把图像的形状变为原来的尺寸 print(img.shape) # (28, 28) img_show(img)
neuralnet_mnist.py#我们对这个MNIST数据集实现神经网络的推理处理
# coding: utf-8 import sys, os sys.path.append(os.pardir) # 为了导入父目录的文件而进行的设定 import numpy as np import pickle from dataset.mnist import load_mnist from common.functions import sigmoid, softmax#把自己在各个不同项目中可以共用的基础函数汇总起来,形成一个独立的项目库,并对每个函数配上单元测试 def get_data(): (x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, flatten=True, one_hot_label=False) return x_test, t_test def init_network():#读入保存在pickle文件sample_weight.pkl中的学习到的权重参数 with open("sample_weight.pkl", 'rb') as f: network = pickle.load(f) return network def predict(network, x):#定义神经网络,以字典变量的形式保存权重和偏置参数 W1, W2, W3 = network['W1'], network['W2'], network['W3'] b1, b2, b3 = network['b1'], network['b2'], network['b3'] a1 = np.dot(x, W1) + b1 z1 = sigmoid(a1) a2 = np.dot(z1, W2) + b2 z2 = sigmoid(a2) a3 = np.dot(z2, W3) + b3 y = softmax(a3) return y x, t = get_data()#获得测试集 network = init_network() accuracy_cnt = 0 for i in range(len(x)): y = predict(network, x[i]) p= np.argmax(y) # 获取概率最高的元素的索引 if p == t[i]: accuracy_cnt += 1 print("Accuracy:" + str(float(accuracy_cnt) / len(x)))
neuralnet_mnist_batch.py#批处理图像
# coding: utf-8 import sys, os sys.path.append(os.pardir) # 为了导入父目录的文件而进行的设定 import numpy as np import pickle from dataset.mnist import load_mnist from common.functions import sigmoid, softmax def get_data(): (x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, flatten=True, one_hot_label=False) return x_test, t_test def init_network(): with open("sample_weight.pkl", 'rb') as f: network = pickle.load(f) return network def predict(network, x): w1, w2, w3 = network['W1'], network['W2'], network['W3'] b1, b2, b3 = network['b1'], network['b2'], network['b3'] a1 = np.dot(x, w1) + b1 z1 = sigmoid(a1) a2 = np.dot(z1, w2) + b2 z2 = sigmoid(a2) a3 = np.dot(z2, w3) + b3 y = softmax(a3) return y x, t = get_data() network = init_network() batch_size = 100 # 批数量 accuracy_cnt = 0 for i in range(0, len(x), batch_size): x_batch = x[i:i+batch_size] y_batch = predict(network, x_batch) p = np.argmax(y_batch, axis=1) accuracy_cnt += np.sum(p == t[i:i+batch_size]) print("Accuracy:" + str(float(accuracy_cnt) / len(x)))