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
PRO

June 26, 2018
Tweet

More Decks by Moscow Python Meetup

Other Decks in Programming

Transcript

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

    View Slide

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

    View Slide

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

    View Slide

  4. One-hot-encoding



    [ 1, 0, 0 ]
    [ 0, 1, 0 ]
    [ 0, 0, 1 ]

    View Slide

  5. 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









    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  9. Кодирование вещественным признаком
    ⇒ 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









    View Slide

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

    View Slide

  11. 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
    Векторные вложения

    View Slide

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

    View Slide

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

    V
    2

    View Slide

  14. Как оценить
    ?
    V
    i

    V
    j

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    V
    j
    Vi

    Vj
    = PMI(A)ij
    слова
    это
    всего
    лишь
    слова
    это
    всего
    лишь

    View Slide

  22. Как оценить ?
    Pointwise mutual information:
    V
    i

    V
    j
    PMI(x; y) ≡ log .
    p(x, y)
    p(x) p(y) слова
    это
    всего
    лишь
    слова
    это
    всего
    лишь

    View Slide

  23. Как оценить ?
    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
    слова
    это
    всего
    лишь
    слова
    это
    всего
    лишь

    View Slide

  24. Как оценить ?
    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
    слова
    это
    всего
    лишь
    слова
    это
    всего
    лишь

    View Slide

  25. V
    i

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  30. Swivel sharding

    View Slide

  31. Swivel sharding

    View Slide

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

    View Slide

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

    View Slide

  34. 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.

    View Slide

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

    View Slide

  36. 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

    View Slide

  37. 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

    View Slide

  38. 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.
    >>>

    View Slide

  39. 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.
    >>>

    View Slide

  40. 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

    View Slide

  41. 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.
    >>>

    View Slide

  42. 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.
    >>>

    View Slide

  43. 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.
    >>>

    View Slide

  44. 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.
    >>>

    View Slide

  45. connect
    host
    port
    tcp
    error
    database
    close
    password
    user
    socket
    authenticate

    View Slide

  46. connect
    host
    port
    tcp
    error
    database
    close
    password
    user
    socket
    authenticate

    View Slide

  47. connect
    host
    port
    tcp
    error
    database
    close
    password
    user
    socket
    authenticate

    View Slide

  48. connect
    host
    port
    tcp
    error
    database
    close
    password
    user
    socket
    authenticate

    View Slide

  49. connect
    host
    port
    tcp
    error
    database
    close
    password
    user
    socket
    authenticate

    View Slide

  50. connect
    host
    port
    tcp
    error
    database
    close
    password
    user
    socket
    authenticate

    View Slide

  51. connect
    host
    port
    tcp
    error
    database
    close
    password
    user
    socket
    authenticate

    View Slide

  52. connect
    host
    port
    tcp
    error
    database
    close
    password
    user
    socket
    authenticate

    View Slide

  53. connect
    host
    port
    tcp
    error
    database
    close
    password
    user
    socket
    authenticate

    View Slide

  54. connect
    host
    port
    tcp
    error
    database
    close
    password
    user
    socket
    authenticate

    View Slide

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

    View Slide

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

    Vj
    ≈ P M Iij
    = log
    Aij
    ∑ Aij

    N
    k=1
    Aik

    N
    k=1
    Ajk

    View Slide

  57. Результаты

    View Slide

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

    View Slide

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

    View Slide

  60. Очепятки



    V (recieve) ≈ V (receive)
    V (grey) ≈ V (gray)
    V (calback) ≈ V (callbak) ≈ V (callback)

    View Slide

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

    View Slide

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

    View Slide

  63. Разбиение кода на сниппеты
    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.

    View Slide

  64. Разбиение кода на сниппеты
    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.

    View Slide

  65. Разбиение кода на сниппеты
    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.

    View Slide

  66. Разбиение кода на сниппеты
    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.

    View Slide

  67. Разбиение кода на сниппеты
    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.

    View Slide

  68. Разбиение кода на сниппеты
    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.

    View Slide

  69. Разбиение кода на сниппеты
    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.

    View Slide

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

    View Slide

  71. 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.

    View Slide

  72. 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.

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide