首页 > 其他分享 >2、点分类任务

2、点分类任务

时间:2023-09-25 20:44:09浏览次数:30  
标签:self 分类 mask print 任务 test model data

1、Cora dataset(数据集描述:Yang et al. (2016))

  • 论文引用数据集,每一个点有1433维向量
  • 最终要对每个点进行7分类任务(每个类别只有20个点有标注)
from torch_geometric.datasets import Planetoid#下载数据集用的
from torch_geometric.transforms import NormalizeFeatures

dataset = Planetoid(root='data/Planetoid', name='Cora', transform=NormalizeFeatures())#transform预处理

print()
print(f'Dataset: {dataset}:')
print('======================')
print(f'Number of graphs: {len(dataset)}')
print(f'Number of features: {dataset.num_features}')
print(f'Number of classes: {dataset.num_classes}')

data = dataset[0]  # Get the first graph object.

print()
print(data)
print('===========================================================================================================')

# Gather some statistics about the graph.
print(f'Number of nodes: {data.num_nodes}')
print(f'Number of edges: {data.num_edges}')
print(f'Average node degree: {data.num_edges / data.num_nodes:.2f}')
print(f'Number of training nodes: {data.train_mask.sum()}')
print(f'Training node label rate: {int(data.train_mask.sum()) / data.num_nodes:.2f}')
print(f'Has isolated nodes: {data.has_isolated_nodes()}')
print(f'Has self-loops: {data.has_self_loops()}')
print(f'Is undirected: {data.is_undirected()}')
Dataset: Cora():
======================
Number of graphs: 1
Number of features: 1433
Number of classes: 7

Data(x=[2708, 1433], edge_index=[2, 10556], y=[2708], train_mask=[2708], val_mask=[2708], test_mask=[2708])
===========================================================================================================
Number of nodes: 2708
Number of edges: 10556
Average node degree: 3.90
Number of training nodes: 140
Training node label rate: 0.05
Has isolated nodes: False
Has self-loops: False
Is undirected: True
  • val_mask和test_mask分别表示这个点需要被用到哪个集中
# 可视化部分
%matplotlib inline
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE

def visualize(h, color):
    z = TSNE(n_components=2).fit_transform(h.detach().cpu().numpy())

    plt.figure(figsize=(10,10))
    plt.xticks([])
    plt.yticks([])

    plt.scatter(z[:, 0], z[:, 1], s=70, c=color, cmap="Set2")
    plt.show()

2、试试直接用传统的全连接层会咋样(Multi-layer Perception Network)

import torch
from torch.nn import Linear
import torch.nn.functional as F


class MLP(torch.nn.Module):
    def __init__(self, hidden_channels):
        super().__init__()
        torch.manual_seed(12345)
        self.lin1 = Linear(dataset.num_features, hidden_channels)
        self.lin2 = Linear(hidden_channels, dataset.num_classes)

    def forward(self, x):
        x = self.lin1(x)
        x = x.relu()
        x = F.dropout(x, p=0.5, training=self.training)
        x = self.lin2(x)
        return x

model = MLP(hidden_channels=16)
print(model)
MLP(
  (lin1): Linear(in_features=1433, out_features=16, bias=True)
  (lin2): Linear(in_features=16, out_features=7, bias=True)
)
model = MLP(hidden_channels=16)
criterion = torch.nn.CrossEntropyLoss()  # Define loss criterion.
optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)  # Define optimizer.

def train():
    model.train()
    optimizer.zero_grad()  # Clear gradients.
    out = model(data.x)  # Perform a single forward pass.
    loss = criterion(out[data.train_mask], data.y[data.train_mask])  # Compute the loss solely based on the training nodes.
    loss.backward()  # Derive gradients.
    optimizer.step()  # Update parameters based on gradients.
    return loss

def test():
    model.eval()
    out = model(data.x)
    pred = out.argmax(dim=1)  # Use the class with highest probability.
    test_correct = pred[data.test_mask] == data.y[data.test_mask]  # Check against ground-truth labels.
    test_acc = int(test_correct.sum()) / int(data.test_mask.sum())  # Derive ratio of correct predictions.
    return test_acc

for epoch in range(1, 210):
    loss = train()
print(f'Epoch: {epoch:03d}, Loss: {loss:.4f}')
Epoch: 209, Loss: 0.3570

准确率计算

test_acc = test()
print(f'Test Accuracy: {test_acc:.4f}')
Test Accuracy: 0.5890

3、Graph Neural Network (GNN)

将全连接层替换成GCN层

from torch_geometric.nn import GCNConv


class GCN(torch.nn.Module):
    def __init__(self, hidden_channels):
        super().__init__()
        torch.manual_seed(1234567)
        self.conv1 = GCNConv(dataset.num_features, hidden_channels)
        self.conv2 = GCNConv(hidden_channels, dataset.num_classes)

    def forward(self, x, edge_index):
        x = self.conv1(x, edge_index)
        x = x.relu()
        x = F.dropout(x, p=0.5, training=self.training)
        x = self.conv2(x, edge_index)
        return x

model = GCN(hidden_channels=16)
print(model)
GCN(
  (conv1): GCNConv(1433, 16)
  (conv2): GCNConv(16, 7)
)

可视化时由于输出是7维向量,所以降维成2维进行展示

model = GCN(hidden_channels=16)
model.eval()

out = model(data.x, data.edge_index)
visualize(out, color=data.y)

image

训练GCN模型

model = GCN(hidden_channels=16)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)
criterion = torch.nn.CrossEntropyLoss()

def train():
    model.train()
    optimizer.zero_grad()  
    out = model(data.x, data.edge_index)  
    loss = criterion(out[data.train_mask], data.y[data.train_mask])  
    loss.backward() 
    optimizer.step()  
    return loss

def test():
    model.eval()
    out = model(data.x, data.edge_index)
    pred = out.argmax(dim=1)  
    test_correct = pred[data.test_mask] == data.y[data.test_mask]  
    test_acc = int(test_correct.sum()) / int(data.test_mask.sum())  
    return test_acc


for epoch in range(1, 101):
    loss = train()
print(f'Epoch: {epoch:03d}, Loss: {loss:.4f}')
Epoch: 100, Loss: 0.5799

准确率计算

test_acc = test()
print(f'Test Accuracy: {test_acc:.4f}')
Test Accuracy: 0.8150

从59%到81%,这个提升还是蛮大的;训练后的可视化展示如下:

model.eval()

out = model(data.x, data.edge_index)
visualize(out, color=data.y)

image


标签:self,分类,mask,print,任务,test,model,data
From: https://www.cnblogs.com/zhangxianrong/p/17728806.html

相关文章

  • 基于weka的数据库挖掘➖分类方法的实现
    基于weka的数据库挖掘➖分类方法的实现关于作者作者介绍......
  • 计算机网络的分类
    计算机网络的分类交换方式:电路交换、报文交换、分组交换使用者:公用网(因特网)、专用网(军队、铁路、电力、银行)传输介质:有线网络、无线网络覆盖范围:拓步结构:......
  • 模式识别与机器学习——生成式分类器 课程笔记
    有监督学习:从有标记的数据中学习推断函数目标函数:\(Y=f(x)\)或\(P(Y|X)\)注意:条件概率用小写p表示,先验概率用大写P表示。贝叶斯判别原则给定观测值X,判断其属于\(\omega1\)类还是\(\omega2\)类,最小化误差概率条件下,\(P(\omega1|X)>P(\omega2|X)\)则判断成\(X\in\omega1\),......
  • 在线问诊 Python、FastAPI、Neo4j — 构建问题分类器
    目录构建字典数据构建Trie字典树按实体组装字典问题分析将问题进行分析,和系统已有的分类进行关联构建字典数据将构建的知识图片字典化,用于后面对问题的解析,下图为症状的字典,其它字典同理构建Trie字典树将建字典数据,组装集合cur_dir='/'.join(os.path.abspath(__file......
  • Django celery 定时任务与周期任务的创建-暂停-开始-删除
    发开阶段遇到了需要定时任务以及周期任务才能进行的事情,这里进行记录一下,防止下次我再写的时候写不明白。首先在你们项目里面创建以下文件:celery:importosos.environ.setdefault("DJANGO_SETTINGS_MODULE","settings")fromceleryimportCeleryfromquality_control.ce......
  • linux Screen 多任务处理
    一、背景系统管理员经常需要SSH或者telent远程登录到Linux服务器,经常运行一些需要很长时间才能完成的任务,比如系统备份、ftp传输等等。通常情况下我们都是为每一个这样的任务开一个远程终端窗口,因为它们执行的时间太长了。必须等待它们执行完毕,在此期间不能关掉窗口或者断开......
  • 基于对数谱图的深度学习心音分类
    这是一篇很有意思的论文,他基于心音信号的对数谱图,提出了两种心率音分类模型,我们都知道:频谱图在语音识别上是广泛应用的,这篇论文将心音信号作为语音信号处理,并且得到了很好的效果。对心音信号进行一致长度的分帧,提取其对数谱图特征,论文提出了长短期记忆(LSTM)和卷积神经网络(CNN)......
  • 金融领域预训练模型用于分类任务,大模型应用参考
    在bert的基础上加了一个分类层:代码实现:output=bert.model.outputoutput=Lambda(lambdax:x[:,0],name='CLS-token')(output)output=Dense(units=num_classes,activation='softmax',kernel_initializer=bert.initializer)(output)model......
  • 194_win7_10任务栏合并但不隐藏标签
    这是一篇原发布于2020-01-2310:28:00得益小站的文章,备份在此处。前言我们都知道Windows的任务栏有个合并、隐藏标签的功能。但Windows提供的三个选项中,就是少了一个不合并但隐藏标签的选项,本文就来解决这个问题。不想看原理,只想快速解决的同学,可以翻到最后,有一键设置的方法。......
  • 异步任务与定时任务
     1.异步任务使用(1)创建线程池配置@Configuration@EnableAsync//开启多线程publicclassThreadPoolConfig{@Bean("taskExecutor")publicExecutorasyncServiceExecutor(){ThreadPoolTaskExecutorexecutor=newThreadPoolTaskExecutor();......