文章目录
前言
开始阅读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 中,以 f
或 F
开头的字符串是格式化字符串字面量。
f-string 的基本语法
f"{expression}"
这里的 expression
可以是任何有效的 Python 表达式,包括变量、函数调用、算术运算等。
示例
-
嵌入变量:
name = "Alice" greeting = f"Hello, {name}!" print(greeting) # 输出: Hello, Alice!
-
格式化选项 :
f-string 也支持格式化选项,类似于
str.format()
方法。例如,你可以控制小数点后的位数、填充字符、对齐方式等:
pi = 3.141592653589793
formatted_pi = f"Pi is approximately {pi:.2f}."
print(formatted_pi) # 输出: Pi is approximately 3.14.
在这个例子中,`:.2f` 指定了浮点数格式化为两位小数。
-
多行 f-string:
f-string 也可以跨越多行,这使得代码更加清晰易读:
text = f"""
Hello,
I am using
an f-string.
"""
print(text)
输出:
Hello,
I am using
an f-string.
总结
这个代码没跑通,就读到这里了。找了一个能跑通的,明天读。。。