转自:https://www.jianshu.com/p/4b30e1dd2252

common_funcs.py
import numpy as np
import matplotlib.pyplot as plt def sigmoid(x):
return 1/(1+np.exp(-x)) def softmax(a):
exp_a = np.exp(a)
sum_exp_a = np.sum(exp_a)
y = exp_a / sum_exp_a
return y def cross_entroy_error(y, t):
if y.ndim == 1:
t = t.reshape(1, t.size)
y = y.reshape(1, y.size) if t.size == y.size:
t = t.argmax(axis=1) batch_size = y.shape[0]
return -np.sum(np.log(y[np.arange(batch_size), t]+1e-7))/batch_size def numerical_gradient(f, x):
h = 1e-4
grad = np.zeros_like(x)
it = np.nditer(x,flags = ['multi_index'], op_flags = ['readwrite'])
while not it.finished:
idx = it.multi_index
tmp_val = x[idx]
x[idx] = float(tmp_val) + h
fxh1 = f(x) x[idx] = tmp_val-h
fxh2 = f(x)
grad[idx] = (fxh1 - fxh2)/(2*h) x[idx] = tmp_val
it.iternext()
return grad def function_2(x):
return np.sum(x**2)
TeoLayerNet.py
import numpy as np
from common_funcs import sigmoid, softmax, cross_entroy_error,numerical_gradient
class TwoLayerNet: def __init__(self, input_size, hidden_size, output_size, weight_init_std = 0.01):
self.params = {'w1':weight_init_std*np.random.randn(input_size,hidden_size),
'b1':np.zeros(hidden_size),
'w2':weight_init_std*np.random.randn(hidden_size,output_size),
'b2':np.zeros(output_size)} def predict(self,x):
w1, w2 = self.params['w1'], self.params['w2']
b1, b2 = self.params['b1'], self.params['b2']
#
a1 = np.dot(x, w1) + b1 #zhuyi x, w1de weizhi
z1 = sigmoid(a1)
#
a2 = np.dot(z1, w2) + b2
y = softmax(a2)
return y def loss(self, x, t):
y = self.predict(x)
return cross_entroy_error(y, t) def accuracy(self, x, t):
y = self.predict(x)
y = np.argmax(y, axis=1)
t = np.argmax(t, axis=1) accuracy = np.sum(y == t)/float(x.shap[0])
return accuracy def gradient(self, x, t):
loss_w = lambda w: self.loss(x, t) grads = {}
grads['w1'] = numerical_gradient(loss_w, self.params['w1'])
grads['b1'] = numerical_gradient(loss_w, self.params['b1'])
grads['w2'] = numerical_gradient(loss_w, self.params['w2'])
grads['b2'] = numerical_gradient(loss_w, self.params['b2']) return grads
minist.py
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__))
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'])
main.py
import numpy as np
import matplotlib.pyplot as plt
from mnist import load_mnist
from TwoLayerNet import TwoLayerNet (x_train, t_train),(x_test, t_test) = load_mnist(normalize = True, one_hot_label = True) train_loss_list = []
train_acc_list = []
test_acc_list = [] iter_num = 10000
train_size = x_train.shape[0]
batch_size = 100
learning_rate = 0.1
iter_per_epoch = max(train_size / batch_size, 1) net_work = TwoLayerNet(input_size=784, hidden_size=50, output_size=10) for i in range(iter_num):
batch_mask = np.random.choice(train_size, batch_size)
x_batch = x_train[batch_mask]
t_batch = t_train[batch_mask] grad = net_work.gradient(x_batch, t_batch) for key in ('w1', 'b1', 'w2', 'b2'):
net_work.params[key] -= learning_rate*grad[key] if i % iter_per_epoch == 0:
loss = net_work.loss(x_train, t_train)
train_loss_list.append(loss)
train_acc = net_work.accuracy(x_train, t_train)
train_acc_list.append(train_acc)
test_acc = net_work.accuracy(x_test, t_test)
test_acc_list.append(test_acc)
print('run... loss:{} train acc:{} test acc:{}'.format(loss, train_acc,test_acc))

自己动手实现一个网络模型 python的更多相关文章

  1. 动手写一个简单的Web框架(HelloWorld的实现)

    动手写一个简单的Web框架(HelloWorld的实现) 关于python的wsgi问题可以看这篇博客 我就不具体阐述了,简单来说,wsgi标准需要我们提供一个可以被调用的python程序,可以实函数 ...

  2. 自己动手实现 HashMap(Python字典),彻底系统的学习哈希表(上篇)——不看血亏!!!

    HashMap(Python字典)设计原理与实现(上篇)--哈希表的原理 在此前的四篇长文当中我们已经实现了我们自己的ArrayList和LinkedList,并且分析了ArrayList和Linke ...

  3. 《动手实现一个网页加载进度loading》

    loading随处可见,比如一个app经常会有下拉刷新,上拉加载的功能,在刷新和加载的过程中为了让用户感知到 load 的过程,我们会使用一些过渡动画来表达.最常见的比如"转圈圈" ...

  4. C#中自己动手创建一个Web Server(非Socket实现)

    目录 介绍 Web Server在Web架构系统中的作用 Web Server与Web网站程序的交互 HTTPListener与Socket两种方式的差异 附带Demo源码概述 Demo效果截图 总结 ...

  5. psutil一个基于python的跨平台系统信息跟踪模块

    受益于这个模块的帮助,在这里我推荐一手. https://pythonhosted.org/psutil/#processes psutil是一个基于python的跨平台系统信息监视模块.在pytho ...

  6. 自己动手实现一个简单的JSON解析器

    1. 背景 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.相对于另一种数据交换格式 XML,JSON 有着诸多优点.比如易读性更好,占用空间更少等.在 ...

  7. 一个使用 Python 的人工智能聊天机器人框架

    一个Python 的 AI Chatbot框架 建立一个聊天室可以听起来很棒,但它是完全可行的. IKY是一个内置于Python中的AI动力对话对话界面. 使用IKY,很容易创建自然语言会话场景,无需 ...

  8. 动手实现一个vue中的模态对话框组件

    写在前面 对话框是很常用的组件 , 在很多地方都会用到,一般我们可以使用自带的alert来弹出对话框,但是假如是设计 出的图该怎么办呢 ,所以我们需要自己写一个对话框,并且如果有很多地方都用到,那我们 ...

  9. 超详细动手搭建一个Vuepress站点及开启PWA与自动部署

    超详细动手搭建一个Vuepress站点及开启PWA与自动部署 五一之前就想写一篇关于Vuepress的文章,结果朋友结婚就不了了之了. 记得最后一定要看注意事项! Vuepress介绍 官网:http ...

随机推荐

  1. IIS Express 使用方法

    配置文件位置: "%userprofile%\My Documents\IISExpress\config\applicationhost.config" 站点配置节: <s ...

  2. (四) appium-desktop 脚本录制常用AW使用介绍

    通过使用appium-desktop录制脚本,编写app自动化脚本的过程中,会使用到一些AW,下面就这些AW的使用方法做详细的介绍.通过实践可以看到这几个AW可以完成测试工作. AWOpenGiveP ...

  3. java一周学习记录(2017/12/2)

    姓名:Danny                               日期:2017/12/2 周日 周一 周二 周三 周四 周五 周六 所花时间 120 150 190 150 180 28 ...

  4. HDU4372(第一类斯特林数)

    题意:N座高楼,高度均不同且为1~N中的数,从前向后看能看到F个,从后向前看能看到B个,问有多少种可能的排列数. 0 < N, F, B <= 2000 首先我们知道一个结论:n的环排列的 ...

  5. 3D打印技术的学习

    1. 我们使用3D建模软件:123Ddesign来设计 123D design软件保存格式有2种,分别为123dx和stl格式 123dx格式:选择菜单栏中“Save”下的“To my compute ...

  6. mysql5.7单机多实例安装

    基于之前的mysql5.7单实例安装 修改/etc/my.cnf文件如下(这里配置4个实例,可自行修改数目) # # 多实例配置文件,可以mysqld_multi --example 查看例子 # [ ...

  7. OI那些事——AFO

    \(OI\)那些事--\(AFO\) 世界上从此少了一个\(Oier\)也不会有人知道,也许只有某个人在某年某月某日翻到了Eternal 风度的博客才会发现:哇,这哥们怎么\(Noip\)就退役了 两 ...

  8. 搜索专题: HDU1429胜利大逃亡

    胜利大逃亡(续) Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total S ...

  9. luogu P5338 [TJOI2019]甲苯先生的滚榜

    传送门 首先,排名系统,一看就知道是原题,可以上平衡树来维护 然后考虑一种比较朴素的想法,因为我们要知道排名在一个人前面的人数,也就是AC数比他多的人数+AC数一样并且罚时少的人数,所以考虑维护那两个 ...

  10. install stackless python on ubuntu

    前言 我准备用stackless模拟游戏玩家登陆/注册等行为,测试游戏服务器的性能. 但是在安装stackless的过程中遇到了很多问题,特此记录下来,也分享给需要的朋友. 关于stackless S ...