Slide 1

Slide 1 text

Алгоритм Swivel и его приложения Константин Славнов, source{d}

Slide 2

Slide 2 text

Категориальные признаки Любые признаки без порядка. Как с ними работать? Города, страны Тексты Графы • ...

Slide 3

Slide 3 text

Кодируем! • One-hot-encoding • Хэширование • Кодирование вещественным признаком

Slide 4

Slide 4 text

One-hot-encoding ⇒ ⇒ ⇒ [ 1, 0, 0 ] [ 0, 1, 0 ] [ 0, 0, 1 ]

Slide 5

Slide 5 text

One-hot-encoding ⇒ ⇒ ⇒ [ 1, 0, 0 ] [ 0, 1, 0 ] [ 0, 0, 1 ] ⎡ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎣ 2 0.5 1 0.75 3 0.9 ⋮ ⋮ ⋮ 5 0.2 ⎤ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎦ ⟹ ⎡ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎣ 1 0 0 2 0.5 0 1 0 1 0.75 0 1 0 3 0.9 ⋮ ⋮ ⋮ ⋮ ⋮ 0 0 1 5 0.2 ⎤ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎦

Slide 6

Slide 6 text

Хеширование ⇒ [ 1, 1] ⇒ [ 0,-1] ⇒ [ 0, 1] ⇒ [-1, 1] ⇒ [ 2, 0] aka the hashing trick

Slide 7

Slide 7 text

Хеширование в sklearn from sklearn.feature_extraction import FeatureHasher fruits = ["cherry", "peach", "apple", "grapes", "strawberry"] hasher = FeatureHasher(n_features=2, input_type="string") hasher.transform(fruits)

Slide 8

Slide 8 text

Кодирование вещественным признаком ⇒ 250 ⇒ 150 ⇒ 100

Slide 9

Slide 9 text

Кодирование вещественным признаком ⇒ 250 ⇒ 150 ⇒ 100 ⎡ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎣ 2 0.5 1 0.75 3 0.9 ⋮ ⋮ ⋮ 5 0.2 ⎤ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎦ ⎡ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎣ 250 100 200 ⋮ 100 ⎤ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎦ ⟹ ⎡ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎣ 250 2 0.5 150 1 0.75 150 3 0.9 ⋮ ⋮ ⋮ 100 5 0.2 ⎤ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎦ ⎡ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎣ 250 100 200 ⋮ 100 ⎤ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎦

Slide 10

Slide 10 text

Итог ☑ Быстро ☑ С любыми признаками ❌ Не конструктивно Если у признака есть структура — ее можно использовать.

Slide 11

Slide 11 text

tensorflow fa-floppy-oat unaligned vector ttypes types const unaligned vec int unaligned vector ttypes types int const unaligned vec example statistics norm normalized squared regularizations regularizations status initialize construction kernel opkernel context error iferror return tfreturn context attr get symmetric error iferror return tfreturn context attr get symmetric shrinkage symmetric symmetric status shrink weight shrinked std max std abs weight shrinkage shrinked std copysign shrinked weight eigen tensor eigen major row eigen shrink eigen tensor eigen major row weights weights sign weights abs weights constant shrinkage cwise max weights constant shrinkage cwise max weights constant symmetric symmetric symmetric symmetric shrinkage and assign copy disallow tfdisallow regularizations model weights example example statistics and compute example norm weighted wxand num partitions model weights model weights regularizations regularization example label example label example weight example weight norm squared norm squared features sparse std ptr unique int unaligned vector indices std ptr unique float unaligned vector values std vector features sparse features sparse dense vector eigen map tensor eigen tensor eigen major row row eigen map tensor eigen tensor eigen major row data matrix data index row data matrix dimension data matrix dimension ttypes types const matrix data matrix int index row std vector std ptr unique dense vector dense vectors example label example weight norm squared examples model weights model weights model weights delta update weights eigen device pool thread device example example bounded delta dual normalized sparse weights size example features sparse features sparse example features sparse feature weights feature weights sparse weights int features sparse indices size feature value features sparse values features sparse values feature weights deltas features sparse indices feature value bounded delta dual normalized dense weights size example dense vector dense vector example dense vectors ttypes types vec deltas dense weights deltas deltas device device deltas dense vector row deltas constant bounded delta dual normalized status initialize context kernel opkernel context input list opinput inputs sparse weights error iferror return tfreturn context input list inputs sparse weights input list opinput dense inputs weights error iferror return tfreturn context input list dense inputs weights list opoutput output outputs sparse weights error iferror return tfreturn context list output outputs sparse weights list opoutput output dense outputs weights error iferror return tfreturn context list output dense outputs weights intialize weights input list opinput inputs weight list opoutput output outputs weight std vector feature weights feature weights inputs weight size tensor delta outputs weight allocate inputs weight shape delta deltas delta flat deltas set zero feature weights back emplace feature weights inputs weight flat deltas intialize weights inputs sparse weights outputs sparse weights sparse weights intialize weights dense inputs weights dense outputs weights dense weights status feature weights ttypes types vec nominals ttypes types vec deltas std vector feature weights sparse weights std vector feature weights dense weights example and assign copy disallow tfdisallow model weights example statistics example and compute example norm weighted wxand num partitions model weights model weights regularizations regularization example statistics result result norm normalized squared norm squared regularization symmetric features sparse size example features sparse features sparse features sparse model weights feature weights sparse weights model weights sparse weights int features sparse indices size int feature index features sparse indices feature value features sparse values features sparse values feature weight sparse weights nominals feature index sparse weights deltas feature index num partitions result feature value regularization shrink feature weight dense vectors size example dense vector dense vector dense vectors model weights feature weights dense weights model weights dense weights eigen tensor eigen major row feature weights dense weights nominals dense weights deltas dense weights deltas constant num partitions eigen tensor eigen major row prediction dense vector row regularization eigen shrink feature weights sum result prediction result examples examples example example example index examples example index examples num examples size features num features num status initialize context kernel opkernel context features num sparse features num sparse values with dense features num features num features num sparse dense features num input list opinput example indices inputs sparse error iferror return tfreturn context input list example indices inputs sparse input list opinput feature indices inputs sparse error iferror return tfreturn context input list feature indices inputs sparse input list opinput feature inputs sparse values features num sparse values with error iferror return tfreturn context input list feature inputs sparse values tensor example weights error iferror return tfreturn context input example weights example weights example weights flat examples num example weights size tensor example labels error iferror return tfreturn context input example labels example labels example labels flat input list Векторные вложения

Slide 12

Slide 12 text

Вложение в векторное пространство "apple" ⇔ V 1 "peach" ⇔ V 2 "cat" ⇔ V 3 similarity(V 1 , V 2 ) < similarity(V 1 , V 3 )

Slide 13

Slide 13 text

Вложение в векторное пространство "apple" ⇔ V 1 "peach" ⇔ V 2 "cat" ⇔ V 3 similarity(V 1 , V 2 ) = V 1 ⊤ V 2

Slide 14

Slide 14 text

Как оценить ? V i ⊤ V j

Slide 15

Slide 15 text

Контекст — слово Пример: "Слова — это всего лишь слова." Ширина контекста — 1. слова это всего лишь слова это всего лишь

Slide 16

Slide 16 text

Контекст — слово Пример: "Слова — это всего лишь слова." слова это всего лишь слова это всего лишь

Slide 17

Slide 17 text

Контекст — слово Пример: "Слова — это всего лишь слова." слова это всего лишь слова это всего лишь

Slide 18

Slide 18 text

Контекст — слово Пример: "Слова — это всего лишь слова." слова это всего лишь слова это всего лишь

Slide 19

Slide 19 text

Контекст — слово Пример: "Слова — это всего лишь слова." слова это всего лишь слова это всего лишь

Slide 20

Slide 20 text

Контекст — слово Пример: "Слова — это всего лишь слова." слова это всего лишь слова это всего лишь

Slide 21

Slide 21 text

Как оценить ? Пример: "Слова — это всего лишь слова." V i ⊤ V j Vi ⊤ Vj = PMI(A)ij слова это всего лишь слова это всего лишь

Slide 22

Slide 22 text

Как оценить ? Pointwise mutual information: V i ⊤ V j PMI(x; y) ≡ log . p(x, y) p(x) p(y) слова это всего лишь слова это всего лишь

Slide 23

Slide 23 text

Как оценить ? Pointwise mutual information: V i ⊤ V j PMI(x; y) ≡ log . x = это y = лишь = = 0. p(x, y) p(x) p(y) p(это, лишь) p(это) p(лишь) 0 1/4 ⋅ 1/4 слова это всего лишь слова это всего лишь

Slide 24

Slide 24 text

Как оценить ? Pointwise mutual information: V i ⊤ V j PMI(x; y) ≡ log . x = это y = всего = = 2. p(x, y) p(x) p(y) p(это, всего) p(это) p(всего) 1/8 1/4 ⋅ 1/4 слова это всего лишь слова это всего лишь

Slide 25

Slide 25 text

V i ⊤ V j ≈ log p(x, y) p(x) p(y)

Slide 26

Slide 26 text

Итого • Снижает размерность данных. • Похожий контекст — похожие вектора. • Логический вывод: . V (девушка) − V (парень) ≃ V (королева) − V (король)

Slide 27

Slide 27 text

Быстро. Мощно.

Slide 28

Slide 28 text

Примеры моделей • Word2vec — Статья на ArXiV, fastText. • GloVe — Статья, реализация. • Swivel — Статья на ArXiV, реализация на tensorflow, наш форк.

Slide 29

Slide 29 text

Swivel ✅ Работает с матрицей слово-контекст ✅ Масштабируется с размером словаря ✅ Горизонтально масштабируется (GPUs & nodes)

Slide 30

Slide 30 text

Swivel sharding

Slide 31

Slide 31 text

Swivel sharding

Slide 32

Slide 32 text

Анализируем код

Slide 33

Slide 33 text

Id2Vec Строим векторное представление для идентификаторов в коде. Как построить матрицу слово-контекст ? Aij

Slide 34

Slide 34 text

class Database: def connect(self, user, password, host, port): self._tcp_socket_connect(host, port) try: self._authenticate(user, password) except AuthenticationError as e: self.socket.close() raise e from None 01. 02. 03. 04. 05. 06. 07. 08.

Slide 35

Slide 35 text

Предобработка _tcp_socket_connect -> [tcp, socket, connect] AuthenticationError -> [authentication, error] authentication, authenticate -> authenticate 01. 02. 03.

Slide 36

Slide 36 text

class Database: def connect(self, user, password, host, port): self._tcp_socket_connect(host, port) try: self._authenticate(user, password) except AuthenticationError as e: self.socket.close() raise e from None database, connect , user , password , host , port , tcp, socket , authenticate , error, close 01. 02. 03. 04. 05. 06. 07. 08. >>> 2 2 2 2 2 2 2

Slide 37

Slide 37 text

class Database: def connect(self, user, password, host, port): self._tcp_socket_connect(host, port) try: self._authenticate(user, password) except AuthenticationError as e: self.socket.close() raise e from None connect , user , password , host , port , tcp, socket , authenticate , error, close 01. 02. 03. 04. 05. 06. 07. 08. >>> 2 2 2 2 2 2 2

Slide 38

Slide 38 text

class Database: def connect(self, user, password, host, port): self._tcp_socket_connect(host, port) try: self._authenticate(user, password) except AuthenticationError as e: self.socket.close() raise e from None connect, user, password, host, port 01. 02. 03. 04. 05. 06. 07. 08. >>>

Slide 39

Slide 39 text

class Database: def connect(self, user, password, host, port): self._tcp_socket_connect(host, port) try: self._authenticate(user, password) except AuthenticationError as e: self.socket.close() raise e from None tcp, socket, connect, host, port 01. 02. 03. 04. 05. 06. 07. 08. >>>

Slide 40

Slide 40 text

class Database: def connect(self, user, password, host, port): self._tcp_socket_connect(host, port) try: self._authenticate(user, password) except AuthenticationError as e: self.socket.close() raise e from None authenticate , user, password, error, socket, close 01. 02. 03. 04. 05. 06. 07. 08. >>> 2

Slide 41

Slide 41 text

class Database: def connect(self, user, password, host, port): self._tcp_socket_connect(host, port) try: self._authenticate(user, password) except AuthenticationError as e: self.socket.close() raise e from None authenticate, user, password 01. 02. 03. 04. 05. 06. 07. 08. >>>

Slide 42

Slide 42 text

class Database: def connect(self, user, password, host, port): self._tcp_socket_connect(host, port) try: self._authenticate(user, password) except AuthenticationError as e: self.socket.close() raise e from None authenticate, error, socket, close 01. 02. 03. 04. 05. 06. 07. 08. >>>

Slide 43

Slide 43 text

class Database: def connect(self, user, password, host, port): self._tcp_socket_connect(host, port) try: self._authenticate(user, password) except AuthenticationError as e: self.socket.close() raise e from None authenticate, error 01. 02. 03. 04. 05. 06. 07. 08. >>>

Slide 44

Slide 44 text

class Database: def connect(self, user, password, host, port): self._tcp_socket_connect(host, port) try: self._authenticate(user, password) except AuthenticationError as e: self.socket.close() raise e from None socket, close 01. 02. 03. 04. 05. 06. 07. 08. >>>

Slide 45

Slide 45 text

connect host port tcp error database close password user socket authenticate

Slide 46

Slide 46 text

connect host port tcp error database close password user socket authenticate

Slide 47

Slide 47 text

connect host port tcp error database close password user socket authenticate

Slide 48

Slide 48 text

connect host port tcp error database close password user socket authenticate

Slide 49

Slide 49 text

connect host port tcp error database close password user socket authenticate

Slide 50

Slide 50 text

connect host port tcp error database close password user socket authenticate

Slide 51

Slide 51 text

connect host port tcp error database close password user socket authenticate

Slide 52

Slide 52 text

connect host port tcp error database close password user socket authenticate

Slide 53

Slide 53 text

connect host port tcp error database close password user socket authenticate

Slide 54

Slide 54 text

connect host port tcp error database close password user socket authenticate

Slide 55

Slide 55 text

Id2Vec Строим векторное представление для идентификаторов в коде. Как построить матрицу слово-контекст ? количество раз когда и встретились вместе  Aij Aij = i j

Slide 56

Slide 56 text

Id2Vec Строим векторное представление для идентификаторов в коде. Как построить матрицу слово-контекст ? количество раз когда и встретились вместе  Aij Aij = i j Vi ⊤ Vj ≈ P M Iij = log Aij ∑ Aij ∑ N k=1 Aik ∑ N k=1 Ajk

Slide 57

Slide 57 text

Результаты

Slide 58

Slide 58 text

afoo qux myfoo baz mfoo wibble dofoo quux dfoo testing ifoo Ближайшие имена к “foo”

Slide 59

Slide 59 text

Логический вывод V (bug) − V (test) + V (expect) ≈ V (suppress) V (database) − V (query) + V (tune) ≈ V (settings) V (send) − V (receive) + V (pop) ≈ V (push)

Slide 60

Slide 60 text

Очепятки • • • V (recieve) ≈ V (receive) V (grey) ≈ V (gray) V (calback) ≈ V (callbak) ≈ V (callback)

Slide 61

Slide 61 text

Id2vec Реализация доступна на Github. $ python3 -m sourced.ml repo2coocc ... $ python3 -m sourced.ml id2vec-preproc ... $ python3 -m sourced.ml id2vec-train ... 01. 02. 03.

Slide 62

Slide 62 text

Разбиение кода на сниппеты

Slide 63

Slide 63 text

Разбиение кода на сниппеты import numpy as np seed = 42 np.random.seed(seed) print(np.random.randint(10)) from sklearn.cluster import KMeans X = np.array([[1, 2], [1, 4]]) kmeans = KMeans(2).fit(X) print(kmeans.labels_) 01. 02. 03. 04. 05. 06. 07. 08.

Slide 64

Slide 64 text

Разбиение кода на сниппеты import numpy as np seed = 42 np.random.seed(seed) print(np.random.randint(10)) from sklearn.cluster import KMeans X = np.array([[1, 2], [1, 4]]) kmeans = KMeans(2).fit(X) print(kmeans.labels_) 01. 02. 03. 04. 05. 06. 07. 08.

Slide 65

Slide 65 text

Разбиение кода на сниппеты import numpy as np seed = 42 np.random.seed(seed) print(np.random.randint(10)) from sklearn.cluster import KMeans X = np.array([[1, 2], [1, 4]]) kmeans = KMeans(2).fit(X) print(kmeans.labels_) 01. 02. 03. 04. 05. 06. 07. 08.

Slide 66

Slide 66 text

Разбиение кода на сниппеты import numpy as np seed = 42 np.random.seed(seed) print(np.random.randint(10)) from sklearn.cluster import KMeans X = np.array([[1, 2], [1, 4]]) kmeans = KMeans(2).fit(X) print(kmeans.labels_) 01. 02. 03. 04. 05. 06. 07. 08.

Slide 67

Slide 67 text

Разбиение кода на сниппеты import numpy as np seed = 42 np.random.seed(seed) print(np.random.randint(10)) from sklearn.cluster import KMeans X = np.array([[1, 2], [1, 4]]) kmeans = KMeans(2).fit(X) print(kmeans.labels_) 01. 02. 03. 04. 05. 06. 07. 08.

Slide 68

Slide 68 text

Разбиение кода на сниппеты import numpy as np seed = 42 np.random.seed(seed) print(np.random.randint(10)) from sklearn.cluster import KMeans X = np.array([[1, 2], [1, 4]]) kmeans = KMeans(2).fit(X) print(kmeans.labels_) 01. 02. 03. 04. 05. 06. 07. 08.

Slide 69

Slide 69 text

Разбиение кода на сниппеты import numpy as np seed = 42 np.random.seed(seed) print(np.random.randint(10)) from sklearn.cluster import KMeans X = np.array([[1, 2], [1, 4]]) kmeans = KMeans(2).fit(X) print(kmeans.labels_) 01. 02. 03. 04. 05. 06. 07. 08.

Slide 70

Slide 70 text

Пример Python Data Science Handbook - Linear Regression.

Slide 71

Slide 71 text

import matplotlib.pyplot as plt import seaborn as sns; sns.set() import numpy as np rng = np.random.RandomState(1) x = 10 * rng.rand(50) y = 2 * x - 5 + rng.randn(50) plt.scatter(x, y); from sklearn.linear_model import LinearRegression model = LinearRegression(fit_intercept=True) model.fit(x[:, np.newaxis], y) xfit = np.linspace(0, 10, 1000) yfit = model.predict(xfit[:, np.newaxis]) 01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12.

Slide 72

Slide 72 text

import matplotlib.pyplot as plt import seaborn as sns; sns.set() import numpy as np rng = np.random.RandomState(1) x = 10 * rng.rand(50) y = 2 * x - 5 + rng.randn(50) plt.scatter(x, y); from sklearn.linear_model import LinearRegression model = LinearRegression(fit_intercept=True) model.fit(x[:, np.newaxis], y) xfit = np.linspace(0, 10, 1000) yfit = model.predict(xfit[:, np.newaxis]) 01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12.

Slide 73

Slide 73 text

TL; DR • Взять задачу • Построить матрицу слово-контекст • Запустить Swivel • ??? • PROFIT!

Slide 74

Slide 74 text

Конец  [email protected]  kslavnov  zurk  blog.sourced.tech  Awesome #MLonCode Презентация: zurk.github.io/moscow-python-06-2018

Slide 75

Slide 75 text

Матричная факторизация