"""
利用numpy实现一个两层的全连接网络
网络结构是:input ->(w1) fc_h -> relu ->(w2) output
数据是随机出的
"""
import numpy as np
#维度和大小参数定义
batch_size = 64
input_dim = 1000
output_dim = 10
hidden_dim = 100 # 数据虚拟 (x,y)
# 每行是一条数据 输入是64*1000,1000表示有1000维度的特征 输出是64*100
# 训练完参数之后,若对一条数据forward,直接运用w1 w2参数即可
# 使用relu激活函数
x = np.random.randn(batch_size,input_dim)
y = np.random.randn(batch_size,output_dim) #定义要训练的参数 w1(1000*100) w2(100*10)
# 方便起见,不设bisa
w1 = np.random.randn(input_dim,hidden_dim)
w2 = np.random.randn(hidden_dim,output_dim) # lr
lr = 1e-06
#实现
for i in range(500):
#迭代500次
#前向传播
h = x.dot(w1) #隐藏层
h_relu = np.maximum(h,0) #relu激活函数
y_hat = h_relu.dot(w2) #计算损失
loss = np.square(y_hat - y).sum() #计算梯度
y_hat_grad = 2.0*(y_hat-y)
w2_grad = h_relu.T.dot(y_hat_grad)
h_relu_grad = y_hat_grad.dot(w2.T)
h_grad = h_relu_grad.copy()
h_grad[h < 0] = 0
w1_grad = x.T.dot(h_grad) #更新参数
w1 = w1 - lr*w1_grad
w2 = w2 - lr*w2_grad
#print("epoch "+str(i)+" end......")
#print("参数w1:")
#print(w1)
#print("参数w1:")
#print(w2)
"""
使用pytorch实现上面的二层神经网络
"""
# pytorch中
## 内积
# tensor.mm(tensor)
## 转置
# tensor.t()
## 乘方运算
# tensor.pow(n)
import torch
device = torch.device('cpu')
# device = torch.device('cuda') # Uncomment this to run on GPU # N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10 # Create random input and output data
x = torch.randn(N, D_in, device=device)
y = torch.randn(N, D_out, device=device) # Randomly initialize weights
w1 = torch.randn(D_in, H, device=device)
w2 = torch.randn(H, D_out, device=device) learning_rate = 1e-6
for t in range(500):
# Forward pass: compute predicted y
h = x.mm(w1)
h_relu = h.clamp(min=0)
y_pred = h_relu.mm(w2) # Compute and print loss; loss is a scalar, and is stored in a PyTorch Tensor
# of shape (); we can get its value as a Python number with loss.item().
loss = (y_pred - y).pow(2).sum()
#print(t, loss.item()) # Backprop to compute gradients of w1 and w2 with respect to loss
grad_y_pred = 2.0 * (y_pred - y)
grad_w2 = h_relu.t().mm(grad_y_pred)
grad_h_relu = grad_y_pred.mm(w2.t())
grad_h = grad_h_relu.clone()
grad_h[h < 0] = 0
grad_w1 = x.t().mm(grad_h) # Update weights using gradient descent
w1 -= learning_rate * grad_w1
w2 -= learning_rate * grad_w2
"""
使用pytorch的自动求导 重新实现
"""
import torch device = torch.device('cpu')
# device = torch.device('cuda') # Uncomment this to run on GPU # N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10 # Create random Tensors to hold input and outputs
x = torch.randn(N, D_in, device=device)
y = torch.randn(N, D_out, device=device) # Create random Tensors for weights; setting requires_grad=True means that we
# want to compute gradients for these Tensors during the backward pass.
w1 = torch.randn(D_in, H, device=device, requires_grad=True)
w2 = torch.randn(H, D_out, device=device, requires_grad=True) learning_rate = 1e-6
for t in range(500):
# Forward pass: compute predicted y using operations on Tensors. Since w1 and
# w2 have requires_grad=True, operations involving these Tensors will cause
# PyTorch to build a computational graph, allowing automatic computation of
# gradients. Since we are no longer implementing the backward pass by hand we
# don't need to keep references to intermediate values.
y_pred = x.mm(w1).clamp(min=0).mm(w2) # Compute and print loss. Loss is a Tensor of shape (), and loss.item()
# is a Python number giving its value.
loss = (y_pred - y).pow(2).sum()
#print(t, loss.item()) # Use autograd to compute the backward pass. This call will compute the
# gradient of loss with respect to all Tensors with requires_grad=True.
# After this call w1.grad and w2.grad will be Tensors holding the gradient
# of the loss with respect to w1 and w2 respectively.
loss.backward() # Update weights using gradient descent. For this step we just want to mutate
# the values of w1 and w2 in-place; we don't want to build up a computational
# graph for the update steps, so we use the torch.no_grad() context manager
# to prevent PyTorch from building a computational graph for the updates
with torch.no_grad():
w1 -= learning_rate * w1.grad
w2 -= learning_rate * w2.grad # Manually zero the gradients after running the backward pass
w1.grad.zero_()
w2.grad.zero_()
# 自己定义网络的一层实现

# 定义自己Relu类,继承自Function函数
# 必须同时实现forward和backward
# 前向传播时,forward用的自己定义的这个
# 反向传播时,必然会再找自己实现的这个backward,如不写,则no implment error class MyReLU(torch.autograd.Function):
"""
We can implement our own custom autograd Functions by subclassing
torch.autograd.Function and implementing the forward and backward passes
which operate on Tensors.
"""
@staticmethod
def forward(ctx, x):
"""
In the forward pass we receive a context object and a Tensor containing the
input; we must return a Tensor containing the output, and we can use the
context object to cache objects for use in the backward pass.
"""
ctx.save_for_backward(x)
return x.clamp(min=0) @staticmethod
def backward(ctx, grad_output):
"""
In the backward pass we receive the context object and a Tensor containing
the gradient of the loss with respect to the output produced during the
forward pass. We can retrieve cached data from the context object, and must
compute and return the gradient of the loss with respect to the input to the
forward function.
"""
x, = ctx.saved_tensors
grad_x = grad_output.clone()
grad_x[x < 0] = 0
return grad_x device = torch.device('cpu')
# device = torch.device('cuda') # Uncomment this to run on GPU # N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10 # Create random Tensors to hold input and output
x = torch.randn(N, D_in, device=device)
y = torch.randn(N, D_out, device=device) # Create random Tensors for weights.
w1 = torch.randn(D_in, H, device=device, requires_grad=True)
w2 = torch.randn(H, D_out, device=device, requires_grad=True) learning_rate = 1e-6
for t in range(500):
# Forward pass: compute predicted y using operations on Tensors; we call our
# custom ReLU implementation using the MyReLU.apply function
y_pred = MyReLU.apply(x.mm(w1)).mm(w2) # Compute and print loss
loss = (y_pred - y).pow(2).sum()
#print(t, loss.item()) # Use autograd to compute the backward pass.
loss.backward() with torch.no_grad():
# Update weights using gradient descent
w1 -= learning_rate * w1.grad
w2 -= learning_rate * w2.grad # Manually zero the gradients after running the backward pass
w1.grad.zero_()
w2.grad.zero_()

【Code】numpy、pytorch实现全连接神经网络的更多相关文章

  1. 如何使用numpy实现一个全连接神经网络?(上)

    全连接神经网络的概念我就不介绍了,对这个不是很了解的朋友,可以移步其他博主的关于神经网络的文章,这里只介绍我使用基本工具实现全连接神经网络的方法. 所用工具: numpy == 1.16.4 matp ...

  2. MINIST深度学习识别:python全连接神经网络和pytorch LeNet CNN网络训练实现及比较(三)

    版权声明:本文为博主原创文章,欢迎转载,并请注明出处.联系方式:460356155@qq.com 在前两篇文章MINIST深度学习识别:python全连接神经网络和pytorch LeNet CNN网 ...

  3. TensorFlow之DNN(二):全连接神经网络的加速技巧(Xavier初始化、Adam、Batch Norm、学习率衰减与梯度截断)

    在上一篇博客<TensorFlow之DNN(一):构建“裸机版”全连接神经网络>中,我整理了一个用TensorFlow实现的简单全连接神经网络模型,没有运用加速技巧(小批量梯度下降不算哦) ...

  4. TensorFlow之DNN(一):构建“裸机版”全连接神经网络

    博客断更了一周,干啥去了?想做个聊天机器人出来,去看教程了,然后大受打击,哭着回来补TensorFlow和自然语言处理的基础了.本来如意算盘打得挺响,作为一个初学者,直接看项目(不是指MINIST手写 ...

  5. 【TensorFlow/简单网络】MNIST数据集-softmax、全连接神经网络,卷积神经网络模型

    初学tensorflow,参考了以下几篇博客: soft模型 tensorflow构建全连接神经网络 tensorflow构建卷积神经网络 tensorflow构建卷积神经网络 tensorflow构 ...

  6. Tensorflow 多层全连接神经网络

    本节涉及: 身份证问题 单层网络的模型 多层全连接神经网络 激活函数 tanh 身份证问题新模型的代码实现 模型的优化 一.身份证问题 身份证号码是18位的数字[此处暂不考虑字母的情况],身份证倒数第 ...

  7. tensorflow中使用mnist数据集训练全连接神经网络-学习笔记

    tensorflow中使用mnist数据集训练全连接神经网络 ——学习曹健老师“人工智能实践:tensorflow笔记”的学习笔记, 感谢曹老师 前期准备:mnist数据集下载,并存入data目录: ...

  8. 深度学习tensorflow实战笔记(1)全连接神经网络(FCN)训练自己的数据(从txt文件中读取)

    1.准备数据 把数据放进txt文件中(数据量大的话,就写一段程序自己把数据自动的写入txt文件中,任何语言都能实现),数据之间用逗号隔开,最后一列标注数据的标签(用于分类),比如0,1.每一行表示一个 ...

  9. 基于MNIST数据集使用TensorFlow训练一个包含一个隐含层的全连接神经网络

    包含一个隐含层的全连接神经网络结构如下: 包含一个隐含层的神经网络结构图 以MNIST数据集为例,以上结构的神经网络训练如下: #coding=utf-8 from tensorflow.exampl ...

随机推荐

  1. (五)surging 微服务框架使用系列之缓存-reids

    1.服务跟客户端初始化的时候需要添加缓存配置 var host = new ServiceHostBuilder() .RegisterServices(builder => { builder ...

  2. 【憩园】C#并发编程之异步编程(三)

      写在前面 本篇是异步编程系列的第三篇,本来计划第三篇的内容是介绍异步编程中常用的几个方法,但是前两篇写出来后,身边的朋友总是会有其他问题,所以决定再续写一篇,作为异步编程(一)和异步编程(二)的补 ...

  3. HTML学习总结&基础篇

    何为坚持?一个“勤”,一个“忍”. 年前给自己定的目标,今年一定要坚持多逛园子,多看一些大佬的帖子,然后自己也尽量能够分享自己学习的收获,让自己进步快些,但是多逛园子是做到了,写博客这个东西,今年好像 ...

  4. 编程心法 之 Scrum - Agile 敏捷开发

    Scrum是一种敏捷开发的方法 先定一个能达到的小目标 Scrum 团队 包括产品负责人.开发团队和Scrum Master Product Owner 产品负责人:管理代办事项和优先级的唯一负责人. ...

  5. Java 工厂模式(一)— 抽象工厂(Abstract Factory)模式

    一.抽象工厂模式介绍: 1.什么是抽象工厂模式: 抽象工厂模式是所有形态的工厂模式中最为抽象和最具有一般性的一种形态,抽象工厂模式向客户端提供一个接口,使得客户端在不知道具体产品的情类型的情况下,创建 ...

  6. Docker-镜像源加速配置

    Docker官网镜像服务在境外,拉取速度很比较慢,所以我们安装完Docker后一般会切换镜像源,将镜像源切换到国内以此达到加速的目的. 国内比较常用的Docker Hub镜像服务:1.阿里云2.Dao ...

  7. Unity NPOI 无法读取xlsx

    遇到问题 在做编辑器开发时,需要在Unity Editor下直接读取Excel源文件,首先想到的是通过npoi去读取,但是遇到无法读取xlsx格式,只能读取xls格式的问题. 我的环境 unity 2 ...

  8. 如何使用java validation api进行参数校验----Hibernate-Validation

    在日常开发中,Hibernate Validator经常用来验证bean的字段,基于注解,方便快捷高效. 1. Bean Validation 中内置的 constraint 注解           ...

  9. AI-2048 注释

    针对2048游戏,有人实现了一个AI程序,可以以较大概率(高于90%)赢得游戏,并且作者在 stackoverflow上简要介绍了AI的算法框架和实现思路. 有博客介绍了其中涉及的算法,讲的很好 其中 ...

  10. 功能测试话题分享-0323 Bug