import torch
from torch.autograd import Variable
import torch.nn.functional as F
import matplotlib.pyplot as plt n_data = torch.ones(100, 2) # 100个具有2个属性的数据 shape=(100,2)
x0 = torch.normal(2*n_data, 1) # 根据原始数据生成随机数据,第一个参数是均值,第二个是方差,这里设置为1了,shape=(100,2)
y0 = torch.zeros(100) # 100个0作为第一类数据的标签,shape=(100,1)
x1 = torch.normal(-2*n_data, 1)
y1 = torch.ones(100) x = torch.cat((x0, x1), 0).type(torch.FloatTensor) # cat数据合并 32-bit floating
y = torch.cat((y0, y1), 0).type(torch.LongTensor) # 64-bit integer x, y = Variable(x), Variable(y) plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], s=100, lw=0)
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)
self.predict = torch.nn.Linear(n_hidden, n_output) def forward(self, x):
x = F.relu(self.hidden(x))
x = self.predict(x)
return x net = Net(2, 10, 2) # 数据是二维的所以输入特征是2,输出是两种类别所以输出层特征是2
print(net)
> Net(
> (hidden): Linear(in_features=2, out_features=10, bias=True)
> (predict): Linear(in_features=10, out_features=2, bias=True)
> )
# plt.ion()
plt.show() optimizer = torch.optim.SGD(net.parameters(), lr=0.02)
loss_func = torch.nn.CrossEntropyLoss() # 交叉熵 CrossEntropy [0.1, 0.2, 0.7] [0,0,1] 数据越大,是这一类的概率越大 for t in range(100):
out = net.forward(x) # 数据经过所有的网络,输出预测值 loss = loss_func(out, y) # 输入与预测值之间的误差loss optimizer.zero_grad() # 梯度重置
loss.backward() # 损失值反向传播,计算梯度
optimizer.step() # 梯度优化 if t % 2 == 0:
# 画图部分 plot and show learning process
plt.cla()
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.5) # plt.ioff()
plt.show()

END

pytorch 5 classification 分类的更多相关文章

  1. tensorflow学习之(九)classification 分类问题之分类手写数字0-9

    #classification 分类问题 #例子 分类手写数字0-9 import tensorflow as tf from tensorflow.examples.tutorials.mnist ...

  2. pytorch -- CNN 文本分类 -- 《 Convolutional Neural Networks for Sentence Classification》

    论文  < Convolutional Neural Networks for Sentence Classification>通过CNN实现了文本分类. 论文地址: 666666 模型图 ...

  3. pytorch解决鸢尾花分类

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

  4. pytorch实现LeNet5分类CIFAR10

    关于LeNet-5 LeNet5的Pytorch实现在网络上已经有很多了,这里记录一下自己的实现方法. LeNet-5出自于Gradient-Based Learning Applied to Doc ...

  5. 用Pytorch训练MNIST分类模型

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

  6. 【caffe范例详解】 - 1.Classification分类

    1. 安装 首先,导入numpy和matplotlib库 # numpy是常用的科学计算库,matplot是常用的绘图库 import numpy as np import matplotlib.py ...

  7. pytorch之 classification

    import torch import torch.nn.functional as F import matplotlib.pyplot as plt # torch.manual_seed(1) ...

  8. pytorch 文本情感分类和命名实体识别NER中LSTM输出的区别

    文本情感分类: 文本情感分类采用LSTM的最后一层输出 比如双层的LSTM,使用正向的最后一层和反向的最后一层进行拼接 def forward(self,input): ''' :param inpu ...

  9. pytorch LSTM情感分类全部代码

    先运行main.py进行文本序列化,再train.py模型训练 dataset.py from torch.utils.data import DataLoader,Dataset import to ...

随机推荐

  1. poj 2914&&hdu 3002 全局最小割Stoer-Wagner算法模板

    #include<stdio.h> #include<string.h> #include<iostream> #define inf 0x3fffffff #de ...

  2. 工具-VIM常用快捷键

    使用vs code 的插件 amvim来快速编辑代码,要熟记下面的命令 由normal模式切换到insert模式的命令键 i 在光标左侧输入正文 I 在光标所在行的行首输入正文 a 在光标右侧输入正文 ...

  3. [SharePoint2010开发入门经典]一、SPS2010介绍

    本章概要: 1.熟悉SPS基本特性 2.理解SPS基础架构 3.开发SPS工具

  4. 浙大PAT考试1013~1016(最伤的一次。。)

    我能说我1016WA了几天都不得最后还是拿别人代码交的么. .. 真心找不到那个神数据.. . 自己把整个程序的流程都画出来了.细致推敲是木有问题的啊... 题目地址:点击打开链接 先从1013開始介 ...

  5. POJ 1777

    一道好题. 由算术基本定理,知: 那么,对于上式的每个因子值只能是2^M的形式.取第一个式子为例,通过分解因式出(1+p^2)=2^k知,a只能为1. 于是对于p只能是梅森素数.而且每个梅森素数只能出 ...

  6. 【POJ 2942】Knights of the Round Table(双联通分量+染色判奇环)

    [POJ 2942]Knights of the Round Table(双联通分量+染色判奇环) Time Limit: 7000MS   Memory Limit: 65536K Total Su ...

  7. unity3d面试题摘选(全)

    ======================================= 数据结构和算法非常重要.图形学也非常重要! 大的游戏公司非常看重个人基础.综合能力.也有的看重你实际工作能力,看你的De ...

  8. poj2947Widget Factory

    对于同余方程的高斯消元啊. 其实也差不多吧.先同一位通分,然后减一下就好了. 主要是判无解和多解的麻烦,需要注意即使有自由元也可能先无解 #include<cstdio> #include ...

  9. win10中让Visual Studio默认使用Administrator权限运行

    https://stackoverflow.com/questions/9654833/how-to-run-visual-studio-as-administrator-by-default Win ...

  10. page template in kentico

    Ad-hoc templates are used for one page only, for which they were created - this is why they are not ...