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 ...
随机推荐
- 哈希(hash)理解
转载自https://www.cnblogs.com/mingaixin/p/4318837.html 一.什么是哈希?(一种更复杂的映射) Hash,一般翻译做“散列”,也有直接音译为“哈希”的,就 ...
- Day 22:网络编程(3)
TCP通讯协议特点: 1. tcp是基于IO流进行数据 的传输的,面向连接. 2. tcp进行数据传输的时候是没有大小限制的. 3. tcp是面向连接,通过三次握手的机制保证数据的完整性.可靠协 ...
- python运算表达式
运算符1.算术运算符:+,-,*,/,//(求整商),%,**(求多次方,左边为数,右边为多少次方)2.关系运算符:>,<,==,<=,>=,!=3.测试运算:in,not i ...
- API网关,让您和Serverless再近一步
从软件行业诞生之日起,技术和业务总是相辅相成.业务的创新促进着软件架构从最早期的单体架构.分布式架构,转变到了如今火热的微服务架构,以及云时代下诞生的Serverless架构.API网关作为单体应用和 ...
- python print %s 号格式化输出
python %号格式化输出: 一种字符串格式化的语法, 基本用法是将值插入到%s占位符的字符串中. %s,表示格式化一个对象为字符 "%±(正负号表示)3(数字表示字符串的长度)s&quo ...
- MySQL笔记 02
SQL对表中数据的CRUD操作: 插入数据: insert into 表名 (列名1,列名2,....) values (值1,值2,....): 插入部分: insert into xuesheng ...
- 在Linux下 MySQL错误 ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES) 解决办法【很管用】
一般这个错误是由密码错误引起,解决的办法自然就是重置密码. 假设我们使用的是root账户. 1.重置密码的第一步就是跳过MySQL的密码认证过程,方法如下: #vim /etc/my.cnf(注:wi ...
- VMWare WorkStation15--Win10下开机启动虚拟机
参考 https://www.cnblogs.com/qmfsun/p/6284236.html http://www.cnblogs.com/eliteboy/p/7838091.html VMWa ...
- DRF项目之解决浏览器同源策略问题
DRF项目,是一个前后端分离的Web框架. 本项目中,我们前端采用的是VUE框架. 前后端分离的情况就会出现一个问题,前端的Ajax请求无法请求到后端API(接口). 那么,为什么会出现这种问题呢? ...
- Python笔记_第五篇_Python数据分析基础教程_文件的读写
1. 读写文件(基本) savetxt.loadtxt i2 = np.eye(2) print(i2) np.savetxt(r"C:\Users\Thomas\Desktop\eye.t ...