Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Алгоритм Swivel и его применения

Алгоритм Swivel и его применения

Константин Славнов (source{d}, Junior Engineer, Machine Learning) @ Moscow Python Meetup 57

"Я расскажу вам о популярном методе построения векторных представлений для элементов последовательности, например, для слов в тексте.
Такие методы применяются в машинном обучении для того, чтобы облегчить работу с категориальными признаками, коими являются, например, слова, вершины графа или любое неупорядоченное множество элементов. Для предобработки такого рода данных используются специальные методы вложения в непрерывное векторное пространство. Я расскажу об одном из таких методов Swivel, продемонстрирую как применять его в текстовых и графовых задачах, а так же расскажу как подобный подход можно применять к анализу исходного кода языка Python".
Видео: http://www.moscowpython.ru/meetup/57/swivel-algo/

Moscow Python Meetup

June 26, 2018
Tweet

More Decks by Moscow Python Meetup

Other Decks in Programming

Transcript

  1. 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 ⎤ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎦
  2. Хеширование ⇒ [ 1, 1] ⇒ [ 0,-1] ⇒ [

    0, 1] ⇒ [-1, 1] ⇒ [ 2, 0] aka the hashing trick
  3. Хеширование в sklearn from sklearn.feature_extraction import FeatureHasher fruits = ["cherry",

    "peach", "apple", "grapes", "strawberry"] hasher = FeatureHasher(n_features=2, input_type="string") hasher.transform(fruits)
  4. Кодирование вещественным признаком ⇒ 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 ⎤ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎦
  5. Итог ☑ Быстро ☑ С любыми признаками ❌ Не конструктивно

    Если у признака есть структура — ее можно использовать.
  6. 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 Векторные вложения
  7. Вложение в векторное пространство "apple" ⇔ V 1 "peach" ⇔

    V 2 "cat" ⇔ V 3 similarity(V 1 , V 2 ) < similarity(V 1 , V 3 )
  8. Контекст — слово Пример: "Слова — это всего лишь слова."

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

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

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

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

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

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

    V i ⊤ V j Vi ⊤ Vj = PMI(A)ij слова это всего лишь слова это всего лишь
  15. Как оценить ? Pointwise mutual information: V i ⊤ V

    j PMI(x; y) ≡ log . p(x, y) p(x) p(y) слова это всего лишь слова это всего лишь
  16. Как оценить ? 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 слова это всего лишь слова это всего лишь
  17. Как оценить ? 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 слова это всего лишь слова это всего лишь
  18. Итого • Снижает размерность данных. • Похожий контекст — похожие

    вектора. • Логический вывод: . V (девушка) − V (парень) ≃ V (королева) − V (король)
  19. Примеры моделей • Word2vec — Статья на ArXiV, fastText. •

    GloVe — Статья, реализация. • Swivel — Статья на ArXiV, реализация на tensorflow, наш форк.
  20. Swivel ✅ Работает с матрицей слово-контекст ✅ Масштабируется с размером

    словаря ✅ Горизонтально масштабируется (GPUs & nodes)
  21. 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.
  22. 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
  23. 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
  24. 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. >>>
  25. 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. >>>
  26. 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
  27. 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. >>>
  28. 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. >>>
  29. 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. >>>
  30. 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. >>>
  31. Id2Vec Строим векторное представление для идентификаторов в коде. Как построить

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

    матрицу слово-контекст ? количество раз когда и встретились вместе  Aij Aij = i j Vi ⊤ Vj ≈ P M Iij = log Aij ∑ Aij ∑ N k=1 Aik ∑ N k=1 Ajk
  33. afoo qux myfoo baz mfoo wibble dofoo quux dfoo testing

    ifoo Ближайшие имена к “foo”
  34. Логический вывод V (bug) − V (test) + V (expect)

    ≈ V (suppress) V (database) − V (query) + V (tune) ≈ V (settings) V (send) − V (receive) + V (pop) ≈ V (push)
  35. Очепятки • • • V (recieve) ≈ V (receive) V

    (grey) ≈ V (gray) V (calback) ≈ V (callbak) ≈ V (callback)
  36. Id2vec Реализация доступна на Github. $ python3 -m sourced.ml repo2coocc

    ... $ python3 -m sourced.ml id2vec-preproc ... $ python3 -m sourced.ml id2vec-train ... 01. 02. 03.
  37. Разбиение кода на сниппеты 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.
  38. Разбиение кода на сниппеты 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.
  39. Разбиение кода на сниппеты 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.
  40. Разбиение кода на сниппеты 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.
  41. Разбиение кода на сниппеты 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.
  42. Разбиение кода на сниппеты 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.
  43. Разбиение кода на сниппеты 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.
  44. 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.
  45. 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.
  46. Конец  [email protected]  kslavnov  zurk  blog.sourced.tech 

    Awesome #MLonCode Презентация: zurk.github.io/moscow-python-06-2018