用pytorch1.0搭建简单的神经网络:进行多分类分析

import torch
import torch.nn.functional as F # 包含激励函数
import matplotlib.pyplot as plt # 假数据
# make fake data
n_data = torch.ones(100, 2)
x0 = torch.normal(2*n_data, 1) # class0 x data (tensor), shape=(100, 2)
y0 = torch.zeros(100) # class0 y data (tensor), shape=(100, 1)
x1 = torch.normal(-2*n_data, 1) # class1 x data (tensor), shape=(100, 2)
y1 = torch.ones(100) # class1 y data (tensor), shape=(100, 1)
# 注意 x, y 数据的数据形式是一定要像下面一样 (torch.cat 是合并数据)
x = torch.cat((x0, x1), 0).type(torch.FloatTensor) # shape (200, 2) FloatTensor = 32-bit floating
y = torch.cat((y0, y1), ).type(torch.LongTensor) # shape (200,) LongTensor = 64-bit integer # The code below is deprecated in Pytorch 0.4. Now, autograd directly supports tensors
# x, y = Variable(x), Variable(y)
# 画散点图
plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=y.data.numpy(), s=100, lw=0, cmap='RdYlGn')
plt.show() # 建立神经网络
# 先定义所有的层属性(__init__()), 然后再一层层搭建(forward(x))层于层的关系链接
class Net(torch.nn.Module):
def __init__(self, n_feature, n_hidden, n_output):
super(Net, self).__init__() # 继承 __init__ 功能
# 定义每层用什么样的形式
self.hidden = torch.nn.Linear(n_feature, n_hidden) # hidden layer
self.out = torch.nn.Linear(n_hidden, n_output) # output layer def forward(self, x): # 这同时也是 Module 中的 forward 功能
# 正向传播输入值, 神经网络分析出输出值
x = F.relu(self.hidden(x)) # activation function for hidden layer
x = self.out(x)
return x net = Net(n_feature=2, n_hidden=10, n_output=2) # define the network
print(net) # net architecture == 显示神经网络结构
# Net(
# (hidden): Linear(in_features=2, out_features=10, bias=True)
# (out): Linear(in_features=10, out_features=2, bias=True)
# )
# 搭建完神经网络后,对 神经网路参数(net.parameters()) 进行优化
# (1.选择优化器 optimizer 是训练的工具
optimizer = torch.optim.SGD(net.parameters(), lr=0.02) # 传入 net 的所有参数, 学习率
# (2.选择优化的目标函数
loss_func = torch.nn.CrossEntropyLoss() # the target label is NOT an one-hotted plt.ion() # something about plotting
# (3.开始训练网络
for t in range(100):
out = net(x) # input x and predict based on x # 喂给 net 训练数据 x, 输出预测值
loss = loss_func(out, y) # must be (1. nn output, 2. target), the target label is NOT one-hotted # 计算两者的误差 optimizer.zero_grad() # clear gradients for next train # 清空上一步的残余更新参数值
loss.backward() # backpropagation, compute gradients # 误差反向传播, 计算参数更新值
optimizer.step() # apply gradients # 将参数更新值施加到 net 的 parameters 上 if t % 2 == 0:
# plot and show learning process
plt.cla()
# 过了一道 softmax 的激励函数后的最大概率才是预测值
prediction = torch.max(out, 1)[1]
pred_y = prediction.data.numpy()
target_y = y.data.numpy()
plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=pred_y, s=100, lw=0, cmap='RdYlGn')
accuracy = float((pred_y == target_y).astype(int).sum()) / float(target_y.size) # 预测中有多少和真实值一样
plt.text(1.5, -4, 'Accuracy=%.2f' % accuracy, fontdict={'size': 20, 'color': 'red'})
plt.pause(0.1) plt.ioff()
plt.show()

用pytorch1.0搭建简单的神经网络:进行多分类分析的更多相关文章

  1. 用pytorch1.0搭建简单的神经网络:进行回归分析

    搭建简单的神经网络:进行回归分析 import torch import torch.nn.functional as F # 包含激励函数 import matplotlib.pyplot as p ...

  2. 用pytorch1.0快速搭建简单的神经网络

    用pytorch1.0搭建简单的神经网络 import torch import torch.nn.functional as F # 包含激励函数 # 建立神经网络 # 先定义所有的层属性(__in ...

  3. 神经网络一(用tensorflow搭建简单的神经网络并可视化)

    import tensorflow as tf import numpy as np import matplotlib.pyplot as plt #创建一个input数据,-1到1之间300个数, ...

  4. python日记:用pytorch搭建一个简单的神经网络

    最近在学习pytorch框架,给大家分享一个最最最最基本的用pytorch搭建神经网络并且训练的方法.本人是第一次写这种分享文章,希望对初学pytorch的朋友有所帮助! 一.任务 首先说下我们要搭建 ...

  5. Python实现一个简单三层神经网络的搭建并测试

    python实现一个简单三层神经网络的搭建(有代码) 废话不多说了,直接步入正题,一个完整的神经网络一般由三层构成:输入层,隐藏层(可以有多层)和输出层.本文所构建的神经网络隐藏层只有一层.一个神经网 ...

  6. pytorch1.0批训练神经网络

    pytorch1.0批训练神经网络 import torch import torch.utils.data as Data # Torch 中提供了一种帮助整理数据结构的工具, 叫做 DataLoa ...

  7. pytorch1.0神经网络保存、提取、加载

    pytorch1.0网络保存.提取.加载 import torch import torch.nn.functional as F # 包含激励函数 import matplotlib.pyplot ...

  8. 使用pytorch快速搭建神经网络实现二分类任务(包含示例)

    使用pytorch快速搭建神经网络实现二分类任务(包含示例) Introduce 上一篇学习笔记介绍了不使用pytorch包装好的神经网络框架实现logistic回归模型,并且根据autograd实现 ...

  9. 从环境搭建到回归神经网络案例,带你掌握Keras

    摘要:Keras作为神经网络的高级包,能够快速搭建神经网络,它的兼容性非常广,兼容了TensorFlow和Theano. 本文分享自华为云社区<[Python人工智能] 十六.Keras环境搭建 ...

随机推荐

  1. Python逆向(三)—— Python编译运行及反汇编

    一.前言 前期我们已经对python的运行原理以及运行过程中产生的文件结构有了了解.本节,我们将结合具体的例子来实践python运行,编译,反编译的过程,并对前些章节中可能遗漏的具体细节进行补充. 二 ...

  2. JS 中的prototype、__proto__与constructor

    我们需要牢记两点: ①__proto__和constructor属性是对象所独有的: ② prototype属性是函数所独有的,因为函数也是一种对象,所以函数也拥有__proto__和construc ...

  3. rocketMq和kafka的架构区别

    概述 其实一直想写一篇rocketMq和kafka在架构设计上的差别,但是一直有个问题没搞明白所以迟迟没动手,今天无意中听人点播了一下似乎明白了这个问题,所以就有了这篇对比. 这篇博文主要讲清楚kaf ...

  4. leaflet地图框架

    leaflet 中文API LeafLet js 官网:http://leafletjs.com/index.html LeafLet js 官网demo: http://leafletjs.com/ ...

  5. freemark 异常

    现象: 前几天跟前端联调,freemark报异常如下: For "#if" condition: Expected a boolean, but this has evaluate ...

  6. css 文本省略号显示

    文本省略号是非常常见的需求,而省略号展示又通常分为俩种情况折行和不折行.不折行: div { white-space:nowrap;/* 规定文本是否折行 */ overflow: hidden;/* ...

  7. Windows安装Redis并添加本地自启动服务并解决客户端dll报错

    参考文章:https://blog.csdn.net/realjh/article/details/82026160 Redis下载: https://github.com/MicrosoftArch ...

  8. 阿里重磅开源在线分析诊断工具Arthas(阿尔萨斯)

    github地址: Arthas English version goes here. Arthas 是Alibaba开源的Java诊断工具,深受开发者喜爱. 当你遇到以下类似问题而束手无策时,Art ...

  9. linux非root用户安装5.7.27版本mysql

    先下安装包,到mysql官网https://dev.mysql.com/downloads/mysql/选好安装包版本.操作系统类型(默认是最新版本,点击右边链接Looking for previou ...

  10. Qt编写气体安全管理系统10-数据导出

    一.前言 数据导出一般指导出到excel表格,可能有部分用户还需要导出到pdf,因为pdf基本上不可编辑,防止用户重新编辑导出的数据,excel可能绝大部分用过电脑的人都知道,广为流行,主要就是微软的 ...