# -*- coding: utf-8 -*-
"""
View more, visit my tutorial page: https://morvanzhou.github.io/tutorials/
My Youtube Channel: https://www.youtube.com/user/MorvanZhou
Dependencies:
torch: 0.4
matplotlib
""" import torch
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 #第二种方法
net=torch.nn.Sequential(
torch.nn.Linear(2,10),
torch.nn.ReLU(),
torch.nn.Linear(10,2)
)
print(net)

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(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()

classification.py的更多相关文章

  1. Sklearn中二分类问题的交叉熵计算

    二分类问题的交叉熵   在二分类问题中,损失函数(loss function)为交叉熵(cross entropy)损失函数.对于样本点(x,y)来说,y是真实的标签,在二分类问题中,其取值只可能为集 ...

  2. Scikit Learn: 在python中机器学习

    转自:http://my.oschina.net/u/175377/blog/84420#OSC_h2_23 Scikit Learn: 在python中机器学习 Warning 警告:有些没能理解的 ...

  3. python MLP 神经网络使用 MinMaxScaler 没有 StandardScaler效果好

    MLP 64,2  preprocessing.MinMaxScaler().fit(X)                               test confusion_matrix:[[ ...

  4. 菜鸟之路——机器学习之BP神经网络个人理解及Python实现

    关键词: 输入层(Input layer).隐藏层(Hidden layer).输出层(Output layer) 理论上如果有足够多的隐藏层和足够大的训练集,神经网络可以模拟出任何方程.隐藏层多的时 ...

  5. sklearn中的数据预处理----good!! 标准化 归一化 在何时使用

    RESCALING attribute data to values to scale the range in [0, 1] or [−1, 1] is useful for the optimiz ...

  6. [Example of Sklearn] - Example

    reference : http://my.oschina.net/u/175377/blog/84420 目录[-] Scikit Learn: 在python中机器学习 载入示例数据 一个改变数据 ...

  7. pointnet++之classification/train.py

    1.数据集加载 if FLAGS.normal: assert(NUM_POINT<=10000) DATA_PATH = os.path.join(ROOT_DIR, 'data/modeln ...

  8. 【转】Windows下使用libsvm中的grid.py和easy.py进行参数调优

    libsvm中有进行参数调优的工具grid.py和easy.py可以使用,这些工具可以帮助我们选择更好的参数,减少自己参数选优带来的烦扰. 所需工具:libsvm.gnuplot 本机环境:Windo ...

  9. Libsvm:脚本(subset.py、grid.py、checkdata.py) | MATLAB/OCTAVE interface | Python interface

    1.脚本 This directory includes some useful codes: 1. subset selection tools. (子集抽取工具) subset.py 2. par ...

随机推荐

  1. oracle中判断"非"

    在oracle中判断为"非"最常见的两种情况,一个是"不等于",一个的"非空". 通过查找资料得知,oracle中判断不等于的方法有好多种: ...

  2. UVA - 1605 Building for UN (联合国大楼)

    题意:一个联合国大楼每层都有数量相等大小相同的格子,将其分配给n个国家,使任意两个不同的国家都相邻(同层有公共边或相邻层的同一个格子). 分析:可以设计一个只有两层的大楼,第一层每个国家占一行,第二层 ...

  3. 4 react 简书 引入 redux 的 combineReducers 对 redux 数据进行管理

    1. src 下的 common 下的 header 创建 store 文件夹 下创建 reducer.js # src/common/header/store/reducer.js const st ...

  4. Python 日期时间datetime 加一天,减一天,加减一小时一分钟,加减一年

    计算年.月.日需要安装组件包 pip install python-dateutil 当前日期时间 import datetime print datetime.datetime.now() # 20 ...

  5. Python pip换源

    前言 哈喽呀,小伙伴们,晚上好呀,今天要给大家带来点什么呐,我们就来说说python的pip换源吧,这个换源,相对来说,还是比较重要的,能少生好几次气的,哈哈哈 为什么要换源 我们搞python的,肯 ...

  6. 在Centos7下源代码安装配置Nginx

    1.安装前准备开发环境安装pcre开发包:yum install -y pcre-devel 安装编译源码所需的工具和库:yum install gcc gcc-c++ ncurses-devel p ...

  7. Hairpin|Bulge|Loop|假结|共变化(进化)|单序列预测|snRNA|snoRNA|siRNA|microRNA|piRNA|LncRNA|antisense RNAs|cis-NATs|trans-NATs|假基因|环形RNA

    生物信息学 GU也可以配对,即“wobble” pairing GU. Hairpin发夹结构,最少不能少于3个碱基.没有配对 Bulge 单侧配对 Loop双侧配对 假结,游离的leading ed ...

  8. h5-web字体和字体图标

    想要使用可以在: https://www.iconfont.cn/webfont?spm=a313x.7781069.1998910419.d81ec59f2#!/webfont/index :是we ...

  9. KVM以及其虚拟机安装

    一.KVM安装 安装:yum -y install kvm python-virtinst libvirt tunctl bridge-utils virt-manager qemu-kvm-tool ...

  10. 80.常用的返回QuerySet对象的方法使用详解:order_by

    order_by: 将模型生成的表按照某个字段进行排序,默认情况下,按照升序的顺序排序,如果想要按照降序的顺序排序可以在字段的前面加一个"-",加一个负号就可以进行反转. mode ...