-
Notifications
You must be signed in to change notification settings - Fork 1
/
context_data.py
302 lines (250 loc) · 13.9 KB
/
context_data.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import torch
import torch.nn as nn
from torch.utils.data import TensorDataset, DataLoader, Dataset
from tqdm import tqdm
import re
import pdb
def age_map(x: int) -> int:
x = int(x)
if x < 10:
return 1
elif x >= 10 and x < 20:
return 2
elif x >= 20 and x < 30:
return 3
elif x >= 30 and x < 40:
return 4
elif x >= 40 and x < 50:
return 5
else:
return 6
def process_context_data(users, books, ratings1, ratings2):
"""
Parameters
----------
users : pd.DataFrame
users.csv를 인덱싱한 데이터
books : pd.DataFrame
books.csv를 인덱싱한 데이터
ratings1 : pd.DataFrame
train 데이터의 rating
ratings2 : pd.DataFrame
test 데이터의 rating
----------
"""
'''
----------------------------------------------유저 전처리-----------------------------------------------------------------
'''
users['location_city'] = users['location'].apply(lambda x: x.split(',')[0].replace(' ','').lower())
users['location_state'] = users['location'].apply(lambda x: x.split(',')[1].replace(' ','').lower())
users['location_country'] = users['location'].apply(lambda x: x.split(',')[2].replace(' ','').lower())
users = users.replace('na', np.nan) #특수문자 제거로 n/a가 na로 바뀌게 되었습니다. 따라서 이를 컴퓨터가 인식할 수 있는 결측값으로 변환합니다.
users = users.replace('', np.nan)
users = users.replace('n/a', np.nan)
modify_location = users[(users['location_country'].isna())&(users['location_city'].notnull())]['location_city'].values
location = users[(users['location'].str.contains('seattle'))&(users['location_country'].notnull())]['location'].value_counts().index[0]
location_list = []
for location in tqdm(modify_location):
try:
right_location = users[(users['location'].str.contains(location))&(users['location_country'].notnull())]['location'].value_counts().index[0]
location_list.append(right_location)
except: pass
for location in tqdm(location_list):
users.loc[users[users['location_city']==location.split(',')[0]].index,'location_state'] = location.split(',')[1]
users.loc[users[users['location_city']==location.split(',')[0]].index,'location_country'] = location.split(',')[2]
loc_city2idx = {v:k for k,v in enumerate(users['location_city'].unique())}
loc_state2idx = {v:k for k,v in enumerate(users['location_state'].unique())}
loc_country2idx = {v:k for k,v in enumerate(users['location_country'].unique())}
users['location_city'] = users['location_city'].map(loc_city2idx)
users['location_state'] = users['location_state'].map(loc_state2idx)
users['location_country'] = users['location_country'].map(loc_country2idx)
users['age'].fillna(1, inplace= True)
users = users.drop(['location'], axis=1)
'''
----------------------------------------------유저 전처리-----------------------------------------------------------------
'''
'''
----------------------------------------------아이템 전처리-----------------------------------------------------------------
'''
books = books.replace('na', np.nan) #특수문자 제거로 n/a가 na로 바뀌게 되었습니다. 따라서 이를 컴퓨터가 인식할 수 있는 결측값으로 변환합니다.
books = books.replace('', np.nan)
books = books.replace('n/a', np.nan)
publisher_dict=(books['publisher'].value_counts()).to_dict()
publisher_count_df= pd.DataFrame(list(publisher_dict.items()),columns = ['publisher','count'])
publisher_count_df = publisher_count_df.sort_values(by=['count'], ascending = False)
modify_list = publisher_count_df[publisher_count_df['count']>1].publisher.values
for publisher in tqdm(modify_list):
try:
number = books[books['publisher']==publisher]['isbn'].apply(lambda x: x[:4]).value_counts().index[0]
right_publisher = books[books['isbn'].apply(lambda x: x[:4])==number]['publisher'].value_counts().index[0]
books.loc[books[books['isbn'].apply(lambda x: x[:4])==number].index,'publisher'] = right_publisher
except: pass
category_df = pd.DataFrame(books['category'].value_counts()).reset_index()
category_df.columns = ['category','count']
books['category_high'] = books['category'].copy()
books.loc[books[books['category']=='biography'].index, 'category_high'] = 'biography autobiography'
books.loc[books[books['category']=='autobiography'].index,'category_high'] = 'biography autobiography'
books.loc[books[books['category'].str.contains('history',na=False)].index,'category_high'] = 'history'
# 대괄호 써있는 카테고리 전치리
books.loc[books[books['category'].notnull()].index, 'category'] = books[books['category'].notnull()]['category'].apply(lambda x: re.sub('[\W_]+','',x).strip())
# 모두 소문자로 통일
books['category'] = books['category'].str.lower()
categories = ['garden','crafts','physics','adventure','music','fiction','nonfiction','science','science fiction','social','homicide',
'sociology','disease','religion','christian','philosophy','psycholog','mathemat','agricult','environmental',
'business','poetry','drama','literary','travel','motion picture','children','cook','literature','electronic',
'humor','animal','bird','photograph','computer','house','ecology','family','architect','camp','criminal','language','india']
books['category_high'] = books['category'].copy()
for category in categories:
books.loc[books[books['category'].str.contains(category,na=False)].index,'category_high'] = category
books['category_high'].fillna('fiction', inplace = True)
bins = [1300, 1970, 1980, 1990, 2000, 2020]
labels = list(range(len(bins) - 1))
labels = ["year_" + str(i) for i in labels]
books['year'] = pd.cut(books['year_of_publication'], bins=bins, right=True, labels=labels)
books.drop('year_of_publication',inplace= True, axis =1)
books.drop(['category'], axis = 1, inplace = True)
books['book_title']= books['book_title'].apply(lambda x: str(x).lower().replace(' ',''))
books['book_author']= books['book_author'].apply(lambda x: str(x).lower().replace(' ',''))
books['language'].fillna('en', inplace = True)
books['category_high'].fillna('fiction', inplace = True)
books = books.rename(columns={'category_high': 'category'})
'''
----------------------------------------------아이템 전처리-----------------------------------------------------------------
'''
ratings = pd.concat([ratings1, ratings2]).reset_index(drop=True)
# 인덱싱 처리된 데이터 조인
context_df = ratings.merge(users, on='user_id', how='left').merge(books[['isbn', 'category', 'year', 'publisher', 'language', 'book_author']], on='isbn', how='left')
train_df = ratings1.merge(users, on='user_id', how='left').merge(books[['isbn', 'category', 'year', 'publisher', 'language', 'book_author']], on='isbn', how='left')
test_df = ratings2.merge(users, on='user_id', how='left').merge(books[['isbn', 'category', 'year', 'publisher', 'language', 'book_author']], on='isbn', how='left')
# 인덱싱 처리
loc_city2idx = {v:k for k,v in enumerate(context_df['location_city'].unique())}
loc_state2idx = {v:k for k,v in enumerate(context_df['location_state'].unique())}
loc_country2idx = {v:k for k,v in enumerate(context_df['location_country'].unique())}
train_df['location_city'] = train_df['location_city'].map(loc_city2idx)
train_df['location_state'] = train_df['location_state'].map(loc_state2idx)
train_df['location_country'] = train_df['location_country'].map(loc_country2idx)
test_df['location_city'] = test_df['location_city'].map(loc_city2idx)
test_df['location_state'] = test_df['location_state'].map(loc_state2idx)
test_df['location_country'] = test_df['location_country'].map(loc_country2idx)
#train_df['age'] = train_df['age'].fillna(int(train_df['age'].mean()))
train_df['age'] = train_df['age'].fillna(int(1))
train_df['age'] = train_df['age'].apply(age_map)
#test_df['age'] = test_df['age'].fillna(int(test_df['age'].mean()))
test_df['age'] = test_df['age'].fillna(int(1))
test_df['age'] = test_df['age'].apply(age_map)
# book 파트 인덱싱
category2idx = {v:k for k,v in enumerate(context_df['category'].unique())}
publisher2idx = {v:k for k,v in enumerate(context_df['publisher'].unique())}
language2idx = {v:k for k,v in enumerate(context_df['language'].unique())}
author2idx = {v:k for k,v in enumerate(context_df['book_author'].unique())}
year2idx = {v:k for k,v in enumerate(context_df['year'].unique())}
train_df['category'] = train_df['category'].map(category2idx)
train_df['publisher'] = train_df['publisher'].map(publisher2idx)
train_df['language'] = train_df['language'].map(language2idx)
train_df['book_author'] = train_df['book_author'].map(author2idx)
train_df['year'] = train_df['year'].map(year2idx)
test_df['category'] = test_df['category'].map(category2idx)
test_df['publisher'] = test_df['publisher'].map(publisher2idx)
test_df['language'] = test_df['language'].map(language2idx)
test_df['book_author'] = test_df['book_author'].map(author2idx)
test_df['year'] = test_df['year'].map(year2idx)
idx = {
"loc_city2idx":loc_city2idx,
"loc_state2idx":loc_state2idx,
"loc_country2idx":loc_country2idx,
"category2idx":category2idx,
"year2idx":year2idx,
"publisher2idx":publisher2idx,
"language2idx":language2idx,
"author2idx":author2idx
}
return idx, train_df, test_df
def context_data_load(args):
"""
Parameters
----------
Args:
data_path : str
데이터 경로
----------
"""
######################## DATA LOAD
users = pd.read_csv(args.data_path + 'users.csv')
books = pd.read_csv(args.data_path + 'books.csv')
train = pd.read_csv(args.data_path + 'train_ratings.csv')
test = pd.read_csv(args.data_path + 'test_ratings.csv')
sub = pd.read_csv(args.data_path + 'sample_submission.csv')
ids = pd.concat([train['user_id'], sub['user_id']]).unique()
isbns = pd.concat([train['isbn'], sub['isbn']]).unique()
idx2user = {idx:id for idx, id in enumerate(ids)}
idx2isbn = {idx:isbn for idx, isbn in enumerate(isbns)}
user2idx = {id:idx for idx, id in idx2user.items()}
isbn2idx = {isbn:idx for idx, isbn in idx2isbn.items()}
train['user_id'] = train['user_id'].map(user2idx)
sub['user_id'] = sub['user_id'].map(user2idx)
test['user_id'] = test['user_id'].map(user2idx)
users['user_id'] = users['user_id'].map(user2idx)
train['isbn'] = train['isbn'].map(isbn2idx)
sub['isbn'] = sub['isbn'].map(isbn2idx)
test['isbn'] = test['isbn'].map(isbn2idx)
books['isbn'] = books['isbn'].map(isbn2idx)
idx, context_train, context_test = process_context_data(users, books, train, test)
field_dims = np.array([len(user2idx), len(isbn2idx),
7, len(idx['loc_city2idx']), len(idx['loc_state2idx']), len(idx['loc_country2idx']),
len(idx['category2idx']), len(idx['year2idx']),
len(idx['publisher2idx']), len(idx['language2idx']), len(idx['author2idx'])], dtype=np.uint32)
data = {
'train':context_train,
'test':context_test.drop(['rating'], axis=1),
'field_dims':field_dims,
'users':users,
'books':books,
'sub':sub,
'idx2user':idx2user,
'idx2isbn':idx2isbn,
'user2idx':user2idx,
'isbn2idx':isbn2idx,
}
return data
def context_data_split(args, data):
"""
Parameters
----------
Args:
test_size : float
Train/Valid split 비율을 입력합니다.
seed : int
랜덤 seed 값
----------
"""
X_train, X_valid, y_train, y_valid = train_test_split(
data['train'].drop(['rating'], axis=1),
data['train']['rating'],
test_size=args.test_size,
random_state=args.seed,
shuffle=True
)
data['X_train'], data['X_valid'], data['y_train'], data['y_valid'] = X_train, X_valid, y_train, y_valid
return data
def context_data_loader(args, data):
"""
Parameters
----------
Args:
batch_size : int
데이터 batch에 사용할 데이터 사이즈
data_shuffle : bool
data shuffle 여부
----------
"""
train_dataset = TensorDataset(torch.LongTensor(data['X_train'].values), torch.LongTensor(data['y_train'].values))
valid_dataset = TensorDataset(torch.LongTensor(data['X_valid'].values), torch.LongTensor(data['y_valid'].values))
test_dataset = TensorDataset(torch.LongTensor(data['test'].values))
train_dataloader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=args.data_shuffle)
valid_dataloader = DataLoader(valid_dataset, batch_size=args.batch_size, shuffle=args.data_shuffle)
test_dataloader = DataLoader(test_dataset, batch_size=args.batch_size, shuffle=False)
data['train_dataloader'], data['valid_dataloader'], data['test_dataloader'] = train_dataloader, valid_dataloader, test_dataloader
return data