recomendation_system.py 5.03 KB
Newer Older
DmitSPopov's avatar
DmitSPopov committed
1
2
3
4
5
import numpy as np
from scipy import sparse
from sklearn.preprocessing import normalize
from random import randint
from web_setting import db
6
from models.all_models import ClickHistory
DmitSPopov's avatar
DmitSPopov committed
7
from collections import Counter
8
from api.api_advertisment import all_advertisments
DmitSPopov's avatar
DmitSPopov committed
9
10


11
def calc_recomendation_by_tags(user_data, all_data):
DmitSPopov's avatar
DmitSPopov committed
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
    row_column_index = []
    for i in range(len(user_data)):
        row_column_index.append(randint(0, 10))

    rows, rows_position = np.unique(row_column_index, return_inverse=True)
    cols, columns_position = np.unique(list(user_data.keys()), return_inverse=True)

    interaction_Sparse = sparse.csr_matrix((list(user_data.values()), (rows_position, columns_position)),
                                           shape=(len(all_data), len(all_data)))
    normalized_matrix = normalize(interaction_Sparse, norm="l2", axis=1)
    symmertic_matrix = normalized_matrix.T * normalized_matrix
    symmertic_matrix.todense()
    result = [all_data[i + 1] for i in symmertic_matrix[0].toarray().argsort()[0]]

    interaction_Sparse_transpose = interaction_Sparse.transpose(copy=True)
    normalized_matrix_transpose = normalize(interaction_Sparse_transpose, norm="l2", axis=1)

    symmertic_matrix_transpose = normalized_matrix * normalized_matrix_transpose * normalized_matrix

    result = [all_data[i + 1] for i in symmertic_matrix_transpose[0].toarray().argsort()[0]]

    result_id = []
    for i in range(len(result)):
        result_id.append(list(all_data.keys())[list(all_data.values()).index(result[i])])

    for x in result_id:
        if result_id.count(x) > 1:
            result_id.remove(x)
            for index in list(all_data.keys()):
                if index not in result_id:
                    result_id.insert(x, index)

    return result_id


DmitSPopov's avatar
DmitSPopov committed
47
def calc_recomendation_by_location(user_data, all_data, tags_recomendation):
DmitSPopov's avatar
DmitSPopov committed
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

    row_column_index = []
    for i in range(len(tags_recomendation)):
        row_column_index.append(randint(0, 10))

    destination = []
    for i in range(len(all_data)):
        destination.append(((list(all_data.values())[i][0] - list(user_data.values())[0][0]) ** 2 +
                            (list(all_data.values())[i][1] - list(user_data.values())[0][1]) ** 2) ** 0.5)

    priority = []
    for i in range(len(tags_recomendation)):
        priority.append(i / len(tags_recomendation))

    priority.sort(reverse=True)
    rows, rows_position = np.unique(row_column_index, return_inverse=True)
    cols, columns_position = np.unique(priority, return_inverse=True)

    interaction_Sparse = sparse.csr_matrix((tags_recomendation, (rows_position, columns_position)),
                                           shape=(len(destination), len(destination)))

    normalized_matrix = normalize(interaction_Sparse, norm="l2", axis=1)
    symmertic_matrix = normalized_matrix.T * normalized_matrix
    symmertic_matrix.todense()

    keys = list(all_data.keys())
    for key, i in zip(keys, range(len(all_data))):
        all_data[key] = destination[i]

    result = [all_data[i + 1] for i in symmertic_matrix[0].toarray().argsort()[0]]

    interaction_Sparse_transpose = interaction_Sparse.transpose(copy=True)
    normalized_matrix_transpose = normalize(interaction_Sparse_transpose, norm="l2", axis=1)

    symmertic_matrix_transpose = normalized_matrix * normalized_matrix_transpose * normalized_matrix

    result = [all_data[i + 1] for i in symmertic_matrix_transpose[0].toarray().argsort()[0]]

    result_id = []
    for i in range(len(result)):
        result_id.append(list(all_data.keys())[list(all_data.values()).index(result[i])])

    for x in result_id:
        if result_id.count(x) > 1:
            result_id.remove(x)

    return result_id


97
def get_recomendation_by_tags(user_id: int, all_adv=all_advertisments()):
DmitSPopov's avatar
DmitSPopov committed
98
99
100
101
102
103
104
105
106
107
108
    queryset = db.session.query(ClickHistory).filter(ClickHistory.user_id==user_id).all()
    all_tags = []
    for _ in queryset:
        all_tags.append(_.tags_id)

    all_tags.sort()

    user_data = dict(Counter(all_tags))

    all_data = dict()

109
    for _ in all_adv:
DmitSPopov's avatar
DmitSPopov committed
110
111
112
113
114
115
116
117
        tag_id = []
        for val in _['adv_id_tagsadv']:
            tag_id.append(val['connect_tags']['id'])
        all_data[_['id']] = tag_id

    result_id = calc_recomendation_by_tags(user_data, all_data)
    return result_id

118
119
120
121
input_distance_user = {1: [10, 200]}  # key - user_id, [x, y]
input_distance_data = {1: [20, 120], 2: [25, -100], 3: [10, 133], 4: [400, 300], 5: [144, 1322], 6: [122, -10],
                       7: [-120, 1432]}  # key - id_adv

DmitSPopov's avatar
DmitSPopov committed
122
123

def get_recomendation_by_location(user_id: int, location_str: str):
124
125
    location = location_str.split(', ')
    location[0], location[1] = float(location[0]), float(location[1])
126
127
128
129
    distance_user = {user_id: location}
    distance_data = dict()
    all_adv = all_advertisments()
    for _ in all_adv:
130
131
132
        coords = _['connect_coordinates']['coordinates'].split(', ')
        coords[0], coords[1] = float(coords[0]), float(coords[1])
        distance_data[_['id']] = coords
DmitSPopov's avatar
DmitSPopov committed
133

134
    return calc_recomendation_by_location(distance_user, distance_data, get_recomendation_by_tags(user_id, all_adv))