import torch
from torch.autograd import Variable
import torch.nn.functional as F
import matplotlib.pyplot as plt # torch.manual_seed(1) # reproducible # 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 = 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() class Net(torch.nn.Module):
def __init__(self, n_feature, n_hidden, n_output):
super(Net, self).__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):
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 optimizer = torch.optim.SGD(net.parameters(), lr=0.02)
loss_func = torch.nn.CrossEntropyLoss() # the target label is NOT an one-hotted
#分类输出的为概率 plt.ion() # something about plotting for t in range(100):
out = net(x) # input x and predict based on 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 if t % 2 == 0:
# plot and show learning process
plt.cla()
prediction = torch.max(F.softmax(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()

输出结果是将散点图分为两类。

torch分类问题的更多相关文章

  1. 『PyTorch』第四弹_通过LeNet初识pytorch神经网络_下

    『PyTorch』第四弹_通过LeNet初识pytorch神经网络_上 # Author : Hellcat # Time : 2018/2/11 import torch as t import t ...

  2. 30个深度学习库:按Python、C++、Java、JavaScript、R等10种语言分类

    30个深度学习库:按Python.C++.Java.JavaScript.R等10种语言分类 包括 Python.C++.Java.JavaScript.R.Haskell等在内的一系列编程语言的深度 ...

  3. PyTorch官方中文文档:torch.nn

    torch.nn Parameters class torch.nn.Parameter() 艾伯特(http://www.aibbt.com/)国内第一家人工智能门户,微信公众号:aibbtcom ...

  4. 深度学习之 cnn 进行 CIFAR10 分类

    深度学习之 cnn 进行 CIFAR10 分类 import torchvision as tv import torchvision.transforms as transforms from to ...

  5. [深度应用]·实战掌握PyTorch图片分类简明教程

    [深度应用]·实战掌握PyTorch图片分类简明教程 个人网站--> http://www.yansongsong.cn/ 项目GitHub地址--> https://github.com ...

  6. 用Pytorch训练MNIST分类模型

    本次分类问题使用的数据集是MNIST,每个图像的大小为\(28*28\). 编写代码的步骤如下 载入数据集,分别为训练集和测试集 让数据集可以迭代 定义模型,定义损失函数,训练模型 代码 import ...

  7. 学习笔记CB012: LSTM 简单实现、完整实现、torch、小说训练word2vec lstm机器人

    真正掌握一种算法,最实际的方法,完全手写出来. LSTM(Long Short Tem Memory)特殊递归神经网络,神经元保存历史记忆,解决自然语言处理统计方法只能考虑最近n个词语而忽略更久前词语 ...

  8. pytorch解决鸢尾花分类

    半年前用numpy写了个鸢尾花分类200行..每一步计算都是手写的  python构建bp神经网络_鸢尾花分类 现在用pytorch简单写一遍,pytorch语法解释请看上一篇pytorch搭建简单网 ...

  9. [转] Torch中实现mini-batch RNN

    工作中需要把一个SGD的LSTM改造成mini-batch的LSTM, 两篇比较有用的博文,转载mark https://zhuanlan.zhihu.com/p/34418001 http://ww ...

随机推荐

  1. .NET 开源项目 Anet 介绍

    使用 Anet 有一段时间了,已经在我的个人网站(如 bookist.cc)投入使用,目前没有发现什么大问题,所以才敢写篇文章向大家介绍. GitHub 地址:https://github.com/a ...

  2. FAST MONTE CARLO ALGORITHMS FOR MATRICES II (快速的矩阵分解策略)

    目录 问题 算法 LINEARTIMESVD 算法 CONSTANTTIMESVD 算法 理论 算法1的理论 算法2 的理论 代码 Drineas P, Kannan R, Mahoney M W, ...

  3. ondaHTTPError: HTTP 000 CONNECTION FAILED for url

    可能是网络问题,换网络. 可能是获取库的IP无法链接到,换库的IP,如添加清华镜像IP等.

  4. css实现多行文本溢出显示省略号(…)

    WebKit浏览器或移动端的页面在WebKit浏览器或移动端(绝大部分是WebKit内核的浏览器)的页面实现比较简单,可以直接使用WebKit的CSS扩展属性(WebKit是私有属性)-webkit- ...

  5. centos7只rsync+inotify

    环境: 操作系统:centos7.4 192.168.1.238 客户端 192.168.1.239 服务端 环境准备: 1.安装以下安装包lrzsz是xshell上传下载的安装包,可以忽略. yum ...

  6. 安装mysql8.0出现服务无法启动,服务没报告任何错误

    改为net start mysql80 参考https://blog.csdn.net/gzejia/article/details/82156994

  7. JS流程控制

    1.if...else... //if 语句:只有当指定条件为 true 时,该语句才会执行代码. //语法 if (condition) { 当条件为 true 时执行的代码 } //if...el ...

  8. 安全工具acunetix使用

    今天来主要介绍了安全测试工具AWVS(acunetix web vulnerability scanner)的使用 1)  安装包的下载地址:https://github.com/jiyanjiao/ ...

  9. python学习日记(内置、匿名函数练习题)

    用map来处理字符串列表 用map来处理字符串列表,把列表中所有水果都变成juice,比方apple_juice fruits=['apple','orange','mango','watermelo ...

  10. Bigtable:A Distributed Storage System for Strctured Data

    2006 年10 月Google 发布三架马车之一的<Bigtable:A Distributed Storage System for Strctured Data>论文之后,Power ...