-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02-TextEncodeProcess.py
More file actions
184 lines (104 loc) · 3.34 KB
/
02-TextEncodeProcess.py
File metadata and controls
184 lines (104 loc) · 3.34 KB
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
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import polars as pl
import numpy as np
import os
from datetime import datetime
from tqdm.auto import tqdm
from pymongo import MongoClient
import pymongo
import seaborn as sns
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch.utils.data import DataLoader, Dataset
import random
from sklearn.metrics import classification_report, balanced_accuracy_score, accuracy_score
# In[2]:
torch.manual_seed(42)
random.seed(42)
np.random.seed(42)
# In[3]:
def to_int_list(x):
x = x[1:-1].split(' ')
x = [int(i) for i in x if i != '']
return x
# In[4]:
products = pl.read_parquet('data/product_properties.parquet')
search = pl.read_parquet('data/search_query.parquet')
# In[5]:
search = search.with_columns(pl.col('query').map_elements(to_int_list, return_dtype=pl.List(pl.Int64)))
products = products.with_columns(pl.col('name').map_elements(to_int_list, return_dtype=pl.List(pl.Int64)))
# In[6]:
print(len(search))
print(len(products))
# In[7]:
class TextDataset(Dataset):
def __init__(self, col):
self.data = np.asarray([list(x) for x in col])
self.data = torch.from_numpy(self.data).long()
def __len__(self):
return self.data.shape[0]
def __getitem__(self, idx):
return self.data[idx, :]
# In[8]:
class Encoder(nn.Module):
def __init__(self, tokens=256, dims=64, layers=2):
super().__init__()
self.emb = nn.Embedding(tokens, dims)
self.layers = nn.LSTM(dims, dims, num_layers=layers, batch_first=True, bidirectional=True)
self.final = nn.Linear(2 * dims, dims)
pass
def forward(self, x):
x = self.emb(x)
x = self.layers(x)[0][:, -1, :]
x = self.final(x)
x = torch.tanh(x)
return x
class Decoder(nn.Module):
def __init__(self, length=16, tokens=256, dims=64, layers=2):
super().__init__()
self.length = length
self.layers = nn.LSTM(dims, dims, num_layers=layers, batch_first=True, bidirectional=True)
self.final = nn.Linear(2 * dims, tokens)
pass
def forward(self, x):
x = x.unsqueeze(1).repeat(1, self.length, 1)
x = self.layers(x)[0]
x = self.final(x)
return x
# In[9]:
Encoder()(torch.ones((3, 16)).long()).shape
# In[10]:
Decoder()(Encoder()(torch.ones((3, 16)).long())).shape
# In[11]:
device = 'cuda' if torch.cuda.is_available() else 'cpu'
# In[12]:
name = DataLoader(TextDataset(products['name']), shuffle=False, batch_size=10000)
query = DataLoader(TextDataset(search['query']), shuffle=False, batch_size=10000)
# In[13]:
encoder = Encoder().to(device)
# In[14]:
encoder.load_state_dict(torch.load('encoder.pth'))
encoder.eval()
# In[15]:
def embedd(dl):
embds = []
for x in tqdm(dl, leave=False):
x = x.to(device)
pred = encoder(x).cpu().detach()
embds.append(pred)
embds = torch.concat(embds, dim=0).numpy()
return embds
# In[16]:
name_e = embedd(name)
products = products.with_columns(pl.Series('name', name_e.tolist()).cast(pl.List(pl.Float32)))
del name_e
# In[17]:
query_e = embedd(query)
search = search.with_columns(pl.Series('query', query_e.tolist()).cast(pl.List(pl.Float32)))
del query_e
# In[18]:
products.write_parquet('product_properties.parquet')
search.write_parquet('search_query.parquet')