MINST样例数据的神经网络学习
标准的入门学习示例,
比一年前看的那书,更有感觉了。
# coding: utf-8
try:
import urllib.request
except ImportError:
raise ImportError('You should use Python 3.x')
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__))
print(dataset_dir)
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)
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))
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)
if normalize:
for key in ('train_img', 'test_img'):
dataset[key] = dataset[key].astype(np.float32)
dataset[key] /= 255.0
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()
import sys, os
import pickle
import numpy as np
from PIL import Image
from minst import load_mnist
# sigmoid作为隐藏层的激活函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# softmax作为输出层的激活函数
def softmax(a):
c = np.max(a)
exp_a = np.exp(a - c)
sum_exp_a = np.sum(exp_a)
y = exp_a / sum_exp_a
return y
def img_show(img):
pil_img = Image.fromarray(np.uint8(img))
pil_img.show()
def get_data():
(x_train, t_train), (x_test, t_test) = load_mnist(flatten=True, normalize=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, _ = get_data()
network = init_network()
W1, W2, W3 = network['W1'], network['W2'], network['W3']
print(x.shape)
print(x[0].shape)
print(W1.shape)
print(W2.shape)
print(W3.shape)
"""
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)))
精确率:
C:\Python36\python.exe C:/Users/Sahara/PycharmProjects/test1/test.py
C:\Users\Sahara\PycharmProjects\test1
Accuracy: 0.9352
Process finished with exit code 0
MINST样例数据的神经网络学习的更多相关文章
- RBF神经网络学习算法及与多层感知器的比较
对于RBF神经网络的原理已经在我的博文<机器学习之径向基神经网络(RBF NN)>中介绍过,这里不再重复.今天要介绍的是常用的RBF神经网络学习算法及RBF神经网络与多层感知器网络的对比. ...
- tensorflow中使用mnist数据集训练全连接神经网络-学习笔记
tensorflow中使用mnist数据集训练全连接神经网络 ——学习曹健老师“人工智能实践:tensorflow笔记”的学习笔记, 感谢曹老师 前期准备:mnist数据集下载,并存入data目录: ...
- 【cs231n】神经网络学习笔记3
+ mu) * v # 位置更新变了形式 对于NAG(Nesterov's Accelerated Momentum)的来源和数学公式推导,我们推荐以下的拓展阅读: Yoshua Bengio的Adv ...
- AI 神经网络学习
神经网络学习 1.输出与输入的关系(感知基): $$ y=\begin{Bmatrix} 1 & {\overrightarrow{x}\cdot \overrightarrow{w}+b&g ...
- [Neural Networks] (Convolutional Neural Networks)CNN-卷积神经网络学习
参考:http://blog.csdn.net/zouxy09/article/details/8781543 ( 但其中有部分错误) http://ufldl.stanford.edu/wiki/i ...
- 神经网络学习中的损失函数及mini-batch学习
# 损失函数(loss function).这个损失函数可以使用任意函数,# 但一般用均方误差(mean squared error)和交叉熵误差(cross entropy error)等一切都在代 ...
- BP神经网络学习笔记_附源代码
BP神经网络基本原理: 误差逆传播(back propagation, BP)算法是一种计算单个权值变化引起网络性能变化的较为简单的方法.由于BP算法过程包含从输出节点开始,反向地向第一隐含层(即最接 ...
- BP神经网络学习
人工神经元模型 S型函数(Sigmoid) 双极S型函数 神经网络可以分为哪些? 按照连接方式,可以分为:前向神经网络 vs. 反馈(递归)神经网络 按照学习方式,可以分为:有导师学习神经网络 ...
- 【cs231n】神经网络学习笔记1
神经网络推荐博客: 深度学习概述 神经网络基础之逻辑回归 神经网络基础之Python与向量化 浅层神经网络 深层神经网络 前言 首先声明,以下内容绝大部分转自知乎智能单元,他们将官方学习笔记进行了很专 ...
随机推荐
- node 单例
ScriptManager.getInstance = function () { if (_instance != null) { return _instance; } else { return ...
- Python:self理解
Python类 class Student: # 类变量,可以通过类.类变量(Student.classroom)或者实例.类变量(a.classroom)方式调用 classroom = '火箭班' ...
- VS 2015main函数带参数的调试
最近学习pcl,学习C++,今天让main的参数接收数据,想起没用过这样的,不知道怎么在vs里面调试 因此找了下方法,并记录下来 代码 #include<iostream> int mai ...
- springcloud 连接docker中运行的RabbitMQ消息中间件。
参考:https://blog.51cto.com/zero01/2173288 主要是记录几个坑: 第一个坑:开始订单服务中配置文件是: #配置rabbitmq 2019.5.17 added by ...
- session知识点小结
Session: 1. 概念:服务器端会话技术,在一次会话的多次请求间共享数据,将数据保存在服务器端的对象HttpSession中. 2. 快速入门: 1. 获取HttpSession对象: Http ...
- 关于st表
#include<cstdio> #include<iostream> #include<cmath> #include<cctype> #includ ...
- python学习-38迭代器和生成器
迭代器和生成器 ---- 迭代器协议和for循环工作机制 1.迭代器协议:对象必须提供一个next方法,执行该方法要么返回迭代中的下一项,要么引起一个Stoplteration异常,以终止迭代(只能往 ...
- jdbcUrl is required with driverClassName
https://blog.csdn.net/newbie_907486852/article/details/81391525 springboot2.0配置多数据源: spring.datasour ...
- 【转载】C#中可使用string.Empty代表空字符
在C#中,如果赋值一个字符串为空白字符串,我们一般会用“”的形式对字符串进行赋值操作,其实在C#的字符串类String类中,有个专门的常量string.Empty来代表空字符串,可直接在赋值的时候使用 ...
- 苹果手机浏览器的$(document).on(“click”,function(){}) 绑定的事件点击无效
需要给对应的元素加上 cursor: pointer 的css样式才可以生效点击事件: