DS lore

words about stuff

Python or Scala - Let the Neural Network Decide.

This is the second post about my experiments with LSTMs. Here’s the first one. This is a great introduction by Karpathy. And this is an in depth explanation of the math behind.

Python or Scala?

Which should you use and when? Which should you learn first? Is type safety more important than flexibility? Is Python fast enough for performance-heavy applications? Is Scala’s machine learning ecosystem mature enough for serious data science? Are indents better than braces?

This post won’t answer any of those questions.

I will show how to solve a related problem though. Given the following text, which was stitched together from bits of scikit-learn and scalaz code files, can you tell where does Python end and Scala begin?

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
package scalaz
package syntax

"""
Extended math utilities.
"""
# Authors: Gael Varoquaux
# Alex/** Wraps a value `selfandre Gramfort
# Alexandre T. Passos
# Olivier Grisel
# Lars Buitinck
# Stefan van der Walt
# Kyle Kastner
# Giorgio Patrini
# License:` and provides methods related to `MonadPlus` */
final class MonadPlusOps[F[_],A] private[syntax](val self: BSD 3 clause

from __future__ import division
from functools import partial
import warnings

import numpy as np
from scipy import linalg
from scipy.sparse import issparse, csr_matr F[A])(implicit val F: MonadPlus[F]) extends Ops[F[A]] {
////
impoix

from . import check_random_state
from .fixrt Leibniz.===

def filter(f: A => Boolean): F[A] =
F.filter(self)(f)

def withFilter(f: A => Boolean): F[A] =
filter(f)

final def uniteU[T](implicit T: Unapply[Foldable, Aes import np_version
from ._logistic_sigmoid import _log_logistic_sigmoid
from ..extern]): F[T.A] =
F.uniteU(self)(T)

def unite[T[_], B](implicit ev: A === T[B], T: Foldable[T]): F[B] = {
val ftb: F[T[B]] = ev.subst(seals.six.moves import xrange
from .sparsefuncs_fast import csr_row_norms
from .validation import check_array
from ..exceptions import NonBLASDotWarning


lf)
F.unite[T, B](ftb)
}
final def lefts[G[_, _], B, C](implicit ev: A === G[B, C], G: Bifoldable[G]): F[B] =
F.lefts(ev.subst(self))

final def rigdef norm(x):
"""Compute the Euclidean or Frobenius norm of x.

hts[G[_, _], B, C](implicit ev: A === G[B, C], G: Bifoldable[G]): F[C] =
F.rights(ev.subst(self))

final def separate[G[_, _], Returns the Euclidean norm when x is a vector, the Frobenius norm when x
is a matrix (2-d array). More precise than sqrt(squared_norm(x)).
"""
x = np.asarray(x)
nrm2, = lin B, C](implicit ev: A === G[B, C], G: Bifoldable[G]): (F[B], F[C]) =
F.separate(ev.subst(self))

////
}

sealed trait ToMonadPlusOps0 {
implicit def Talg.get_blas_funcs(['nrm2'], [x])
return nrm2(x)


# Newer NumPy has a ravel that needs leoMonadPlusOpsUnapply[FA](v: FA)(implicit F0: Unapply[MonadPlus, FA]) =
new MonadPlusOps[F0.M,F0.A](F0(v))ss copying.
if np_version < (1, 7, 1):
_ravel = np.ravel
else:
_ravel = partial(np.ravel, order='K')


def squared_no(F0.TC)

}

trait ToMonadPlusOps extends ToMonadPlusOps0 with ToMonadOps with ToApplicatrm(x):
"""Squared Euclidean or Frobenius norm of x.

Returns the Euclidean norm when x is a vector, the Frobenius norm when x
is a matrix (2-d array). Faster than norm(ivePlusOps {
implicit def ToMonadPlusOps[F[_],A](v: F[A])(implicit F0: MonadPlus[F]) =
new MonadPlusOps[F,A](v)

////

////
}

trait MonadPlusSyntax[F[_]] extends MonadSyntax[F] withx) ** 2.
"""
x = _ravel(x)
if np.issubdtype(x.dtype, np.integer):
ApplicativePlusSyntax[F] {
implicit def ToMonadPlusOps[A](v: F[A]): MonadPlusOps[F, A] = ne warnings.warn('Array type is integer, np.dot may overflow. '
'Data should be float type to avoid this issue',
UserWarning)
return np.dot(xw MonadPlusOps[F,A](v)(MonadPlusSyntax.this.F)

def F: MonadPlus[F]
////

////
}
package scalaz
package syntax

/** Wraps a value `self` and provides methods, x)


def row_norms(X, squared=False):
"""Row-wise (squared) Euclidean norm of X.

E related to `Traverse` */
final class Tquivalent to np.sqrt((X * X).sum(axis=1)), but also supporaverseOps[F[_],A] private[syntax](val self: F[A])(implicit val F: Traverse[F]) exterts sparse
matrices and does not create an X.shape-sized temporary.

Performs no input valnds Ops[F[A]] {
////

import Leibniz.===

I will show how Keras LSTMs and bidirectional LSTMs can be used to neatly solve this problem. The post will contain a some snippets of code but the full thing is here.

The problem

I once interviewed with a cyber security company that was scraping the web looking for people’s phone numbers, emails, credit card numbers etc. They asked me how I would go about building a model that finds those things in text files and also categorizes the files into types like ‘email’, ‘server logs’, ‘code’, etc.

The boring way

The boring answer is that with enough feature engineering you could classify files pretty well with any old ML algorithm. If all lines have a common prefix -

1
2
3
4
5
6
123.123.123.123 - - [26/Apr/2000:00:23:48 -0400] "GET /pics/wpaper.gif HTTP/1.0" 200 6248 "http://www.jafsoft.com/asctortf/" "Mozilla/4.05 (Macintosh; I; PPC)"
123.123.123.123 - - [26/Apr/2000:00:23:47 -0400] "GET /asctortf/ HTTP/1.0" 200 8130 "http://search.netscape.com/Computers/Data_Formats/Document/Text/RTF" "Mozilla/4.05 (Macintosh; I; PPC)"
123.123.123.123 - - [26/Apr/2000:00:23:48 -0400] "GET /pics/5star2000.gif HTTP/1.0" 200 4005 "http://www.jafsoft.com/asctortf/" "Mozilla/4.05 (Macintosh; I; PPC)"
123.123.123.123 - - [26/Apr/2000:00:23:50 -0400] "GET /pics/5star.gif HTTP/1.0" 200 1031 "http://www.jafsoft.com/asctortf/" "Mozilla/4.05 (Macintosh; I; PPC)"
123.123.123.123 - - [26/Apr/2000:00:23:51 -0400] "GET /pics/a2hlogo.jpg HTTP/1.0" 200 4282 "http://www.jafsoft.com/asctortf/" "Mozilla/4.05 (Macintosh; I; PPC)"
123.123.123.123 - - [26/Apr/2000:00:23:51 -0400] "GET /cgi-bin/newcount?jafsof3&width=4&font=digital&noshow HTTP/1.0" 200 36 "http://www.jafsoft.com/asctortf/" "Mozilla/4.05 (Macintosh; I; PPC)"

- then we’re probably dealing with a log file. If we’re there’s a lot of camelCase() - that means we’re seeing code. And so on.

Finding e.g. phone numbers in text is more involved but still doable this way. You would have to first generate potential potential matches using regular expressions and then classify each as a true or spurious based on the context it appears in.

Inevitably, for every new file type and every type of entity to be found in the file, one would have to come up with new features and maybe train a separate classifier.

Super tedious.

The RNN way

The fun and potentially superior solution uses char-RNNs. Instead of all those handcrafted features and regular expressions and different models, we can train a single recurrent neural network to label each character in the text as either belonging to a phone number (credit card number, email …) or not. If we do it right and have enough training data, the network should be able to learn that phone numbers are more likely to occur in emails than in server logs and that Java code tends to use camel case while Python has indented blocks following a colon - and all kinds of other features that would otherwise have to be hardcoded.

Let’s do it!

Implementation

As it turned out, the hardest part was getting and preparing the data. Since I don’t have access to a labeled dataset with phone numbers and emails, I decided to create an artificial one. I took all the Python files from scikit-learn repository and all the Scala files from scalaz and spliced them together into one giant sequence of characters. The sequence takes a few dozen consecutive characters from a Python file, then a few dozen from a Scala file, then Python again and so on. The result is the Frankenstein’s monster at the top of the post (except tens of megabytes more of it).

Preparing training data

The sequence made up of all the Python and Scala files wouldn’t fit in my RAM (Big Data, as promised ;), so it is generated online during training, using a generator:

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
from random import choice

def chars_from_files(list_of_files):
    # reads a list of files in random order and yields
    # one character at a time     
    while True:
        filename = choice(list_of_files)
        with open(filename, 'rb') as f:
            chars = f.read()
            for c in chars:
                yield c

def splice_texts(files_a, files_b):
    """ Takes two lists of files and generates a sequence
    of characters from those files. Yields pairs:
    (character, index of the source - 0 or 1)
    """
    a_chars = chars_from_files(files_a)
    b_chars = chars_from_files(files_b)
    generators = [a_chars, b_chars]

    # take between 20 and 50 characters from one source
    # before moving to the other source    
    jump_range = range(20, 50)

    source_ind = choice([0, 1])
    while True:
        jump_size = choice(jump_range)
        gen = generators[source_ind]
        for _ in range(jump_size):
            yield (gen.next(), source_ind)
        source_ind = 1 - source_ind

# it can be used like this
gen = splice_texts(["file1.txt", "file2.txt"], ["file3.txt", "file4.txt"])
char_1, label_1 = gen.next()
char_2, label_2 = gen.next()
# and so on ...

The other reason for using a generator is that the sequence can be randomized (both the order of files and the number of consecutive characters taken from one source). This way the network will never see the same sequence twice which will reduce overfitting.

Next step is encoding the characters as vectors (one-hot-encoding):

1
2
3
4
5
6
7
8
9
10
import numpy as np

# Only allowing these characters:
chars = '\n !"#$%&\'()*+,-./0123456789:;<=>?@[\\]^_`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~'
char2ind = dict((c, i) for i, c in enumerate(chars))
char2vec = {}
for c in chars:
    vec = np.zeros(len(chars))
    vec[char2ind[c]] = 1
    char2vec[c] = vec

To take advantage of the parallel processing powers of the GPU, the input vectors need to be shaped into batches. Keras requires that batches for LSTM be 3-dimensional arrays, where first dimension corresponds to the number of samples in a batch, second - number of characters in a sequence and third - dimensionality of the input vector. The latter is in our case equal to the number of characters in our alphabet.

For example, if there were only two sequences to encode, both of length 4, and only 3 letters in the alphabet, this is how we would construct a batch:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# sequences to encode:
# 'abca'
# 'cacb'

# vectors corresponding to characters
a = [1,0,0]
b = [0,1,0]
c = [0,0,1]

batch = np.array([
    [a,b,c,a],
    [c,a,c,b]
])
# batch.shape gives (2, 4, 3)
# which is = (number of sequences, length of a sequence, number of available chars)

If the sequences are too long to fit in one batch - as they are in our case - they need to be split into multiple batches. This would ordinarily mean losing some context information for characters that are near the boundary of a sequence chunk. Fortunately Keras LSTM has a setting stateful=True which tells the network that the sequences from one batch are continued in the next one. For this to work, the batches must be prepared in a specific way, with n-th sequence in a batch being continued in the n-th sequence of the next batch.

1
2
3
4
5
6
7
8
9
10
11
12
13
# sequences to encode:
# 'abcdefgh'
# 'opqrstuv'

batch_1 = np.array([
    [a,b,c,d],      # first element of first batch
    [o,p,q,r]       # second element of first batch
])
# i-th element of second batch is the continuation of i-th element of first_batch
batch_2 = np.array([
    [e,f,g,h],      # first element of second batch
    [s,t,u,v]       # second element of second batch
])

In our case, each sequence is produced by a generator reading from files. We will have to start a number of generators equal to the desired batch size.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def generate_batches(files_a, files_b, batch_size, sequence_len):
    gens = [splice_texts(files_a, files_b) for _ in range(batch_size)]
    while True:
        X = []
        y = []
        for g in gens:
            vecs = []
            labels = []
            for _ in range(sequence_len):
                c, l = g.next()
                vecs.append(char2vec[c])
                labels.append([l])
            X.append(vecs)
            y.append(labels)

        yield (np.array(X), np.array(y))

Done. This generator produces batches accepted by Keras’ LSTM. batch_size and sequence_len settings influence GPU/CPU utilisation but otherwise shouldn’t make any difference (as long as stateful=True!).

The network

Now for the easy part. Construct the network:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from keras.layers import Dense, Dropout, LSTM, TimeDistributed
from keras.models import Sequential

batch_size = 1024
seq_len = 100
n_chars = 96
rnn_size = 128
batch_shape = (batch_size, seq_len, n_chars)

model = Sequential()
# Let's use 3 LSTM layers, because why not
model.add(LSTM(rnn_size, return_sequences=True, batch_input_shape=batch_shape, stateful=True))
model.add(Dropout(dropout_rate))
model.add(LSTM(rnn_size, return_sequences=True, batch_input_shape=batch_shape, stateful=True))
model.add(Dropout(dropout_rate))
model.add(LSTM(rnn_size, return_sequences=True, batch_input_shape=batch_shape, stateful=True))
model.add(Dropout(dropout_rate))

model.add(TimeDistributed(Dense(units=1, activation='sigmoid')))
model.compile(optimizer='adam', loss='mse', metrics=['accuracy', 'binary_crossentropy'])

And train it:

1
2
3
4
5
6
from keras.callbacks import ModelCheckpoint

model_path = "models/my_model"
generator = generate_batches(files_a, files_b, batch_size, seq_len)
checkpointer = ModelCheckpoint(model_path)
model.fit_generator(generator, steps_per_epoch=1000, epochs=10, callbacks=[checkpointer])

Making predictions is just as easy:

1
predictions = model.predict_generator(generator, steps=50)

That’s it! The full code I used has a few more bells and whistles, but this is the core of it.

I have split the Python and Scala files into train and test sets (80:20) and trained the network on the training set for a few hours. This is what the network’s prediction on the test set (same text as on top of of this post) looks like:

package scalaz
package syntax

"""
Extended math utilities.
"""
# Authors: Gael Varoquaux
# Alex/** Wraps a value `selfandre Gramfort
# Alexandre T. Passos
# Olivier Grisel
# Lars Buitinck
# Stefan van der Walt
# Kyle Kastner
# Giorgio Patrini
# License:` and provides methods related to `MonadPlus` */
final class MonadPlusOps[F[_],A] private[syntax](val self: BSD 3 clause

from __future__ import division
from functools import partial
import warnings

import numpy as np
from scipy import linalg
from scipy.sparse import issparse, csr_matr F[A])(implicit val F: MonadPlus[F]) extends Ops[F[A]] {
////
impoix

from . import check_random_state
from .fixrt Leibniz.===

def filter(f: A => Boolean): F[A] =
F.filter(self)(f)

def withFilter(f: A => Boolean): F[A] =
filter(f)

final def uniteU[T](implicit T: Unapply[Foldable, Aes import np_version
from ._logistic_sigmoid import _log_logistic_sigmoid
from ..extern]): F[T.A] =
F.uniteU(self)(T)

def unite[T[_], B](implicit ev: A === T[B], T: Foldable[T]): F[B] = {
val ftb: F[T[B]] = ev.subst(seals.six.moves import xrange
from .sparsefuncs_fast import csr_row_norms
from .validation import check_array
from ..exceptions import NonBLASDotWarning


lf)
F.unite[T, B](ftb)
}
final def lefts[G[_, _], B, C](implicit ev: A === G[B, C], G: Bifoldable[G]): F[B] =
F.lefts(ev.subst(self))

final def rigdef norm(x):
"""Compute the Euclidean or Frobenius norm of x.

hts[G[_, _], B, C](implicit ev: A === G[B, C], G: Bifoldable[G]): F[C] =
F.rights(ev.subst(self))

final def separate[G[_, _], Returns the Euclidean norm when x is a vector, the Frobenius norm when x
is a matrix (2-d array). More precise than sqrt(squared_norm(x)).
"""
x = np.asarray(x)
nrm2, = lin B, C](implicit ev: A === G[B, C], G: Bifoldable[G]): (F[B], F[C]) =
F.separate(ev.subst(self))

////
}

sealed trait ToMonadPlusOps0 {
implicit def Talg.get_blas_funcs(['nrm2'], [x])
return nrm2(x)


# Newer NumPy has a ravel that needs leoMonadPlusOpsUnapply[FA](v: FA)(implicit F0: Unapply[MonadPlus, FA]) =
new MonadPlusOps[F0.M,F0.A](F0(v))ss copying.
if np_version < (1, 7, 1):
_ravel = np.ravel
else:
_ravel = partial(np.ravel, order='K')


def squared_no(F0.TC)

}

trait ToMonadPlusOps extends ToMonadPlusOps0 with ToMonadOps with ToApplicatrm(x):
"""Squared Euclidean or Frobenius norm of x.

Returns the Euclidean norm when x is a vector, the Frobenius norm when x
is a matrix (2-d array). Faster than norm(ivePlusOps {
implicit def ToMonadPlusOps[F[_],A](v: F[A])(implicit F0: MonadPlus[F]) =
new MonadPlusOps[F,A](v)

////

////
}

trait MonadPlusSyntax[F[_]] extends MonadSyntax[F] withx) ** 2.
"""
x = _ravel(x)
if np.issubdtype(x.dtype, np.integer):
ApplicativePlusSyntax[F] {
implicit def ToMonadPlusOps[A](v: F[A]): MonadPlusOps[F, A] = ne warnings.warn('Array type is integer, np.dot may overflow. '
'Data should be float type to avoid this issue',
UserWarning)
return np.dot(xw MonadPlusOps[F,A](v)(MonadPlusSyntax.this.F)

def F: MonadPlus[F]
////

////
}
package scalaz
package syntax

/** Wraps a value `self` and provides methods, x)


def row_norms(X, squared=False):
"""Row-wise (squared) Euclidean norm of X.

E related to `Traverse` */
final class Tquivalent to np.sqrt((X * X).sum(axis=1)), but also supporaverseOps[F[_],A] private[syntax](val self: F[A])(implicit val F: Traverse[F]) exterts sparse
matrices and does not create an X.shape-sized temporary.

Performs no input valnds Ops[F[A]] {
////

import Leibniz.===

final def tmap[B](f: A => B): F[B] =
F.map(seidation.
"""
if issparse(X):
if not isinstance(X, csr_matrix):

Font size shows the true label (small - Python, big - Scala) and background color represents the network’s prediction (white - Python, dark red - Scala).

It’s pretty good overall, but network keeps making a few unforced errors. Consider this bit:

package scalaz
package syntax

"""

  • it is very unsure about the first few characters of the input. Even though package scalaz should be a dead giveaway, the prediction only becomes confident at about the character ‘g’
  • it is sometimes too slow to change the prediction. Like in the case of Python’s triple quotation marks """" following a stretch of Scala code. Triple quotes should immediately be labeled as Python but only the third one is.

These mistakes stem from the fact that the RNN doesn’t look ahead and can only interpret a character in the context of characters that came before. Triple quotes almost certainly come from a stretch of Python code, but you don’t know that you’re seeing triple quotes until you’ve seen all three. That’s why the prediction gradually changes from Scala to Python (red to white) as the RNN encounters the second and third consecutive quote.

This problem actually has a straightforward solution - bidirectional RNN. It’s a type of RNN where the sequence is fed to it from both ends at the same time. This way, the network will be aware of the second and third quotation marks already when it’s producing the label for the first one.

To make the LSTM bidirectional in Keras one needs simply to wrap it with the Bidirectional wrapper:

1
2
3
4
5
6
from keras.layers import Bidirectional

model.add(Bidirectional(LSTM(rnn_size, return_sequences=True, stateful=True), batch_input_shape=batch_shape))

# instead of
# model.add(LSTM(rnn_size, return_sequences=True, batch_input_shape=batch_shape))

Everything else stays the same.

Here’s a sample of results from a bidirectional LSTM:

package scalaz
package std

import std.AllInstances._
import scalaz.scalacheck.ScalazProperties._
import scalaz.scalac"""
===============================heck.ScalazArbitrary._
import org.scalacheck.{Gen, Arbitrary}
import Lens.{lens => _, _}
import org.scalacheck.Prop.fo=========
Comparison of Calibration of ClassifrAll

object LensTest extends SpecLite {

{
implicit def lensArb = Arbitrary(Gen.const(Lens.lensId[Int]))
implicit def lensEqual = new Equal[Lens[Int, Iiers
========================================

Well calibrated classifiers are probabint]] {
def equal(a1: Lens[Int, Int], a2: Lens[Int, Int]): Boolean = a1.get(0) == a2.get(0)
}
checkAll("Lens", category.laws[Lens]) // not really testing much!
}

checkAll("id",listic classifiers for which the output
of the predict_proba method can be directly interpreted as a confidence level.
For instance a well calibrated (binary) classifier should classify the samp lens.laws(Lens.lensId[Int]))
checkAll("trivialles
such that among the samples to which it gave a predict_proba", lens.laws(Lens.trivialLens[Int]))
checkAll("codiagLens", lens.laws(Lens.codiagLens[Int]))
checkAll("Tuple2.first", lens.laws(Lens.firstLens[Int, Int]))
checkAll("Tuple2.second", le value close to
0.8, approx. 80% actually belong to the positive class.

Logisticns.laws(Lens.secondLens[Int, Int]))
checkAll("Set.containRegression returns well calibrated predictions as it directly
os", lens.laws(Lens.lensId[Set[Int]].contains(0)))
checkAll("Map.member", lens.laws(Lens.lensId[Map[Boolean, Int]].ptimizes log-loss. In contrast, the othemember(true)))
checkAll("sum", lens.laws(Lens.firsr methods return biased probabilities,
with different biases per method:

* GaussianNaiveBayes tends to push probabilities to 0 otLens[Int, String].sum(Lens.firstLens[Int, String])))

"NumericLens" should {
"+=" ! forAll((i: Int) => (Lens.lensId[Int] += i).run(1) must_=== ((i + 1) -> (i +

I think this looks better overall. The problem of updating prediction too slowly is mostly gone - package scalaz is marked as Scala immediately, starting with the letter ‘p’. However, now the network started making weird mistakes in the middle of a word for no reason. Like this one:

Comparison of Calibration

Why is the middle of the ‘Calibration’ all of a sudden marked as Scala?

The culprit is statefulness. Remember that stateful=True means that for each sequence in a batch, the state of the network at the beginning of a sequence is reused from the state at the end of the previous sequence*. This acts as if there were no batches, just one unending sequence. But in a bidirectional layer the sequence is fed to the network twice, from both directions. So half of the state should be borrowed from the previous sequence, and half from the next sequence that has not been seen yet! In reality all of the state is reused from previous sequence, so half of the network ends up in the wrong state. This is why those weird mispredictions appear and appear at regular intervals. At the beginning of a new batch, half of the network is in the wrong state and starts predicting the wrong label.

* or more precisely, the state at the end of the corresponding sequence in the previous batch

Let’s get rid of statefulness in the bidirectional version of the network:

1
model.add(Bidirectional(LSTM(rnn_size, return_sequences=True, stateful=False), batch_input_shape=batch_shape))

Unfortunately this means that we will have to use longer sequences (in the previous experiments I used 128 characters, now 200) to give the network more context for labeling a character. And even with that, prediction for characters near the boundary between consecutive sequences is bound to be poorer - like in regular unidirectional LSTM. To make up for it I decided to give the network more layers (4) and more time to train (a day). Let’s see how it worked out:

package scalaz

import scalaz.syntax.equal._
import scalaz.syntax.show._

sealed abstract class Either3[+A, +B, +C] extends Pro"""Bayesian Gaussian Mixture Modduct with Serializable {
def fold[Z](left: A => Z, middle: B => Z, right: C => Z): Z = this match {
case Left3(a) => left(a)
caseel."""
# Author: Wei Xue <xuewei4d Middle3(b) => middle(b)
case Right3(c) => right(c)
}

def eitherLeft: (A \/ B) \/ C = this match {
case Left3(a) => -\@gmail.com>
# Thierry Guillemot <thierry.guillemot.work@gmail.com>
# License: BSD 3 clause

import math
import numpy as np
from scipy.special import betaln, digamma, /(-\/(a))
case Middle3(b) => -\/(\/-(b))
case Right3(c) => \/-(c)
}

gammaln

from .base import BaseMixture, _check_shape
from .gaussian_mixture import _check_precision_matrix
from .gaussian_mixture import _check_precision_positivity
from .gaus def eitherRight: A \/ (B \/ C) = this match {
case Left3(a) => -\/(a)
case Middle3(b) => \/-(-\/(b))
case Right3(c)sian_mixture import _compute_log_det_cholesky
from .gaussian_mixture import _compute_precision_cholesky
from .gaussian_mixture import _estimate_gaussian_p => \/-(\/-(c))
}

def leftOr[Z](z: => Z)(f: A => Z): Z = fold(f, _ => z, _ => z)
def middleOr[Z](zarameters
from .gaussian_mixture import _estimate_log_gaussian_prob
from ..utils import check_array
from ..utils.validation import check_is_fitted


def _log_dirichlet_norm(dirichlet_concentration: => Z)(f: B => Z): Z = fold(_ => z, f, _ => z)
def rightOr[Z](z: => Z)(f: C => Z): Z = fold(_ => z, _ => z, f)
}

final case class Left3[+A, +B, +C](a: A) extends Either3[A, B, C]
final case cla):
"""Compute the log of the Dirichlet distribution normalization term.

Parameters
----------
dirichletss Middle3[+A, +B, +C](b: B) extend_concentration : array-like, shape (n_samples,)
The s Either3[A, B, C]
final case class Right3[+A, +B, +C](c: parameters values of the Dirichlet distribution.

Returns
-------
log_dirichlet_norm : float
The log normalization of the DirichleC) extends Either3[A, B, C]

object Either3 {
def left3[A, B, C](a: A): Either3[A, B, C] = Left3(a)
def middle3[A, B, C](b: B)t distribution.
"""
return (gammaln(np.sum(dirichlet_concentration)) -
np.sum(gammaln(dirichlet_concentration)))


def _log_wishart_norm(degrees_o: Either3[A, B, C] = Middle3(b)
def right3[A, B, C](c: C): Either3[A, B, C] = Right3(c)

implicit def equal[A: Equal, B: Equal, C: Equalf_freedom, log_det_precisions_chol, n_features):
"""Compute the log of the Wishart distribution normalization term.

Parameters
----------
degrees_of_freedom : array-like, shape ]: Equal[Either3[A, B, C]] = new Equal[Either3[A, B, C]] {
def equal(e1: Either3[A, B, C], e2: Either3[A, B, C]) = (e1, e2) match {
case (Left3(a1)(n_components,)
The number of degrees of freedom on t, Left3(a2)) => a1 === a2
case (Middle3(b1), Middle3(b2)) => b1 === b2
case (Right3(c1), Right3(c2)) => c1 === c2
case _ => false
}
}

implicihe covariance Wishart
t def show[A: Show, B: Show, C: Show]: Show[Either3[A, B, C]] = ne distributions.

log_det_precision_chol : array-like, shapw Show[Either3[A, B, C]] {
override def show(v: Either3[A, B, C]) = v match {
case Left3(a) => Cord("Left3(", a.shows, e (n_components,)
The determinant of the precision matrix for each component.

n_feat")")
case Middle3(b) => Cord("Middle3(", b.shows, ")")
case Right3(c) => Cord("Right3(", c.shows, ")")
}
}
}


// vim: set ts=4 sw=4 et:
package scalaz
package syntures : int
The number of features.

Return
------
log_wishart_norm : array-like, shape (n_components,)
The log noax

/** Wraps a value `self` and provides methods related to `Unzip` */
final class UnzipOps[F[_],A] private[syntax](val self: F[A])(implicit val F: Unzip[F]) extends Ops[F[Armalization of the Wishart distribution.
"""
# To simplify the comp]] {
////
////
}

sealed trait ToUnzipOps0 {
implicit def ToUnzipOpsUnapply[FA](v: FA)(implicit F0: Unapply[Unzip, FA])utation we have removed the np.log(np.pi) term
return -(degrees_of_freedom * log_det_precisi =
new UnzipOps[F0.M,F0.A](F0(v))(F0.TC)

}

trait ToUnzipOps extends ToUnzipOps0 {
implicit def ToUnzipOps[F[_],A](v: Fons_chol +
degrees_of_freedom * n_features * .5 * math.log(2.) +
np.sum(gammaln(.5 * (degrees_of_freedom -
[A])(implicit F0: Unzip[F]) =
new UnzipOps[F,A](v)

////
implicit def ToUnzipPairOps[F[_],A,B](v: F[(A, B)])(implicit F0: Unzip[F]) =
new UnzipPairOps[F,A,B](v)(F0)

final c np.arange(n_features)[:, np.newaxis])), 0))


class BayesianGaussianMixture(BaseMixlass UnzipPairOps[F[_],A, B] private[syntax](self: F[(A, B)])(imture):
"""Variational Bayesian estimation of a Gaussian mixt

Weird mislabelings are gone, boundaries between labels are crisp, overall accuracy improved. It’s practically perfect. Thank you François Chollet!

This is it for now. More experiments in the next post.

As a bonus, this is a prediction from a network trained collected works of Shakespeare mixed with .R files from caret repository:



SCENE III.
CYMBELINE'S palace. An ante-chamber adjoining IMOGEN'S apartments

Enter CLtimestamp <- Sys.time()
library(caret)

model <- "nbSearch"

######################################OTEN and LORDS

FIRST LORD. Your lordship is the most patient man in loss, the most
coldest that ever turn'd up ac###################################

set.seed(2)
training <- LPH07_1(100, factors = TRUE, class = TRUE)
testing <- LPH07_1(100, factors = TRUE, class = TRUE)
trainX <- training[, -ncol(te.
CLOTEN. It would make any man cold to lose.
FIRST LORD. But not every man paraining)]
trainY <- training$Class

cctrl1 <- trainControl(method = "cv",tient after the noble temper of
your lordship. You are most hot and furious when you win.
CLOTEN. Winning will put any man into courage. If I cou number = 3, returnResld get this
foolish Imogen, I should have gold enough. It's almost morning,
is't not?
FIRST LORD. Day, my lord.
CLamp = "all",
classProbs = TRUE,
summaryFunction = twoClassSummary)
cctrl2 <OTEN. I would this music would come- trainControl(method = "LOOCV",
classProbs = TRUE, summaryFunction = twoClassSummary)
cctrl3 <- trainControl(method = ". I am advised to give her
music a mornings; they say it will penetrate.

Enter musicians

Come on, tune. If you none",
classcan penetrate her with your fingering, so.
We'll try with tongue too. If none wilProbs = TRUE, summaryFunction = twoClassSummary)
cctrlR <l do, let her remain; but
I'll nev- trainControl(method = "cv", number = 3, returnResamp = "all", search = "random")

set.seed(849)
test_class_cv_model <- train(trainX, trainY,
er give o'er. First, a very excellent good-conceited
thing; after, a wonderful sweet air, with admirable rich words to
it- and then let her consider.

SONG

Hark, har method = "nbSearch",
k! the lark at heaven's gate sings,
And Phoebus 'gins arise,
His steeds to water at those springs
On chalic'd flow'rs that lies;
And winking Ma trControl = ccry-buds begin
To ope their golden eyes.
With everything that pretty bin,
My lady sweet, arise;
Arise, arise!

So, get you gone. If this penetrate, I trl1,
metric = "ROC")

test_class_pred <- predict(test_class_cv_model, testing[, -ncol(testing)])
test_class_prob <- predict(test_classwill consider your music
the better; if it do not, it is a vice in her ears which
horsehairs and calves' guts, nor the voice of unpaved eunuch to
boot, can_cv_model, testing[, -ncol(testing)], type = "prob")
never amend. Exeunt musicians

Enter CYMBELINE and QUEEN

SECOND LORD. Here comes the King.
CLOTEN. I am glad I was up so late, for that's the re
set.seed(849)
test_class_rand <- trainason I was up
so early. He cannot choose but take this service I hav(trainX, trainY,
method = "nbSearch",
trControl = cctrlR,
e done
fatherly.- Good morrow to your Majesty and to my gracious mother.
CYMBELINE. Attend you here the door of our stern daughter?
Will she no tuneLength = 4)

set.seed(849)
test_class_loo_model <- train(trainX, trainY,
method = "nbt forth?
CLOTEN. I have assail'd her with musics, but she vouchsafes no
notice.
CYMBELINE.Search",

Conclusions

What have we learned?

  • constructing and training a network with Keras is embarassingly easy
  • but preparing data for char RNNSs is still very manual and awkward
  • RNN can’t be both stateful and bidirectional. Duh!
  • distinguishing between programming languages with char-RNN works remarkably well with no parameter tuning or feature engineering
  • looks promising as a method of tagging special entities (code snippets or emails or phone numbers or…) included in text

Neural networks are in many ways overhyped. On most supervised machine learning problems you would be better off with a good old random forest. But tagging sequences is one of those applications that are difficult and tedious to even translate into a regular supervised learning task. How do you feed a stream of characters into a decision tree? And an RNN solves it straight out of the box, no questions asked.

Comments