classification.py
# -*- 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的更多相关文章
- Sklearn中二分类问题的交叉熵计算
		二分类问题的交叉熵 在二分类问题中,损失函数(loss function)为交叉熵(cross entropy)损失函数.对于样本点(x,y)来说,y是真实的标签,在二分类问题中,其取值只可能为集 ... 
- Scikit Learn: 在python中机器学习
		转自:http://my.oschina.net/u/175377/blog/84420#OSC_h2_23 Scikit Learn: 在python中机器学习 Warning 警告:有些没能理解的 ... 
- python MLP 神经网络使用 MinMaxScaler 没有 StandardScaler效果好
		MLP 64,2 preprocessing.MinMaxScaler().fit(X) test confusion_matrix:[[ ... 
- 菜鸟之路——机器学习之BP神经网络个人理解及Python实现
		关键词: 输入层(Input layer).隐藏层(Hidden layer).输出层(Output layer) 理论上如果有足够多的隐藏层和足够大的训练集,神经网络可以模拟出任何方程.隐藏层多的时 ... 
- sklearn中的数据预处理----good!! 标准化 归一化 在何时使用
		RESCALING attribute data to values to scale the range in [0, 1] or [−1, 1] is useful for the optimiz ... 
- [Example of Sklearn] -  Example
		reference : http://my.oschina.net/u/175377/blog/84420 目录[-] Scikit Learn: 在python中机器学习 载入示例数据 一个改变数据 ... 
- pointnet++之classification/train.py
		1.数据集加载 if FLAGS.normal: assert(NUM_POINT<=10000) DATA_PATH = os.path.join(ROOT_DIR, 'data/modeln ... 
- 【转】Windows下使用libsvm中的grid.py和easy.py进行参数调优
		libsvm中有进行参数调优的工具grid.py和easy.py可以使用,这些工具可以帮助我们选择更好的参数,减少自己参数选优带来的烦扰. 所需工具:libsvm.gnuplot 本机环境:Windo ... 
- 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 ... 
随机推荐
- C#重写窗体的方法
			using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ... 
- hdu1222Wolf and Rabbit (公约数的巧题)
			一个很坑的问题,想到点子上很好解决,想不到的话头破也不一定能做出来. There is a hill with n holes around. The holes are signed from 0 ... 
- Day 20:网络编程(1)
			什么是计算机网络? 指的是分布在不同地域的计算机,通过外部设备连接起来,实现资源共享与数据传输的计算机系统. 通信三要素: IP: IP地址 Internet上的每台主机(Host)都有一个唯一的IP ... 
- 部署Ambari Server实战案例
			部署Ambari Server实战案例 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.准备三台虚拟机(需要自行安装jdk环境) 1>.角色分配 NameNode节点: h ... 
- MFC工程合并
			假使有两个工程,分别为工程A和工程B. 第一步:把A中.rc文件中的 两张图中间的对话框资源拷贝出来,粘贴到B工程中的.rc资源文件中,也是两张图中间 第二步:打开工程-----VIEW------R ... 
- windows driver 驱动程序我的下载地址
			http://download.csdn.net/detail/sz76211822/8197619 版权声明:本文为博主原创文章,未经博主允许不得转载. 
- 从华硕裁员、分拆业务看传统PC企业转型到底有多难?
			近段时间,华硕的处境可谓"冰火两重天".一方面,华硕正式发布ROG游戏手机.这款手机以超强性能和华丽外观,让游戏玩家群体为之沸腾.即使最高售价高达12999元,还是有不少玩家趋之若 ... 
- PHP - 验证码制作加验证
			一,主页 index.php <!DOCTYPE html> <html lang="en"> <head> <meta charse ... 
- Java查漏补缺(3)(面向对象相关)
			Java查漏补缺(3) 继承·抽象类·接口·静态·权限 相关 this与super关键字 this的作用: 调用成员变量(可以用来区分局部变量和成员变量) 调用本类其他成员方法 调用构造方法(需要在方 ... 
- Arduino学习——u8glib提供的字体样式
			Fonts, Capital A Height4 Pixel Height U8glib Font FontStruct5 Pixel Height 04 Font 04 Font 04 Font ... 
