图神经网络——GAT代码阅读


前言

开始阅读GAT 代码,链接如下:
git_gat代码

读的是这个文件

注:请先看总结


函数和方法笔记

1. np.array()

  • 定义:NumPy 库中的函数,用于创建多维数组。
  • 语法np.array(object, dtype=None, copy=False)
  • 用途:用于数值计算、数据预处理、图像处理等。
  • 功能:可以将列表(list)、元组(tuple)或其他数组转换为 NumPy 数组。NumPy 数组是一个同质的数据结构,这意味着数组中的所有元素都必须是相同的数据类型。
基本用法
import numpy as np

# 创建一个一维数组
a = np.array([1, 2, 3, 4, 5])
print(a)  # 输出: [1 2 3 4 5]

# 创建一个二维数组
b = np.array([[1, 2, 3], [4, 5, 6]])
print(b)
# 输出:
# [[1 2 3]
#  [4 5 6]]
参数
  • object: 要转换为数组的对象,通常是列表或元组。
  • dtype: 数据类型,默认为 None。如果指定,数组将转换为该数据类型。
  • copy: 如果为 True,则数据不会被缓存,而是复制到新数组中。
示例
import numpy as np

# 创建一个浮点数数组
c = np.array([1, 2, 3], dtype=float)
print(c)  # 输出: [1. 2. 3.]

# 创建一个二维数组,并指定数据类型
d = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32)
print(d)
# 输出:
# [[1 2 3]
#  [4 5 6]]

# 使用 copy 参数
e = np.array([1, 2, 3])
f = np.array(e, copy=True)
e[0] = 10
print(e)  # 输出: [10  2  3]
print(f)  # 输出: [1 2 3]

2. super().__init__()

  • 定义:用于在子类构造器中调用父类构造器。
  • 语法super().__init__()
  • 用途:确保父类的初始化逻辑被执行。若父类含有 重要初始化命令 ,没有会导致出错。
  • 示例
    class Parent: 
        def __init__(self): 
            print("Parent constructor") 
    
    class Child(Parent): 
        def __init__(self): 
            super().__init__() 
            print("Child constructor") 
    
    c = Child()
    # 输出: Parent constructor
    #        Child constructor
    
  • 拓展
    • 支持多重继承。
    • 确保初始化逻辑的正确传递。

3. torch.Tensor

  • 定义:PyTorch 中用于表示多维数组的类。
  • 语法torch.Tensor(*sizes, dtype=None, device=None)
  • 用途:用于构建和训练深度学习模型。
  • 示例
    import torch  
    t = torch.Tensor(2, 3)  
    print(t)  # 输出: tensor([[0., 0., 0.],  
    
    #     生成2行3列的随机数            [0., 0., 0.]])  
    

创建张量

以下是一些常用的创建 torch.Tensor 的方法:

import torch

# 从现有数据创建张量
x = torch.tensor([1, 2, 3])
print(x)  # 输出: tensor([1, 2, 3])

# 创建一个形状为 (5, 3) 的随机初始化张量 
x = torch.rand(5, 3) 
print(x) 

# 创建一个形状为 (5, 3) 的全0张量 
x = torch.zeros(5, 3)  
print(x)  

# 创建一个形状为 (5, 3) 的全1张量  
x = torch.ones(5, 3)  
print(x)  

# 创建一个指定大小的未初始化张量  
x = torch.empty(5, 3)   
print(x)   

张量的基本操作

import torch   

# 创建两个张量  
a = torch.tensor([1, 2, 3])  
b = torch.tensor([4, 5, 6])  

# 张量加法  
c = a + b 
print(c)  # 输出: tensor([5, 7, 9]) 

# 张量点积 
*d = torch.dot(a, b) 
print(d)  # 输出: tensor(22) 

# 张量切片
e = a[1:]  # 获取第二个元素到最后
print(e)  # 输出: tensor([2, 3])

# 张量拼接
f = torch.cat((a, b), dim=0)  # 沿着第一个维度拼接
print(f)  # 输出: tensor([1, 2, 3, 4, 5, 6])

张量与自动求导

import torch

# 创建一个张量,并设置 requires_grad=True 来跟踪其梯度
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)

# 进行一些操作
y = x ** 2  # y = [1, 4, 9]
z = y.sum()  # z = 14

# 计算 z 关于 x 的梯度
z.backward()

# 输出梯度
print(x.grad)  # 输出: tensor([1., 2., 3.])

张量与设备

张量可以在不同的设备上运行,如 CPU 或 GPU:

import torch

# 创建一个张量
x = torch.tensor([1, 2, 3]*)

# 将张量移动到 GPU 上(如果可用)
if torch.cuda.is_available():
    x = x.to('cuda')
    print(x)  # 输出: tensor([1, 2, 3], device='cuda:0')

# 将张量移动回 CPU
x = x.to('cpu')
print(x)  # 输出: tensor([1, 2, 3])

4. torch.randn()

  • 定义:生成一个给定形状的张量,元素从标准正态分布中随机采样。
  • 语法torch.randn(*sizes, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
  • 用途:常用于神经网络参数的初始化。
  • 示例
    r = torch.randn(2, 3)
    print(r)  # 输出: tensor([[ 0.3480,  0.8625, -0.7496],
    #                  [ 0.4516, -0.6809,  0.5078]])
    

5. .view() 方法

  • 定义:PyTorch 张量方法,用于改变张量的形状而不改变数据。
  • 语法tensor.view(*shape)
  • 用途:在模型的不同层之间重塑张量。
  • 示例
    x = torch.randn(2, 3)
    y = x.view(3, 2)
    print(y)  # 输出: tensor([[ 0.3480,  0.8625],
    #                 [-0.7496,  0.4516],
    #                 [ 0.5078, -0.6809]])
    
  • 拓展
    • 要求新旧形状包含相同数量的元素。

6. torch.einsum()

  • 定义:执行爱因斯坦求和约定,用于高效张量操作。
  • 语法torch.einsum(subscript, *operands)
  • 用途:在深度学习中实现复杂的张量运算。
  • 示例
    a = torch.randn(2, 3)
    b = torch.randn(3, 2)
    result = torch.einsum('ij,jk->ik', a, b)
    print(result)  # 输出: tensor([[ ... ], [ ... ]])
    
  • 拓展
    • 可以定制复杂的运算,如矩阵乘法、转置、批处理等。

7. .masked_fill() 方法

  • 定义:根据给定的布尔掩码替换张量中的元素。
  • 语法tensor.masked_fill(mask, value)
  • 用途:在深度学习中实现条件操作,如注意力机制。
  • 示例
    x = torch.tensor([1, 2, 3, 4, 5])
    mask = (x > 2)
    y = x.masked_fill(mask, 0)
    print(y)  # 输出: tensor([1, 2, 0, 0, 0])
    
  • 拓展
    • 可以用于实现条件数据过滤和特征选择。

8. nn.Dropout 模块

  • 定义:在训练过程中随机丢弃部分神经元的输出,以减少过拟合。
  • 语法nn.Dropout(p=0.5, inplace=False)#
  • 用途:作为神经网络的正则化手段。
  • 示例
    import torch.nn as nn  
    dropout = nn.Dropout(p=0.2) #   
    x = torch.randn(2, 3)    
    y = dropout(x)          
    print(y)  # 输出: tensor([[ ... ], [ ... ]])          
    
  • 拓展
    • 可以调整丢弃概率 p 来控制正则化的强度。

9、f-string

在 Python 中,以 fF 开头的字符串是格式化字符串字面量。

f-string 的基本语法

f"{expression}"

这里的 expression 可以是任何有效的 Python 表达式,包括变量、函数调用、算术运算等。

示例

  1. 嵌入变量:

    name = "Alice"
    greeting = f"Hello, {name}!"
    print(greeting)  # 输出: Hello, Alice!
    
  2. 格式化选项 :

    f-string 也支持格式化选项,类似于 str.format() 方法。例如,你可以控制小数点后的位数、填充字符、对齐方式等:

pi = 3.141592653589793
formatted_pi = f"Pi is approximately {pi:.2f}."
print(formatted_pi)  # 输出: Pi is approximately 3.14.
在这个例子中,`:.2f` 指定了浮点数格式化为两位小数。
  1. 多行 f-string

    f-string 也可以跨越多行,这使得代码更加清晰易读:

text = f"""
Hello,
I am using
an f-string.
"""
print(text)

输出:

Hello,
I am using
an f-string.

总结

这个代码没跑通,就读到这里了。找了一个能跑通的,明天读。。。

以下是一个简单的GAT(Graph Attention Network)神经网络代码示例: ```python import torch import torch.nn as nn import torch.nn.functional as F class GATLayer(nn.Module): def __init__(self, in_features, out_features, dropout=0.6, alpha=0.2): super(GATLayer, self).__init__() self.dropout = dropout self.alpha = alpha self.W = nn.Linear(in_features, out_features, bias=False) self.a = nn.Linear(2*out_features, 1, bias=False) def forward(self, X, adj_matrix): h = self.W(X) N = h.size(0) a_input = torch.cat([h.repeat(1, N).view(N*N, -1), h.repeat(N, 1)], dim=1).view(N, -1, 2*h.size(1)) e = F.leaky_relu(self.a(a_input).squeeze(2), negative_slope=self.alpha) zero_vec = -9e15*torch.ones_like(e) attention = torch.where(adj_matrix > 0, e, zero_vec) attention = F.softmax(attention, dim=1) attention = F.dropout(attention, p=self.dropout, training=self.training) h_prime = torch.matmul(attention, h) return F.elu(h_prime) class GAT(nn.Module): def __init__(self, in_features, hidden_features, out_features, num_layers, dropout=0.6, alpha=0.2): super(GAT, self).__init__() self.hidden_features = hidden_features self.num_layers = num_layers self.layers = nn.ModuleList([GATLayer(in_features, hidden_features, dropout=dropout, alpha=alpha)]) self.layers.extend([GATLayer(hidden_features, hidden_features, dropout=dropout, alpha=alpha) for _ in range(num_layers-2)]) self.layers.append(GATLayer(hidden_features, out_features, dropout=dropout, alpha=alpha)) def forward(self, X, adj_matrix): h = X for layer in self.layers: h = layer(h, adj_matrix) return h ``` 这是一个简单的GAT神经网络的实现,包括了GATLayer和GAT两个类。GATLayer定义了一个GAT层的操作,GAT则将多个GAT层串联起来构成整个神经网络。其中,in_features表示输入特征的维度,hidden_features表示隐层特征的维度,out_features表示输出特征的维度,num_layers表示GAT层数,dropout表示dropout率,alpha表示LeakyReLU的斜率。 希望这个代码示例对你有帮助!如有任何问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值