
# 임베딩 벡터를 생성한 전체 범주의 개수가 10이고, 임베딩 벡터 차원이 3이므로 10*3 크기의 행렬 생성됨 -> 정규분포를 따르는 랜덤값으로 초기화됨
embedding = nn.Embedding(10, 3)
# 이미 만들어진 embedding에서 2개의 샘플을 복사해서 가져오는 Lookup 작업을 함.
# 이때 1번째 샘플은 embedding 행렬의 1,2,4,5 행의 임베딩 벡터를 가져오고,
# 2번째 샘플은 4,3,2,9 행의 임베딩 벡터를 가져옴
input = torch.LongTensor([[1, 2, 4, 5], [4, 3, 2, 9]])
embedding(input)
# 결과값
>> tensor([[[-0.0251, -1.6902, 0.7172],
[-0.6431, 0.0748, 0.6969],
[ 1.4970, 1.3448, -0.9685],
[-0.3677, -2.7265, -0.1685]],
[[ 1.4970, 1.3448, -0.9685],
[ 0.4362, -0.4004, 0.9400],
[-0.6431, 0.0748, 0.6969],
[ 0.9124, -2.3616, 1.1151]]])
import torch
# 빈 텐서 생성
tensor_uniform = torch.empty(3, 5)
tensor_normal = torch.empty(3, 5)
# 균등 분포로 초기화
torch.nn.init.xavier_uniform_(tensor_uniform, gain=1.0, generator=None)
print(f'균등 분포 ', tensor_uniform )
# 정규 분포로 초기화
torch.nn.init.xavier_normal_(tensor_normal, gain=1.0)
print(f'정규 분포',tensor_normal)
------------------------------------------------------
균등 분포 tensor([[-0.5576, -0.7264, 0.2654, -0.7511, -0.3088],
[ 0.7059, 0.6009, -0.6884, -0.0664, 0.7435],
[ 0.5134, 0.6118, 0.2403, 0.0801, 0.7607]])
정규 분포 tensor([[ 0.9741, 0.1742, -1.0699, -0.1486, 0.2731],
[-0.2109, -0.2306, 0.7515, -0.9540, 1.0228],
[-0.4853, 0.2636, 0.6432, -0.1358, -0.4924]])
출처: https://resultofeffort.tistory.com/114 [resultofeffort:티스토리]

import torch
tensor_uniform = torch.empty(3, 5)
torch.nn.init.kaiming_uniform_(tensor_uniform, mode='fan_in', nonlinearity='relu', generator=None)
print(f'균등 분포 ', tensor_uniform )
tensor_normal = torch.empty(3, 5)
torch.nn.init.kaiming_normal_(tensor_normal, mode='fan_in', nonlinearity='relu', generator=None)
print(f'정규 분포',tensor_normal)
출처: https://resultofeffort.tistory.com/114 [resultofeffort:티스토리]
import torch
t1 = torch.tensor([[1, 2], [3, 4]]) # (2, 2)
t2 = torch.tensor([[5, 6], [7, 8]]) # (2, 2)
# dim=0 (행 기준, 세로로 붙이기)
cat_0 = torch.cat([t1, t2], dim=0)
# dim=1 (열 기준, 가로로 붙이기)
cat_1 = torch.cat([t1, t2], dim=1)
print("dim=0:", cat_0)
print("dim=1:", cat_1)
# 결과값
>> dim=0: tensor([[1, 2],
[3, 4],
[5, 6],
[7, 8]])
>> dim=1: tensor([[1, 2, 5, 6],
[3, 4, 7, 8]])
import torch
t1 = torch.tensor([1, 2])
t2 = torch.tensor([3, 4])
# dim=0에 쌓기 (새로운 차원 추가)
# t1, t2는 (2,) 크기 -> stack 후 (2, 2) 크기가 됨
stacked = torch.stack([t1, t2], dim=0)
print(stacked)
# 결과값
>> tensor([[1, 2],
[3, 4]])
import torch
mat1 = torch.tensor([[1, 2], [3, 4]]) # (2, 2)
mat2 = torch.tensor([[1, 0], [0, 1]]) # (2, 2) 단위 행렬
# 행렬 곱
result = torch.matmul(mat1, mat2)
print(result)
# 결과값
>> tensor([[1, 2],
[3, 4]])
import torch
# 1. 희소 텐서 생성 (Indices와 Values로 정의)
# (0, 1) 위치에 3, (1, 2) 위치에 4가 있는 2x3 행렬
i = torch.LongTensor([[0, 1], [1, 2]])
v = torch.FloatTensor([3, 4])
sparse_mat = torch.sparse_coo_tensor(i, v, (2, 3))
# 2. 밀집 텐서 생성 (3x2 행렬)
dense_mat = torch.tensor([[1, 0], [0, 1], [1, 0]], dtype=torch.float32)
# 3. 행렬 곱 (2x3) @ (3x2) -> (2x2)
res = torch.sparse.mm(sparse_mat, dense_mat)
print(res)
# 결과값
# [0행] (0,1)값 3 * [1행] (0,1) -> 3*0 + 3*1 = 3
>> tensor([[0., 3.],
[4., 0.]])
import torch
a = torch.tensor([[1, 2], [3, 4]])
b = torch.tensor([[2, 2], [2, 2]])
# 원소별 곱셈 (1*2, 2*2, 3*2, 4*2)
result = torch.mul(a, b)
print(result)
# 결과값
>> tensor([[2, 4],
[6, 8]])
import torch
t = torch.tensor([1, 2, 3, 4, 5, 6])
# 2개씩 자르기
split_t = torch.split(t, 2)
print(split_t)
# 리스트 형태로 각 텐서 반환
# 결과값
>> (tensor([1, 2]), tensor([3, 4]), tensor([5, 6]))
import torch
input_tensor = torch.empty(2, 3) # (2, 3) 크기
random_tensor = torch.rand_like(input_tensor)
print(random_tensor)
# 결과값 (랜덤)
>> tensor([[0.8231, 0.4123, 0.1982],
[0.2141, 0.6521, 0.9812]])
import torch
t = torch.tensor([10, -5, 0, 3.5, -0.1])
result = torch.sign(t)
print(result)
# 결과값
>> tensor([ 1., -1., 0., 1., -1.])
import torch
import torch.nn as nn
model = nn.Sequential(
nn.Linear(10, 20),
nn.ReLU(),
nn.Linear(20, 10)
)
print(model)
import torch
import torch.nn as nn
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.layers = nn.ModuleList([
nn.Linear(10, 20),
nn.ReLU(),
nn.Linear(20, 10)
])
def forward(self, x):
for layer in self.layers:
x = layer(x)
return x
model = MyModel()
print(model)
import torch
import torch.nn as nn
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.layers = nn.ModuleDict({
'fc1': nn.Linear(10, 20),
'relu': nn.ReLU(),
'fc2': nn.Linear(20, 10)
})
def forward(self, x):
x = self.layers['fc1'](x)
x = self.layers['relu'](x)
x = self.layers['fc2'](x)
return x
model = MyModel()
print(model)
import torch
import torch.nn as nn
class MyModel(nn.Module):
def __init__(self):
super().__init__()
# Case 1: 일반 Tensor로 선언
# 모델은 이것을 그냥 '고정된 숫자 데이터'로 취급함 (학습 X, 상수로 변하지 않음)
self.my_tensor = torch.randn(1)
# Case 2: nn.Parameter로 감싸서 선언
# 모델은 이것을 '학습해야 할 가중치'로 등록함 (학습 O)
self.my_param = nn.Parameter(torch.randn(1))
def forward(self, x):
# 우리는 그저 수식만 적으면 됨 (어떻게 학습할지는 PyTorch가 알아서 함)
# y = x * W + b 형태
return x * self.my_param + self.my_tensor
model = MyModel()
# 모델이 인식한 '학습 대상' 목록 확인
print(f"학습 대상 파라미터: {list(model.parameters())}")
# 결과값
# my_tensor는 무시되고, my_param만 리스트에 존재함!
# >> 학습 대상 파라미터: [Parameter containing: tensor([-0.5421], requires_grad=True)]
import torch
import torch.nn as nn
class GNNLayer(nn.Module):
def __init__(self):
super().__init__()
# 타입별로 다른 가중치를 딕셔너리로 관리
self.weights = nn.ParameterDict({
'user': nn.Parameter(torch.randn(5, 5)),
'item': nn.Parameter(torch.randn(5, 5))
})
def forward(self, x, node_type):
# 입력된 node_type('user' or 'item')에 맞는 파라미터를 꺼내서 연산
# 마찬가지로 수식만 적으면 해당 파라미터만 자동으로 학습됨
w = self.weights[node_type]
return torch.matmul(x, w)
model = GNNLayer()
# 'user' 타입 가중치 확인
print(f"User Weights Size: {model.weights['user'].size()}")
# 결과값
# >> User Weights Size: torch.Size([5, 5])
class MyModel(nn.Module):
def __init__(self):
super().__init__()
self.W = nn.Parameter(torch.randn(1)) # 가중치 (학습 O)
self.b = nn.Parameter(torch.randn(1)) # 편향 (학습 O)
self.d = nn.Parameter(torch.randn(1)) # 나누는 값 (학습 O)
def forward(self, x):
# 수식 그대로 작성
return (x * self.W + self.b) / self.d
class MyModel(nn.Module):
def __init__(self):
super().__init__()
self.W = nn.Parameter(torch.randn(1))
self.b = nn.Parameter(torch.randn(1))
# d는 학습 안 함 (상수)
self.d = 2.0
def forward(self, x):
return (x * self.W + self.b) / self.d
*참고