-
Notifications
You must be signed in to change notification settings - Fork 0
/
recvae_train.py
200 lines (142 loc) ยท 7.2 KB
/
recvae_train.py
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import datetime
import time
import math
import argparse
import collections
import os
import pickle
import csv
from tqdm import tqdm
import torch
import torch.optim as optim
import numpy as np
import bottleneck as bn
import pandas as pd
from scipy import sparse
from parse_config import ConfigParser
from utils import prepare_device
from trainer import Trainer
from trainer.ae_trainer import AETrainer
import model.loss as module_loss
from model.loss import loss_function_dae, loss_function_vae
import model.metric as module_metric
import model.model as module_arch
from model.metric import recall_at_k_batch
from model.model import MultiDAE, MultiVAE, RecVAE
from data_loader.ae_dataloader import AETrainDataSet, AETestDataSet, ae_data_load, get_labels
import data_loader.data_loaders as module_data
from data_loader.data_loaders import AEDataLoader
# fix random seeds for reproducibility
SEED = 123
torch.manual_seed(SEED)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(SEED)
def make_prediction_file(output_path, inference_results, config, total_recall_at_k, user_label, item_label):
model_name, lr, n_epochs, dropout_rate, batch_size = config['model_name'], config['lr'], config['n_epochs'], config['dropout_rate'], config['batch_size']
with open(output_path + f'/mat_{RecVAE}_{round(lr,4)}_epoch{n_epochs}_{total_recall_at_k}_dropout{dropout_rate}_batch_{batch_size}.pkl', "wb") as file:
pickle.dump(inference_results, file)
def make_inference_data_and_mark(config, root_data, user_label, item_label):
# inference์์ ์ธ rating ๋ง๋ จํ๊ธฐ
n_users, n_items = config['n_users'], config['n_items']
ratings = pd.read_csv(root_data+'train_ratings.csv')[['user', 'item']]
temp_rows, temp_cols = ratings['user'].apply(lambda x : user_label[x]), ratings['item'].apply(lambda x: item_label[x])
raw_data = sparse.csr_matrix((np.ones_like(temp_rows), (temp_rows, temp_cols)), dtype='float64', shape=(n_users, n_items)).toarray()
train_mark=raw_data.nonzero() # ์ต์ข
์ธํผ๋ฐ์ค ๋ ํํฐ๋งํด์ค ๋ง์คํฌ]
return torch.Tensor(raw_data), train_mark # ์ธํผ๋ฐ์ค์ ์ฐ๊ธฐ ์ํด Tensor๋ก ๋ฐ๊ฟ์ค
def write_submission_file(output_path, final_10, config, total_recall_at_k, user_label, item_label):
model_name, lr, n_epochs, dropout_rate, batch_size = config['model_name'], config['lr'], config['n_epochs'], config['dropout_rate'], config['batch_size']
label_to_user = {v: k for k, v in user_label.items()}
label_to_item = {v: k for k, v in item_label.items()}
with open(output_path + f'/sub_{model_name}_{lr}__epoch{n_epochs}_{total_recall_at_k}_dropout{dropout_rate}_batch_{batch_size}.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
# Write the header row
writer.writerow(['user', 'item'])
# Write the data rows
print("Creating submission file: 31360 users")
for i, row in tqdm(enumerate(final_10)):
u_n = label_to_user[i]
for j in row:
writer.writerow([u_n, label_to_item[j]])
def get_set_and_loader(tr_data, te_data, config):
batch_size, num_workers = config['batch_size'], config['num_workers']
trainset = AETrainDataSet(tr_data)
validset = AETestDataSet(tr_data, te_data)
train_loader = AEDataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=num_workers)
valid_loader = AEDataLoader(validset, batch_size=batch_size, shuffle=False, num_workers=num_workers)
return trainset, validset, train_loader, valid_loader
def ae_train(config):
start_time = time.time()
n_kfold = config['n_kfold']
n_epochs = config['n_epochs']
dropout_rate = config['dropout_rate']
lr = config['lr']
batch_size = config['batch_size']
root_data = config['root_data']
data_dir = config['data_dir']
weight_decay = config['weight_decay']
num_workers = config['num_workers']
model_name = config['model_name']
output_path = config['output_path']
n_users = config['n_users']
n_items = config['n_items']
p_dims = [200, 600, n_items]
n_gpu_use = torch.cuda.device_count()
device = torch.device('cuda:0' if n_gpu_use > 0 else 'cpu')
all_recalls = []
inference_results = []
user_label, item_label = get_labels(data_dir)
raw_data, train_mark = make_inference_data_and_mark(config, root_data, user_label, item_label)
for fold in range(1, n_kfold+1): # k_fold๋ฅผ ์ผ๋จ 5ํ๋ก ์ ์ด๋๊ธฐ
print(f'====================Start: {fold}-fold for 5 fold====================')
model = RecVAE(600, 200, 6807).to(device)
# optimizer = optim.Adam(model.parameters(), lr=1e-3, weight_decay=0.00)
criterion = loss_function_dae
optimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay = weight_decay)
tr_data, te_data = ae_data_load(data_dir, fold)
trainset, validset, train_loader, valid_loader = get_set_and_loader(tr_data, te_data, config)
trainer = AETrainer(model=model, optimizer=optimizer, config=config, device=device, train_loader=train_loader, valid_loader=valid_loader, criterion=criterion)
print(f'==========Training Start==========')
print(f"=================Encoder Training Start =================")
for epoch in range(1, n_epochs+1):
recall_epoch, X_preds, heldouts = trainer.train()
# ๋ง์ง๋ง ํ๋ จ ์๋ฃ๋ recall ์ฌ์ฉ
all_recalls.append(recall_epoch)
# ์ด ๋ชจ๋ธ์ ์ฌ์ฉํด์ ์ธํผ๋ฐ์ค ์งํ ๋ฐ ๋ฆฌ์คํธ์ ์ ์ฅ
inference_result = trainer.inference(raw_data)
inference_results.append(inference_result)
total_recall_at_k = round(sum(all_recalls)/len(all_recalls),4)
print(f'==============์ต์ข
recall_at_k๋ {total_recall_at_k}์
๋๋ค===============')
print(f'=======================Starting Inference=======================')
print("==========์ด๋ฏธ ๋ณธ ์ํ๋ฅผ ํํฐ๋งํด์ค๋๋ค.==========")
# ์๋ ๋ณธ ์ํ๋ฅผ ๋นผ์ฃผ๋ ํํฐ๋ง ์์
inference_results = np.array(inference_results)
inference_results = np.mean(inference_results, axis=0)
inference_results[train_mark] = -np.inf
final_10 = bn.argpartition(-inference_results, 10, axis=1)[:, :10] # 10๊ฐ๋ง ๋จ๊ฒจ๋
# ํ์ผ์ ์ ์ฅํ ๋๋ ํ ๋ฆฌ ์ค์
if not os.path.exists(output_path):
os.mkdir(output_path)
# ์์ธก ํ์ผ์ ์ ์ฅํจ
make_prediction_file(output_path, inference_results, config, total_recall_at_k, user_label, item_label)
#์ ์ถ ํ์ผ์ ์ ์ฅํจ
write_submission_file(output_path, final_10, config, total_recall_at_k, user_label, item_label)
if __name__ == "__main__":
config = {
"n_kfold": 1,
"n_epochs": 1,
"dropout_rate": 0.5,
"lr": 0.0005,
"batch_size": 64,
"root_data": './data/train/' ,
"data_dir": './data/train/ae_data',
"weight_decay": 0.01,
"num_workers": 1,
"model_name": 'RecVAE', # [MultiDAE, MultiVAE, RecVAE]
"output_path": './output/auto_encoder',
"n_users": 31360,
"n_items": 6807,
'anneal_cap': 0.2,
'total_anneal_step': 200000
}
ae_train(config)