# -*- 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. 实验吧-隐写-FIVE1、so beautiful so white(文件头修改)

    FIVE1 下载图片,kali下foremost恢复文件,将得到的图片用Winhex打开进行观察,发现最后面有一段貌似是代码的东西. LS0uLi4gIC4tICAuLi4uLiAgLS0uLi4gI ...

  2. jQuery中:first,:first-child,first()的使用区别

    ul li:first  先获取页面中所有li节点对象数组,然后返回数组中的第一个li节点对象 . :first-child  选择器选取属于其父元素的第一个子元素的所有元素. first() 返回被 ...

  3. selenium2Library无法启动chrome

    使用其他浏览器都没有影响,唯独chrome启动不起来,去掉IE-连接-局域网设置-自动检测设置就OK了

  4. 安装VMtools vim编辑器的使用 压缩包命令 Linux下的用户管理 (第三天)

    VM tools:方便我们虚拟机和宿主机之间复制数据或移动文件等 安装VMtools 1.菜单栏-虚拟机-安装VM tools 将其选中 2.进入系统,在桌面位置里面有VM tools的光盘,双击进入 ...

  5. Rancher第一款Kubernetes操作系统推出

    Rancher实验室推出了业界首款针对Kubernetes的轻量级操作系统k3OS.它具有极低的资源消耗,最小的操作和二级引导,极大地简化了低资源计算环境. Kubernetes操作,提高Kubern ...

  6. (转) Windows如何区分鼠标双击和两次单击

    Windows如何区分鼠标双击和两次单击 http://lbsloveldm.blog.hexun.com/12212875_d.html 在Windows平台上,鼠标左键的按下.松开.快速的两次点击 ...

  7. 个人微信开发API协议(转)

    安卓微信的api,个人微信开发API协议,微信 ipad sdk,微信ipad协议,微信web版接口api,微信网页版接口,微信电脑版sdk,微信开发sdk,微信开发API,微信协议,微信接口文档sd ...

  8. TypeScript——枚举类型

    enum类型是对JavaScript标准数据类型的一个补充. 在运行环境下编译成对象, 可用属性名索引, 也可用属性值索引.而其实现原理为:反向映射 (如下例)   数字枚举 enum Role { ...

  9. comparable接口 和 comparator接口的特点与区别

    1. Comparator 和 Comparable 相同的地方 他们都是java的一个接口, 并且是用来对自定义的class比较大小的. 什么是自定义class: 如 public class Pe ...

  10. vps 跑流量