-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3-1.py
More file actions
99 lines (76 loc) · 3.24 KB
/
Copy path3-1.py
File metadata and controls
99 lines (76 loc) · 3.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
from torch import nn
import torch
x = torch.tensor([1.])
model=nn.Linear(1,1)#입력 node 한개 출력 node 한개인 layer
print(model)#(in=레이어 갯수, out=레이어 갯수, bias=True 끄면 False로 나옴)
print(model.weight)
print(model.bias)
#가중치와 편향 두개 다 이미 tensor로 만들어져있고 requires_grad = True로 되어있음 학습을 해야하기 때문에
y = model(x)#x를 model이라는 인공 신경망에 통과
print(y)#1에 weight 곱하고 bias 더한 값
y2 = x @ model.weight + model.bias # 식으로 표현
fc1 = nn.Linear(1,3)
fc2 = nn.Linear(3,1)
print(fc1.weight)
print(fc1.bias)
print(fc2.weight)
print(fc2.bias)
x = torch.tensor([1.])
x = fc1(x)
print(x)
y = fc2(x)
print(y)
y2 = (x @ fc1.weight.T + fc1.bias) @ fc2.weight.T + fc2.bias # 식으로
model = nn.Linear(2,3)
# 데이터 여러개를 통과시키고 싶다면 개x채의 형태로 넣어야함 (채x개 개*채 둘다 안됨)
x = torch.randn(5,2)#개x채 2개의 채널(키,몸무게)을 가진 5명의 사람들
print(model(x))#5,3이 나옴 이유는 출력이 3인 레이어에 5번 집어 넣었으니 그 값이 5개 나올테고 출력이 3이니 3이 5개 쌓인 5,3 형태로 나오게 됨
x = torch.randn(4,5,2)#nn.Linear은 이거를 개x개x채로 들어오게 됨 2개의 특징을 가진 5사람이 4개의 조를 이루고 있다라는 뜻으로 생각하면 됨
#weight에 Transpose 하는 이유는 각각의 데이터에 똑같은 weight을 갖고오니까 3,2 데이터에는 똑같이 3,2 weight가 있기에 이러면 행렬 곱 연산을 못함 그래서 할 수 있게 만들 기 위해 Transpose
fc1 = nn.Linear(1,3)
fc2 = nn.Linear(3,1)
x = torch.tensor([1.])
model = nn.Sequential(fc1,fc2)#(1번째,2번째) 순서로 한번에 통과시키는 기능
print(model(x))
model = nn.Sequential(nn.Linear(2,5),
nn.Linear(5,10),
nn.Linear(10,3)) # 보통 이렇게 표현
x = torch.randn(5,2)
print(x)
print(model(x))
class MyModel(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(2,5)
self.fc2 = nn.Linear(5,10)
self.fc3 = nn.Linear(10,3)
self.act = nn.Sigmoid()
def forward(self,x) :
x = self.fc1(x)
x = self.act(x)
x = self.fc2(x)
x = self.act(x)
x = self.fc3(x)
x = self.act(x)
return x
model = MyModel()
x = torch.randn(5,2)
y = model(x)#model.forward(x)와 같은 표현 nn.Module에는 __call__이라는 스페셜 메서드가 있는데 인스턴스()형태로 호출 가능
class MyModel2(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Sequential(nn.Linear(2,5),
nn.Sigmoid(),
nn.Linear(5,10),
nn.Sigmoid(),
nn.Linear(10,3),
nn.Sigmoid())
def forward(self,x):
x = self.linear(x)
return x
model2 = MyModel2()
x = torch.randn(5,2)
y = model2(x)
list(model.parameters())#model이 가지고 있는 모든 파라미터를 보여줌
num = sum([p.numel() for p in model.parameters() if p.requires_grad])#파라미터 수 구하기
print(num)