用numpy实现搭建一个简单的forward和backward

  1. import numpy as np
  2. N, D_in, H, D_out = 64, 1000, 100, 10
  3. x = np.random.randn(N, D_in) # (64, 1000)
  4. y = np.random.randn(N, D_out) # (64, 10)
  5. w1 = np.random.randn(D_in, H) # (1000, 100)
  6. w2 = np.random.randn(H, D_out) # (100, 10)
  7. learning_rate = 1e-6
  8.  
  9. for t in range(2):
  10. # Forward pass: compute predicted y
  11. h = x.dot(w1) # (64, 100)
  12. h_relu = np.maximum(h, 0) # (64, 100) 实现relu函数功能
  13. y_pred = h_relu.dot(w2) # (64, 10)
  14.  
  15. loss = np.square(y_pred - y).sum() # sum()所有元素求和
  16. # Backprop to compute gradients of w1 and w2 with respect to loss
  17. grad_y_pred = 2.0 * (y_pred - y)
  18. grad_w2 = h_relu.T.dot(grad_y_pred)
  19. grad_h_relu = grad_y_pred.dot(w2.T)
  20. grad_h = grad_h_relu.copy() # (64, 100)
  21. grad_h[h < 0] = 0 # 在h中负元素对应位置处grad_h中置0 -> 实现relu函数功能
  22. grad_w1 = x.T.dot(grad_h) # .T是转置 (1000, 100)
  23.  
  24. # Update weights
  25. w1 -= learning_rate * grad_w1 # (1000, 100)
  26. w2 -= learning_rate * grad_w2

用tensor实现搭建一个简单的forward和backward

  1. import torch
  2.  
  3. dtype = torch.FloatTensor
  4. # dtype = torch.cuda.FloatTensor
  5.  
  6. # N is batch size; D_in is input dimension;
  7. # H is hidden dimension; D_out is output dimension.
  8. N, D_in, H, D_out = 64, 1000, 100, 10
  9.  
  10. x = torch.randn(N, D_in).type(dtype)
  11. y = torch.randn(N, D_out).type(dtype)
  12.  
  13. # Randomly initialize weights
  14. w1 = torch.randn(D_in, H).type(dtype)
  15. w2 = torch.randn(H, D_out).type(dtype)
  16.  
  17. learning_rate = 1e-6
  18. for t in range(500):
  19. # Forward pass: compute predicted y
  20. h = x.mm(w1) # 与numpy对比,dot点乘
  21. h_relu = h.clamp(min=0)
  22. y_pred = h_relu.mm(w2)
  23.  
  24. loss = (y_pred - y).pow(2).sum()
  25. # Backprop to compute gradients of w1 and w2 with respect to loss
  26. grad_y_pred = 2.0 * (y_pred - y)
  27. grad_w2 = h_relu.t().mm(grad_y_pred)
  28. grad_h_relu = grad_y_pred.mm(w2.t())
  29. grad_h = grad_h_relu.clone()
  30. grad_h[h < 0] = 0
  31. grad_w1 = x.t().mm(grad_h)
  32.  
  33. # Update weights using gradient descent
  34. w1 -= learning_rate * grad_w1
  35. w2 -= learning_rate * grad_w2

用variable实现forward和backward

  1. # use PyTorch Variables and autograd to implement our two-layer network;
    # now we no longer need to manually implement the backward pass through the network
  2.  
  3. import torch
  4. from torch.autograd import Variable
  5.  
  6. dtype = torch.FloatTensor
  7. N, D_in, H, D_out = 64, 1000, 100, 10
  8.  
  9. # Setting requires_grad=False indicates that we do not need to compute gradients with respect to these Variables during the backward pass.
  10. x = Variable(torch.randn(N, D_in).type(dtype), requires_grad=False)
  11. y = Variable(torch.randn(N, D_out).type(dtype), requires_grad=False)
  12.  
  13. # Setting requires_grad=True indicates that we want to compute gradients with respect to these Variables during the backward pass.
  14. w1 = Variable(torch.randn(D_in, H).type(dtype), requires_grad=True)
  15. w2 = Variable(torch.randn(H, D_out).type(dtype), requires_grad=True)
  16.  
  17. learning_rate = 1e-6
  18. for t in range(2):
  19. # Forward pass: we do not need to keep references to intermediate values since we are not implementing the backward pass by hand
  20. y_pred = x.mm(w1).clamp(min=0).mm(w2)
  21.  
  22. # Now loss is a Variable of shape (1,) and loss.data is a Tensor of shape (1,); loss.data[0] is a scalar value holding the loss.
  23. loss = (y_pred - y).pow(2).sum()
  24. # print(loss) # [torch.FloatTensor of size 1]
  25. # print(loss.size()) # torch.Size([1])
  26. # print(loss.data) # [torch.FloatTensor of size 1]
  27. print(loss.data[0])
  28.  
  29. loss.backward()
  30.  
  31. w1.data -= learning_rate * w1.grad.data
  32. w2.data -= learning_rate * w2.grad.data
  33.  
  34. w1.grad.data.zero_()
  35. w2.grad.data.zero_()

用variable实现relu函数

  1. import torch
  2. from torch.autograd import Variable
  3.  
  4. class MyReLU(torch.autograd.Function):
  5. def forward(self, input):
  6. self.save_for_backward(input)
  7. return input.clamp(min=0)
  8.  
  9. def backward(self, grad_output):
  10. input, = self.saved_tensors
  11. grad_input = grad_output.clone()
  12. grad_input[input < 0] = 0
  13. return grad_input
  14.  
  15. dtype = torch.FloatTensor
  16. N, D_in, H, D_out = 64, 1000, 100, 10
  17.  
  18. x = Variable(torch.randn(N, D_in).type(dtype), requires_grad=False)
  19. y = Variable(torch.randn(N, D_out).type(dtype), requires_grad=False)
  20.  
  21. w1 = Variable(torch.randn(D_in, H).type(dtype), requires_grad=True)
  22. w2 = Variable(torch.randn(H, D_out).type(dtype), requires_grad=True)
  23.  
  24. learning_rate = 1e-6
  25. for t in range(2):
  26. relu = MyReLU()
  27.  
  28. # Forward pass
  29. y_pred = relu(x.mm(w1)).mm(w2)
  30.  
  31. loss = (y_pred - y).pow(2).sum()
  32. loss.backward()
  33.  
  34. w1.data -= learning_rate * w1.grad.data
  35. w2.data -= learning_rate * w2.grad.data
  36.  
  37. w1.grad.data.zero_()
  38. w2.grad.data.zero_()

模型搭建练习1_用numpy和tensor、variable实现前后向传播、实现激活函数的更多相关文章

  1. 入门项目数字手写体识别:使用Keras完成CNN模型搭建(重要)

    摘要: 本文是通过Keras实现深度学习入门项目——数字手写体识别,整个流程介绍比较详细,适合初学者上手实践. 对于图像分类任务而言,卷积神经网络(CNN)是目前最优的网络结构,没有之一.在面部识别. ...

  2. 一周总结:AutoEncoder、Inception 、模型搭建及下周计划

    一周总结:AutoEncoder.Inception .模型搭建及下周计划   1.AutoEncoder: AutoEncoder: 自动编码器就是一种尽可能复现输入信号的神经网络:自动编码器必须捕 ...

  3. [开发技巧]·TensorFlow中numpy与tensor数据相互转化

    [开发技巧]·TensorFlow中numpy与tensor数据相互转化 个人主页–> https://xiaosongshine.github.io/ - 问题描述 在我们使用TensorFl ...

  4. 【Python秘籍】numpy到tensor的转换

    在用pytorch训练神经网络时,我们常常需要在numpy的数组变量类型与pytorch中的tensor类型进行转换,今天给大家介绍一种它们之间互相转换的方法. 一.numpy到tensor 首先我们 ...

  5. TensorFlow中numpy与tensor数据相互转化

    numpy与tensor数据相互转化: *Numpy2Tensor 虽然TensorFlow网络在输入Numpy数据时会自动转换为Tensor来处理,但是我们自己也可以去显式的转换: data_ten ...

  6. Darknet_Yolov3模型搭建

    Darknet_Yolov3模型搭建 YOLO(You only look once)是目前流行的目标检测模型之一,目前最新已经发展到V3版本了,在业界的应用也很广泛.YOLO的特点就是"快 ...

  7. 【python学习小知识】求绝对值和numpy和tensor的相互转换

    一.python求绝对值的三种方法 1.条件判断 2.内置函数abs() 3.内置模块 math.fabs 1.条件判段,判断大于0还是小于0,小于0则输出相反数即可 # 法1:使用条件判断求绝对值 ...

  8. Python 学习之中的一个:在Mac OS X下基于Sublime Text搭建开发平台包括numpy,scipy

    1 前言 Python有许多IDE能够用,官方自己也带了一个,Eclipse也能够. 但我在使用各种IDE之后,发现用Sublime Text是最好用的一个.因此.我都是用Sublime Text来编 ...

  9. TypeError: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

    报错原因:numpy不能读取CUDA tensor 需要将它转化为 CPU tensor. 所以如果想把CUDA tensor格式的数据改成numpy时,需要先将其转换成cpu float-tenso ...

随机推荐

  1. 【Kubernetes】资源列表

    1.Kubernetes资源列表 https://www.cnblogs.com/linuxk/p/10436260.html

  2. go经典练习题涉及流程控制-字符串-struct-map的数据类型的处理

    one:求1到100之间的质数 package main import ( "fmt" ) func isPrime(n int) bool { var flag = true f ...

  3. php 判断一个点是否在一个多边形区域内

    <?php class pointMap{ private static $coordArray; private static $vertx = []; private static $ver ...

  4. Java学习3之成员方法及函数重载

    方法的定义:方法名称,返回值,参数列表,修饰符(权限修饰符,final,static),实现体. 参考自:<Java 程序设计与工程实践> 方法的签名: 唯一区别其他方法的元素:(1)方法 ...

  5. [cocos2dx utils] cocos2dx读取,解析csv文件

    在我们的游戏中,经常需要将策划的数值配置成csv文件,所以解析csv文件就是一个很common的logic, 例如如下csv文件: 下面是一个基于cocos2dx 2.2.4的实现类: #ifndef ...

  6. 【bzoj1189】[HNOI2007]紧急疏散evacuate BFS最短路+动态加边网络流

    题目描述 发生了火警,所有人员需要紧急疏散!假设每个房间是一个N M的矩形区域.每个格子如果是'.',那么表示这是一块空地:如果是'X',那么表示这是一面墙,如果是'D',那么表示这是一扇门,人们可以 ...

  7. [canvas入坑1]canvas 画布拖拽效果

    查看效果请到 http://philippica.github.io/  点击drag 和上一篇画图很像,所以有些部分做了省略 当鼠标按下时保存当前画布上的内容到ppImgData中,并且记录下初始点 ...

  8. linux编程学习

    linux编程学习 工具篇 “公欲善其事,必先利其器”.编程是一门实践性很强的工作,在你以后的学习或工作中,你将常常会与以下工具打交道, 下面列出学习 C 语言编程常常用到的软件和工具. (一)操作系 ...

  9. Databus架构分析与初步实践

    简介 Databus是一个低延迟.可靠的.支持事务的.保持一致性的数据变更抓取系统.由LinkedIn于2013年开源.Databus通过挖掘数据库日志的方式,将数据库变更实时.可靠的从数据库拉取出来 ...

  10. 远程映射错误 “发生系统错误 1312 指定的登录会话不存在。可能已被终止 IIS 访问 远程共享目录”

    最近和其他公司做接口,需要将数据上传给对方. 我们发送程序部署在前置机上,文件在内网数据中.需要映射到文件服务器后上传数据.本机vs开发是可以映射成功,但是部署到远程的IIS中,就不能成功. 报错:  ...