10
10
import matplotlib .pyplot as plt
11
11
import torch .nn .functional as F
12
12
13
+
13
14
n_dim = 2
14
15
x_train , y_train = make_blobs (n_samples = 80 , n_features = n_dim , centers = [[1 ,1 ],[- 1 ,- 1 ],[1 ,- 1 ],[- 1 ,1 ]], shuffle = True , cluster_std = 0.3 )
15
16
x_test , y_test = make_blobs (n_samples = 20 , n_features = n_dim , centers = [[1 ,1 ],[- 1 ,- 1 ],[1 ,- 1 ],[- 1 ,1 ]], shuffle = True , cluster_std = 0.3 )
16
17
18
+
17
19
def label_map (y_ , from_ , to_ ):
18
20
y = numpy .copy (y_ )
19
21
for f in from_ :
@@ -25,6 +27,7 @@ def label_map(y_, from_, to_):
25
27
y_test = label_map (y_test , [0 , 1 ], 0 )
26
28
y_test = label_map (y_test , [2 , 3 ], 1 )
27
29
30
+
28
31
def vis_data (x ,y = None , c = 'r' ):
29
32
if y is None :
30
33
y = [None ] * len (x )
@@ -38,12 +41,14 @@ def vis_data(x,y = None, c = 'r'):
38
41
vis_data (x_train , y_train , c = 'r' )
39
42
plt .show ()
40
43
44
+
41
45
x_train = torch .FloatTensor (x_train )
42
46
print (x_train .shape )
43
47
x_test = torch .FloatTensor (x_test )
44
48
y_train = torch .FloatTensor (y_train )
45
49
y_test = torch .FloatTensor (y_test )
46
50
51
+
47
52
class NeuralNet (torch .nn .Module ):
48
53
def __init__ (self , input_size , hidden_size ):
49
54
super (NeuralNet , self ).__init__ ()
@@ -61,16 +66,19 @@ def forward(self, input_tensor):
61
66
output = self .sigmoid (linear2 )
62
67
return output
63
68
69
+
64
70
model = NeuralNet (2 , 5 )
65
71
learning_rate = 0.03
66
72
criterion = torch .nn .BCELoss ()
67
73
epochs = 2000
68
74
optimizer = torch .optim .SGD (model .parameters (), lr = learning_rate )
69
75
76
+
70
77
model .eval ()
71
78
test_loss_before = criterion (model (x_test ).squeeze (), y_test )
72
79
print ('Before Training, test loss is {}' .format (test_loss_before .item ()))
73
80
81
+
74
82
# 오차값이 0.73 이 나왔습니다. 이정도의 오차를 가진 모델은 사실상 분류하는 능력이 없다고 봐도 무방합니다.
75
83
# 자, 이제 드디어 인공신경망을 학습시켜 퍼포먼스를 향상시켜 보겠습니다.
76
84
@@ -84,20 +92,24 @@ def forward(self, input_tensor):
84
92
train_loss .backward ()
85
93
optimizer .step ()
86
94
95
+
87
96
model .eval ()
88
97
test_loss = criterion (model (x_test ).squeeze (), y_test )
89
98
print ('After Training, test loss is {}' .format (test_loss .item ()))
90
99
100
+
91
101
# 학습을 하기 전과 비교했을때 현저하게 줄어든 오차값을 확인 하실 수 있습니다.
92
102
# 지금까지 인공신경망을 구현하고 학습시켜 보았습니다.
93
103
# 이제 학습된 모델을 .pt 파일로 저장해 보겠습니다.
94
104
95
105
torch .save (model .state_dict (), './model.pt' )
96
106
print ('state_dict format of the model: {}' .format (model .state_dict ()))
97
107
108
+
98
109
# `save()` 를 실행하고 나면 학습된 신경망의 가중치를 내포하는 model.pt 라는 파일이 생성됩니다. 아래 코드처럼 새로운 신경망 객체에 model.pt 속의 가중치값을 입력시키는 것 또한 가능합니다.
99
110
100
111
new_model = NeuralNet (2 , 5 )
101
112
new_model .load_state_dict (torch .load ('./model.pt' ))
102
113
new_model .eval ()
103
114
print ('벡터 [-1, 1]이 레이블 1을 가질 확률은 {}' .format (new_model (torch .FloatTensor ([- 1 ,1 ])).item ()))
115
+
0 commit comments