-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrule_based.py
173 lines (128 loc) ยท 6.89 KB
/
rule_based.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
import copy
import numpy as np
import pandas as pd
import random
import torch
from transformers import AutoTokenizer, AutoModel
from sklearn.metrics.pairwise import cosine_similarity
from similarity import content_based_filtering_cosine
class FeatureExtractor:
def __init__(self, model_name):
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
self.model = AutoModel.from_pretrained(model_name).eval()
def mean_pooling(self, model_output, attention_mask):
token_embeddings = model_output[0] #First element of model_output contains all token embeddings
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
def match_question_top1(self, question_string, embedding_matrix) -> int:
encoded_input = self.tokenizer(question_string, padding = True, truncation = True, return_tensors = 'pt')
with torch.no_grad():
output = self.model(**encoded_input)
embedding = self.mean_pooling(output, encoded_input['attention_mask'])
similarity = cosine_similarity(embedding, embedding_matrix)[0]
top1_idx = np.argsort(similarity)[::-1][0].item()
top1_sim = np.sort(similarity)[::-1][0].item()
return top1_idx + 1, top1_sim
class Recommendation:
def __init__(self, document, item, qcate_dict, matrix, embedder, question_category, company,
job_large, job_small, answer, topk):
#data
self.document = document
self.item = item
self.qcate_dict = qcate_dict
self.matrix = matrix
# model
self.embedder = embedder
#user information
self.question_category = str(question_category)
self.company = company
self.job_large = job_large
self.job_small = job_small
self.answer = None if len(answer) == 0 else answer
#setting
self.topk = topk
#filtering
self.fquestion = None
self.fcompany = None
self.fjob = None
def filtering(self):
self.fquestion = self.qcate_dict[self.question_category] #์ง๋ฌธ ํํฐ๋ง
self.fcompany = list(self.document[self.document["company"] == self.company]["doc_id"])
self.job_large = list(self.document[self.document["job_large"] == self.job_large]["doc_id"])
self.job_small = list(self.document[self.document["job_small"] == self.job_small]["doc_id"])
def _process_without_answer(self, tag):
result = tag.sort_values(by=["weight_score", "pro_good_cnt", "doc_view"], ascending = [False, False, False])[["answer_id", "weight_score"]]
answer_ids, scores = result['answer_id'], result['weight_score']
answer_ids = list(answer_ids)[:10]
scores = list(scores)[:10]
high_score = scores[0]
high_score_answers = [answer_id for answer_id, score in zip(answer_ids, scores) if score == high_score]
residue = [answer_id for answer_id, score in zip(answer_ids, scores) if score != high_score]
if len(high_score_answers) >= self.topk:
return random.sample(high_score_answers, self.topk)
else:
result_ids = high_score_answers + random.sample(residue, self.topk - len(high_score_answers))
return result_ids
def recommend_with_company_jobtype(self):
"""
Tag 1 : ์ง๋ฌธ O / ํ์ฌ O / ์ง๋ฌด O
"""
tag1 = self.item.copy()
tag1['weight_score'] = np.zeros(len(self.item))
tag1['weight_score'] += np.where(self.item['answer_id'].isin(self.fquestion), 2, 0)
tag1['weight_score'] += np.where(self.item['doc_id'].isin(self.fcompany), 1, 0)
tag1['weight_score'] += np.where(self.item['doc_id'].isin(self.job_large), 0.7, 0)
tag1['weight_score'] += np.where(self.item['doc_id'].isin(self.job_small), 0.3, 0)
if self.answer != None:
tag1 = tag1.sort_values(by = 'weight_score', ascending = False).iloc[:10]
tag1 = content_based_filtering_cosine(np.array(tag1["answer_id"]), self.matrix[tag1["answer_id"]], self.answer,
self.embedder, self.topk)
return list(tag1)
else:
return self._process_without_answer(tag1)
def recommend_with_jobtype_without_company(self):
"""
Tag 2 : ์ง๋ฌธ O / ํ์ฌ x / ์ง๋ฌด O
"""
tag2 = self.item.copy()
tag2['weight_score'] = np.zeros(len(self.item))
tag2['weight_score'] += np.where(self.item['answer_id'].isin(self.fquestion), 2, 0)
tag2['weight_score'] += np.where(self.item['doc_id'].isin(self.job_large), 1, 0)
tag2['weight_score'] += np.where(self.item['doc_id'].isin(self.job_small), 0.3, 0)
if self.answer != None:
tag2 = tag2.sort_values(by = 'weight_score', ascending = False).iloc[:10]
tag2 = content_based_filtering_cosine(np.array(tag2["answer_id"]), self.matrix[tag2["answer_id"]], self.answer,
self.embedder, self.topk)
return list(tag2)
else:
return self._process_without_answer(tag2)
def recommend_with_company_without_jobtype(self):
"""
Tag 3 : ์ง๋ฌธ O / ํ์ฌ O / ์ง๋ฌด X
"""
tag3 = self.item.copy()
tag3['weight_score'] = np.zeros(len(self.item))
tag3['weight_score'] += np.where(self.item['answer_id'].isin(self.fquestion), 1, 0)
tag3['weight_score'] += np.where(self.item['doc_id'].isin(self.fcompany), 2, 0)
if self.answer != None:
tag3 = tag3.sort_values(by = 'weight_score', ascending = False).iloc[:10]
tag3 = content_based_filtering_cosine(np.array(tag3["answer_id"]), self.matrix[tag3["answer_id"]], self.answer,
self.embedder, self.topk)
return list(tag3)
else:
return self._process_without_answer(tag3)
def recommed_based_popularity(self):
"""
Tag 4 : popularity
"""
tag4 = self.item[self.item["answer_id"].isin(self.fquestion)].sort_values('doc_view', ascending = False)
return list(tag4["answer_id"])[:self.topk]
def recommend_based_expert(self):
"""
Tag 5 : ์ ๋ฌธ๊ฐ ํ๊ฐ
"""
tag5_good = self.item[self.item["answer_id"].isin(self.fquestion)].sort_values(by=['pro_good_cnt',"pro_bad_cnt"], ascending = [False,True])
tag5_bad = self.item[self.item["answer_id"].isin(self.fquestion)].sort_values(by=['pro_bad_cnt',"pro_good_cnt"], ascending = [False,True])
tag5_good = list(tag5_good["answer_id"])[:self.topk//2]
tag5_bad = list(tag5_bad["answer_id"])[:self.topk//2]
return tag5_good, tag5_bad