1. """
  2. 利用numpy实现一个两层的全连接网络
  3. 网络结构是:input ->(w1) fc_h -> relu ->(w2) output
  4. 数据是随机出的
  5. """
  6. import numpy as np
  7. #维度和大小参数定义
  8. batch_size = 64
  9. input_dim = 1000
  10. output_dim = 10
  11. hidden_dim = 100
  12. # 数据虚拟 (x,y)
  13. # 每行是一条数据 输入是64*1000,1000表示有1000维度的特征 输出是64*100
  14. # 训练完参数之后,若对一条数据forward,直接运用w1 w2参数即可
  15. # 使用relu激活函数
  16. x = np.random.randn(batch_size,input_dim)
  17. y = np.random.randn(batch_size,output_dim)
  18. #定义要训练的参数 w1(1000*100) w2(100*10)
  19. # 方便起见,不设bisa
  20. w1 = np.random.randn(input_dim,hidden_dim)
  21. w2 = np.random.randn(hidden_dim,output_dim)
  22. # lr
  23. lr = 1e-06
  24. #实现
  25. for i in range(500):
  26. #迭代500次
  27. #前向传播
  28. h = x.dot(w1) #隐藏层
  29. h_relu = np.maximum(h,0) #relu激活函数
  30. y_hat = h_relu.dot(w2)
  31. #计算损失
  32. loss = np.square(y_hat - y).sum()
  33. #计算梯度
  34. y_hat_grad = 2.0*(y_hat-y)
  35. w2_grad = h_relu.T.dot(y_hat_grad)
  36. h_relu_grad = y_hat_grad.dot(w2.T)
  37. h_grad = h_relu_grad.copy()
  38. h_grad[h < 0] = 0
  39. w1_grad = x.T.dot(h_grad)
  40. #更新参数
  41. w1 = w1 - lr*w1_grad
  42. w2 = w2 - lr*w2_grad
  43. #print("epoch "+str(i)+" end......")
  44. #print("参数w1:")
  45. #print(w1)
  46. #print("参数w1:")
  47. #print(w2)
  1. """
  2. 使用pytorch实现上面的二层神经网络
  3. """
  4. # pytorch中
  5. ## 内积
  6. # tensor.mm(tensor)
  7. ## 转置
  8. # tensor.t()
  9. ## 乘方运算
  10. # tensor.pow(n)
  11. import torch
  12. device = torch.device('cpu')
  13. # device = torch.device('cuda') # Uncomment this to run on GPU
  14. # N is batch size; D_in is input dimension;
  15. # H is hidden dimension; D_out is output dimension.
  16. N, D_in, H, D_out = 64, 1000, 100, 10
  17. # Create random input and output data
  18. x = torch.randn(N, D_in, device=device)
  19. y = torch.randn(N, D_out, device=device)
  20. # Randomly initialize weights
  21. w1 = torch.randn(D_in, H, device=device)
  22. w2 = torch.randn(H, D_out, device=device)
  23. learning_rate = 1e-6
  24. for t in range(500):
  25. # Forward pass: compute predicted y
  26. h = x.mm(w1)
  27. h_relu = h.clamp(min=0)
  28. y_pred = h_relu.mm(w2)
  29. # Compute and print loss; loss is a scalar, and is stored in a PyTorch Tensor
  30. # of shape (); we can get its value as a Python number with loss.item().
  31. loss = (y_pred - y).pow(2).sum()
  32. #print(t, loss.item())
  33. # Backprop to compute gradients of w1 and w2 with respect to loss
  34. grad_y_pred = 2.0 * (y_pred - y)
  35. grad_w2 = h_relu.t().mm(grad_y_pred)
  36. grad_h_relu = grad_y_pred.mm(w2.t())
  37. grad_h = grad_h_relu.clone()
  38. grad_h[h < 0] = 0
  39. grad_w1 = x.t().mm(grad_h)
  40. # Update weights using gradient descent
  41. w1 -= learning_rate * grad_w1
  42. w2 -= learning_rate * grad_w2
  1. """
  2. 使用pytorch的自动求导 重新实现
  3. """
  4. import torch
  5. device = torch.device('cpu')
  6. # device = torch.device('cuda') # Uncomment this to run on GPU
  7. # N is batch size; D_in is input dimension;
  8. # H is hidden dimension; D_out is output dimension.
  9. N, D_in, H, D_out = 64, 1000, 100, 10
  10. # Create random Tensors to hold input and outputs
  11. x = torch.randn(N, D_in, device=device)
  12. y = torch.randn(N, D_out, device=device)
  13. # Create random Tensors for weights; setting requires_grad=True means that we
  14. # want to compute gradients for these Tensors during the backward pass.
  15. w1 = torch.randn(D_in, H, device=device, requires_grad=True)
  16. w2 = torch.randn(H, D_out, device=device, requires_grad=True)
  17. learning_rate = 1e-6
  18. for t in range(500):
  19. # Forward pass: compute predicted y using operations on Tensors. Since w1 and
  20. # w2 have requires_grad=True, operations involving these Tensors will cause
  21. # PyTorch to build a computational graph, allowing automatic computation of
  22. # gradients. Since we are no longer implementing the backward pass by hand we
  23. # don't need to keep references to intermediate values.
  24. y_pred = x.mm(w1).clamp(min=0).mm(w2)
  25. # Compute and print loss. Loss is a Tensor of shape (), and loss.item()
  26. # is a Python number giving its value.
  27. loss = (y_pred - y).pow(2).sum()
  28. #print(t, loss.item())
  29. # Use autograd to compute the backward pass. This call will compute the
  30. # gradient of loss with respect to all Tensors with requires_grad=True.
  31. # After this call w1.grad and w2.grad will be Tensors holding the gradient
  32. # of the loss with respect to w1 and w2 respectively.
  33. loss.backward()
  34. # Update weights using gradient descent. For this step we just want to mutate
  35. # the values of w1 and w2 in-place; we don't want to build up a computational
  36. # graph for the update steps, so we use the torch.no_grad() context manager
  37. # to prevent PyTorch from building a computational graph for the updates
  38. with torch.no_grad():
  39. w1 -= learning_rate * w1.grad
  40. w2 -= learning_rate * w2.grad
  41. # Manually zero the gradients after running the backward pass
  42. w1.grad.zero_()
  43. w2.grad.zero_()
  1. # 自己定义网络的一层实现
  2. # 定义自己Relu类,继承自Function函数
  3. # 必须同时实现forward和backward
  4. # 前向传播时,forward用的自己定义的这个
  5. # 反向传播时,必然会再找自己实现的这个backward,如不写,则no implment error
  6. class MyReLU(torch.autograd.Function):
  7. """
  8. We can implement our own custom autograd Functions by subclassing
  9. torch.autograd.Function and implementing the forward and backward passes
  10. which operate on Tensors.
  11. """
  12. @staticmethod
  13. def forward(ctx, x):
  14. """
  15. In the forward pass we receive a context object and a Tensor containing the
  16. input; we must return a Tensor containing the output, and we can use the
  17. context object to cache objects for use in the backward pass.
  18. """
  19. ctx.save_for_backward(x)
  20. return x.clamp(min=0)
  21. @staticmethod
  22. def backward(ctx, grad_output):
  23. """
  24. In the backward pass we receive the context object and a Tensor containing
  25. the gradient of the loss with respect to the output produced during the
  26. forward pass. We can retrieve cached data from the context object, and must
  27. compute and return the gradient of the loss with respect to the input to the
  28. forward function.
  29. """
  30. x, = ctx.saved_tensors
  31. grad_x = grad_output.clone()
  32. grad_x[x < 0] = 0
  33. return grad_x
  34. device = torch.device('cpu')
  35. # device = torch.device('cuda') # Uncomment this to run on GPU
  36. # N is batch size; D_in is input dimension;
  37. # H is hidden dimension; D_out is output dimension.
  38. N, D_in, H, D_out = 64, 1000, 100, 10
  39. # Create random Tensors to hold input and output
  40. x = torch.randn(N, D_in, device=device)
  41. y = torch.randn(N, D_out, device=device)
  42. # Create random Tensors for weights.
  43. w1 = torch.randn(D_in, H, device=device, requires_grad=True)
  44. w2 = torch.randn(H, D_out, device=device, requires_grad=True)
  45. learning_rate = 1e-6
  46. for t in range(500):
  47. # Forward pass: compute predicted y using operations on Tensors; we call our
  48. # custom ReLU implementation using the MyReLU.apply function
  49. y_pred = MyReLU.apply(x.mm(w1)).mm(w2)
  50. # Compute and print loss
  51. loss = (y_pred - y).pow(2).sum()
  52. #print(t, loss.item())
  53. # Use autograd to compute the backward pass.
  54. loss.backward()
  55. with torch.no_grad():
  56. # Update weights using gradient descent
  57. w1 -= learning_rate * w1.grad
  58. w2 -= learning_rate * w2.grad
  59. # Manually zero the gradients after running the backward pass
  60. w1.grad.zero_()
  61. 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. 二进制数据的序列化反序列化和Json的序列化反序列化的重要区别

    前言:最近一个一个很奇怪的问题,很明白的说,就是没看懂,参照下面的代码: /// <summary> /// 反序列化对象 /// </summary> /// <typ ...

  2. 根据点击事件去选取电脑中.rvt文件

    private void button_Click(object sender, RoutedEventArgs e) { //这个选出来是文件夹 //选择文件 var openFileDialog ...

  3. nginx系列10:通过upstream模块选择上游服务器和负载均衡策略round-robin

    upstream模块的使用方法 1,使用upstream和server指令来选择上游服务器 这两个指令的语法如下图: 示例: 2,对上游服务使用keepalive长连接 负载均衡策略round-rob ...

  4. 自己实现的typeOf函数1

    自己实现的typeOf函数:返回传入参数的类型 主要用于解决,js自带的typeof返回结果不精确:Ext JS中typeOf对字符串对象.元素节点.文本节点.空白文本节点判断并不准确的问题 js代码 ...

  5. H5与C3权威指南笔记--transition动画

    translation:过渡 举个栗子:transition: width 1s linear; transition有三个属性,分别是transition-property, transition- ...

  6. 用存储过程向数据库添加大量数据【mysql】

    预分配ID的设计,需要先为数据库生成大量的数据.比如对用户ID有要求的系统,那么用户ID就要预先生成. 通过python,php,c/c++/c#,js等程序生成也是可以,但需要这些程序环境,而且单条 ...

  7. IKAnalyzer结合Lucene实现中文分词

    1.基本介绍 随着分词在信息检索领域应用的越来越广泛,分词这门技术对大家并不陌生.对于英文分词处理相对简单,经过拆分单词.排斥停止词.提取词干的过程基本就能实现英文分词,单对于中文分词而言,由于语义的 ...

  8. C语言面试程序阅读整理

    一.数组和指针 1.数组和指针的存储 写出下面的输出结果: char str1[] = "abc"; char str2[] = "abc"; const ch ...

  9. JS直接调用C#后台方法(ajax调用)

    1. 先手动引用DLL或者通过NuGet查找引用,这里提供一个AjaxPro.2.dll的下载: 2. 之后的的过程不想写了,网上都大同小异的,直接参考以前大佬写的: AjaxPro2完整入门教程 总 ...

  10. 基于nginx搭建yum源服务器

      1.首先关闭防护墙或者设置规则通过且关闭selinux 停止firewall systemctl stop firewalld 禁止firewall开机启动 systemctl disable f ...