以下我们用 PyTorch 实现一个很简单的二分类器,所用的数据来自 Scikit learn。

首先来生成含200个样本的数据,并绘制出样本的散点图如下图所示:

import matplotlib.pyplot as plt
from sklearn.cluster import SpectralClustering
import sklearn.datasetsX,y = sklearn.datasets.make_moons(200,noise=0.2)plt.scatter(X[:,0],X[:,1],s=40,c=y,cmap=plt.cm.Spectral)
<matplotlib.collections.PathCollection at 0x149ce908>

可以看到生成了两类数据,分别用 0 和 1 来表示。我们接下来将要在这个样本数据上构造一个分类器,采用的是一个很简单的全连接网络,网络结构如下:

这个网络包含一个输入层,一个中间层,一个输出层。中间层包含 3 个神经元,使用的激活函数是 tanh。当然,中间层的神经元越多,分类效果一般越好,但这个 3 层的网络对于我们的样本数据已经足够用了。我们来算一下参数数量:上图中一共有 6+6 = 12 条线,就是 12 个权重,加上 3+ 2 = 5 个 bias,一共 17 个参数需要训练。

接下来将样本数据从 numpy 转成 tensor:

X = torch.from_numpy(X).type(torch.FloatTensor)
y = torch.from_numpy(y).type(torch.LongTensor)

开始构建神经网络,其中损失函数用交叉熵损失函数,梯度优化器用Adam。

import torch.nn as nn
import torch.nn.functional as Fclass MyClassifier(nn.Module):def __init__(self):super(MyClassifier,self).__init__()self.fc1 = nn.Linear(2,3)self.fc2 = nn.Linear(3,2)def forward(self,x):x = self.fc1(x)x = F.tanh(x)x = self.fc2(x)return xdef predict(self,x):pred = F.softmax(self.forward(x))ans = []for t in pred:if t[0]>t[1]:ans.append(0)else:ans.append(1)return torch.tensor(ans)
model = Net()
criterion = nn.CrossEntropyLoss()  #交叉熵损失函数
optimizer = torch.optim.Adam(model.parameters(), lr=0.01) #Adam梯度优化器

训练:

epochs = 10000
losses = []
for i in range(epochs):y_pred = model.forward(X)loss = criterion(y_pred,y)losses.append(loss.item())optimizer.zero_grad()loss.backward()optimizer.step()

查看训练误差:

from sklearn.metrics import accuracy_score
print(accuracy_score(model.predict(X),y))# Output
0.995

下面的函数帮助我们在两个分类之间画一条分界线,便于将结果可视化。

def predict(x):x = torch.from_numpy(x).type(torch.FloatTensor)ans = model.predict(x)return ans.numpy()def plot_decision_boundary(pred_func,X,y):x_min, x_max = X[:, 0].min() - .5, X[:, 0].max()+ .5y_min, y_max = X[:, 1].min() - .5, X[:, 1].max()+ .5h = 0.01xx,yy=np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))Z = pred_func(np.c_[xx.ravel(), yy.ravel()])Z = Z.reshape(xx.shape)plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.binary)

分类结果:

plot_decision_boundary(lambda x : predict(x) ,X.numpy(), y.numpy())

完整代码参见参考资料2,简单二分类器结果如下图所示 。

import sklearn.datasets
import torch
import numpy as npnp.random.seed(0)
X, y = sklearn.datasets.make_moons(200,noise=0.2)import matplotlib.pyplot as pltplt.scatter(X[:,0],X[:,1],s=40,c=y,cmap=plt.cm.binary)X = torch.from_numpy(X).type(torch.FloatTensor)
y = torch.from_numpy(y).type(torch.LongTensor)import torch.nn as nn
import torch.nn.functional as F#our class must extend nn.Module
class Net(nn.Module):def __init__(self):super(Net,self).__init__()#Our network consists of 3 layers. 1 input, 1 hidden and 1 output layer#This applies Linear transformation to input data. self.fc1 = nn.Linear(2,3)#This applies linear transformation to produce output dataself.fc2 = nn.Linear(3,2)#This must be implementeddef forward(self,x):#Output of the first layerx = self.fc1(x)#Activation function is Relu. Feel free to experiment with thisx = F.tanh(x)#This produces outputx = self.fc2(x)return x#This function takes an input and predicts the class, (0 or 1)        def predict(self,x):#Apply softmax to outputpred = F.softmax(self.forward(x))ans = []for t in pred:if t[0]>t[1]:ans.append(0)else:ans.append(1)return torch.tensor(ans)#Initialize the model
model = Net()
#Define loss criterion
criterion = nn.CrossEntropyLoss()
#Define the optimizer
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)#Number of epochs
epochs = 50000
#List to store losses
losses = []
for i in range(epochs):#Precit the output for Given inputy_pred = model.forward(X)#Compute Cross entropy lossloss = criterion(y_pred,y)#Add loss to the listlosses.append(loss.item())#Clear the previous gradientsoptimizer.zero_grad()#Compute gradientsloss.backward()#Adjust weightsoptimizer.step()from sklearn.metrics import accuracy_score
print(accuracy_score(model.predict(X),y))def predict(x):x = torch.from_numpy(x).type(torch.FloatTensor)ans = model.predict(x)return ans.numpy()# Helper function to plot a decision boundary.
# If you don't fully understand this function don't worry, it just generates the contour plot below.
def plot_decision_boundary(pred_func,X,y):# Set min and max values and give it some paddingx_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5h = 0.01# Generate a grid of points with distance h between themxx,yy=np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))# Predict the function value for the whole gidZ = pred_func(np.c_[xx.ravel(), yy.ravel()])Z = Z.reshape(xx.shape)# Plot the contour and training examplesplt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.binary)plot_decision_boundary(lambda x : predict(x) ,X.numpy(), y.numpy())
# Output result:0.97

参考资料:

1. https://www.pytorchtutorial.com/pytorch-simple-classifier/

2. https://github.com/prudvinit/MyML/blob/master/lib/neural%20networks/pytorch%20moons.py

3. https://scikit-learn.org/stable/modules/classes.html#module-sklearn.cluster

Pytorch实现二分类器相关推荐

  1. ML之分类预测之ElasticNet:利用ElasticNet回归对二分类数据集构建二分类器(DIY交叉验证+分类的两种度量PK)

    ML之分类预测之ElasticNet:利用ElasticNet回归对二分类数据集构建二分类器(DIY交叉验证+分类的两种度量PK) 目录 输出结果 设计思路 核心代码 输出结果 设计思路 核心代码 # ...

  2. PyTorch系列 (二): pytorch数据读取自制数据集并

    PyTorch系列 (二): pytorch数据读取 PyTorch 1: How to use data in pytorch Posted by WangW on February 1, 2019 ...

  3. 如何用PyTorch训练图像分类器

    本文为 AI 研习社编译的技术博客,原标题 : How to Train an Image Classifier in PyTorch and use it to Perform Basic Infe ...

  4. 【机器学习】scikitLearn分类任务以mnist为例,训练二分类器并衡量性能指标:ROC及PR曲线

    分类相关导航: [机器学习]分类任务以mnist为例,数据集准备及预处理 [机器学习]scikitLearn分类任务以mnist为例,训练二分类器并衡量性能指标:ROC及PR曲线 [机器学习]scik ...

  5. 基于pytorch的softmax分类器

    一.概述 本文在pytorch的框架下,基于softmax分类器的原理,给出softmax分类器的源码,实现图像的分类.结合代码阐述神经网络的搭建过程,用测试集检验神经网络的训练结果,最后在本文末给出 ...

  6. 使用Pytorch构建一个分类器(CIFAR10模型)

    分类器任务和数据介绍 ·构建一个将不同图像进行分类的神经网络分类器,对输入的的图片进行判别并完成分类. ·本案例采用CIFAR10数据集作为原始图片数据 ·CIFAR10数据集介绍:数据集中每张图片的 ...

  7. 使用pytorch构建图片分类器

    分类器任务和数据介绍 构造一个将不同图像进行分类的神经网络分类器, 对输入的图片进行判别并完成分类. 本案例采用CIFAR10数据集作为原始图片数据. CIFAR10数据集介绍: 数据集中每张图片的尺 ...

  8. 使用PyTorch训练图像分类器

    训练分类器 2019年年初,ApacheCN组织志愿者翻译了PyTorch1.0版本中文文档(github地址),同时也获得了PyTorch官方授权,我相信已经有许多人在中文文档官网上看到了.不过目前 ...

  9. DL知识拾贝(Pytorch)(二):DL元素之一:激活函数

    文章目录 1. 典型激活函数及进阶 1.1 Sigmoid 1.2 Tanh 1.3 ReLU及其变种 1.3.1 ReLU 1.3.2 Leaky ReLU 1.3.3 PReLU 1.3.4 RR ...

最新文章

  1. C标准中一些预定义的宏,如__FILE__,__func__等
  2. return 返回值的问题
  3. Android手势的识别
  4. JSP和FreeMarker的比较
  5. java jsp 特殊标签_JSP复习(四):JSTL标记
  6. python dataframe去除重复项_python - Pandas DataFrame处理查找DataFrame中的重复项 - 堆栈内存溢出...
  7. 制造业数字化转型的启明星——低代码开发平台
  8. 急救: Autodesk MapGuide Studio - Preview在MapGuide Open Source环境不能进行中文标注
  9. 社工必备查询网址汇总
  10. 【运筹学】线性规划数学模型 ( 求解基矩阵示例 | 矩阵的可逆性 | 线性规划表示为 基矩阵 基向量 非基矩阵 非基向量 形式 )
  11. 大数据入门最全组件思维导图
  12. sql登录名和用户名_通过分配角色和权限来移动或复制SQL登录名
  13. Chrome将网页保存为图片、PDF
  14. Unity 3分钟,将你的Terrin 地形转为FBX
  15. 【时间之外】面向监狱的编程?该学学网络安全法了(3)
  16. [PHP响应式营销型万能H5建站系统源码] 免费开源建站利器+可视化自由布局页面
  17. 牛津3000词汇表(The Oxford 3000™)
  18. 动手学数据分析-数据可视化
  19. 如何使用html代码给文字加边框?
  20. 加一度教你如何做好百度竞价数据分析

热门文章

  1. 基于SM3的HMAC算法的实现
  2. Nginx安装与使用(配置详解)
  3. 转载系列【检测】| CVPR2020:Bridging the Gap Between Anchor-based and Anchor-free Detection via Adaptive Trai
  4. Windows10系统22H2安装AX201蓝牙出现叹号问题解决思路(iPhone13联机同样解决)
  5. Android服务器——TomCat服务器的搭建 配置TomCat环境变量
  6. Word处理控件Aspose.Words功能演示:使用 C# 将 DOCX 转换为 HTML
  7. stty 命令说明及使用讲解
  8. Pygame游戏之 合金弹头
  9. spring-data-redis整合redis集群配置
  10. 亲,你有一份 ChatGPT4 的体验机会待查收! 一站式 AI 工具箱 - Poe 介绍