<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jacob Zweig on Medium]]></title>
        <description><![CDATA[Stories by Jacob Zweig on Medium]]></description>
        <link>https://medium.com/@jacob.zweig?source=rss-4459aa7bce57------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8gZGaPiK1U2zsXP_6pMl4w.jpeg</url>
            <title>Stories by Jacob Zweig on Medium</title>
            <link>https://medium.com/@jacob.zweig?source=rss-4459aa7bce57------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 15 Nov 2026 10:01:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jacob.zweig/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[BERT in Keras with Tensorflow hub]]></title>
            <link>https://medium.com/data-science/bert-in-keras-with-tensorflow-hub-76bcbc9417b?source=rss-4459aa7bce57------2</link>
            <guid isPermaLink="false">https://medium.com/p/76bcbc9417b</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Jacob Zweig]]></dc:creator>
            <pubDate>Thu, 21 Mar 2019 20:40:07 GMT</pubDate>
            <atom:updated>2019-04-08T15:52:35.349Z</atom:updated>
            <content:encoded><![CDATA[<p>At <a href="http://strong.io/">Strong Analytics</a>, many of our projects involve using deep learning for natural language processing. In one recent project we worked to encourage kids to explore freely online while making sure they stayed safe from cyberbullying and online abuse, while another involved predicting deductible expenses from calendar and email events.</p><p>A key component of any NLP project is the ability to rapidly test and iterate using techniques. Keras offers a very quick way to prototype state-of-the-art deep learning models, and is therefore an important tool we use in our work.</p><p>In a <a href="https://towardsdatascience.com/elmo-embeddings-in-keras-with-tensorflow-hub-7eb6f0145440">previous post</a>, we demonstrated how to integrate ELMo embeddings as a custom Keras layer to simplify model prototyping using Tensorflow hub. <a href="https://arxiv.org/abs/1810.04805">BERT</a>, a language model introduced by Google, uses transformers and pre-training to achieve state-of-the-art on many language tasks. It has recently been added to Tensorflow hub, which simplifies integration in Keras models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4LUqkMipdAI8Xgg1.png" /><figcaption>Deeply bidirectional unsupervised language representations with BERT</figcaption></figure><p>Let’s get building! First, we load the same IMDB data we used previously:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84df94b3d241a9d78e331c03fa667a42/href">https://medium.com/media/84df94b3d241a9d78e331c03fa667a42/href</a></iframe><p>Next, we tokenize the data using the tf-hub model, which simplifies preprocessing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e593016f9b1f7a169d101e0d1d6573e4/href">https://medium.com/media/e593016f9b1f7a169d101e0d1d6573e4/href</a></iframe><p>We next build a custom layer using Keras, integrating BERT from tf-hub. The model is very large (110,302,011 parameters!!!) so we fine tune a subset of layers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6aede1e2f292e5818832596ebefc354/href">https://medium.com/media/d6aede1e2f292e5818832596ebefc354/href</a></iframe><p>Now, we can easily build and train our model using the BERT layer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9c50df84069a594a7158ab75b426c45/href">https://medium.com/media/e9c50df84069a594a7158ab75b426c45/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*D9kYNwnwqhMkvLvvVrljfA.png" /><figcaption>Using a GPU for large models like BERT is advised!</figcaption></figure><p>Pretty easy! See the <a href="https://github.com/strongio/keras-bert">full notebook on Github</a> and build cool stuff!</p><p><strong><em>Want to work on challenging NLP, Machine Learning, and AI in a variety of industries with a team of top data scientists in Chicago? We’re hiring talented data scientists and engineers!</em></strong></p><p>Learn more at <a href="http://strong.io/">strong.io</a> and apply at <a href="https://careers.strong.io/">careers.strong.io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76bcbc9417b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/bert-in-keras-with-tensorflow-hub-76bcbc9417b">BERT in Keras with Tensorflow hub</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elmo Embeddings in Keras with TensorFlow hub]]></title>
            <link>https://medium.com/data-science/elmo-embeddings-in-keras-with-tensorflow-hub-7eb6f0145440?source=rss-4459aa7bce57------2</link>
            <guid isPermaLink="false">https://medium.com/p/7eb6f0145440</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Jacob Zweig]]></dc:creator>
            <pubDate>Tue, 24 Apr 2018 03:07:27 GMT</pubDate>
            <atom:updated>2019-04-08T15:53:16.601Z</atom:updated>
            <content:encoded><![CDATA[<p>The newly released <a href="https://www.tensorflow.org/hub/">Tensorflow hub</a> provides an easy interface to use existing machine learning models for transfer learning. Sometimes, however, it’s nice to fire up Keras and quickly prototype a model. With a few fixes, it’s easy to integrate a Tensorflow hub model with Keras!</p><p><a href="https://arxiv.org/pdf/1802.05365.pdf">ELMo embeddings</a>, developed at <a href="http://allennlp.org/elmo">Allen NLP</a>, are one of many great pre-trained models available on Tensorflow Hub. ELMo embeddings are learned from the internal state of a bidirectional LSTM and represent contextual features of the input text. It’s been shown to outperform GloVe and Word2Vec embeddings on a wide variety of NLP tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*gpBBcQbdtIceERjJ784j1A.png" /><figcaption>A bidirectional LSTM is trained on a large text corpus, and the internal states are combined to calculate rich, context sensitive features of text.</figcaption></figure><p>Here’s a bit of code our team at <a href="http://strong.io/">Strong Analytics</a> recently used to prototype an NLP model using state of the art ELMo embeddings in Keras.</p><p>First we load some data:</p><pre># Load all files from a directory in a DataFrame.<br>def load_directory_data(directory):<br>  data = {}<br>  data[&quot;sentence&quot;] = []<br>  data[&quot;sentiment&quot;] = []<br>  for file_path in os.listdir(directory):<br>    with tf.gfile.GFile(os.path.join(directory, file_path), &quot;r&quot;) as f:<br>      data[&quot;sentence&quot;].append(f.read())<br>      data[&quot;sentiment&quot;].append(re.match(&quot;\d+_(\d+)\.txt&quot;, file_path).group(1))<br>  return pd.DataFrame.from_dict(data)<br><br># Merge positive and negative examples, add a polarity column and shuffle.<br>def load_dataset(directory):<br>  pos_df = load_directory_data(os.path.join(directory, &quot;pos&quot;))<br>  neg_df = load_directory_data(os.path.join(directory, &quot;neg&quot;))<br>  pos_df[&quot;polarity&quot;] = 1<br>  neg_df[&quot;polarity&quot;] = 0<br>  return pd.concat([pos_df, neg_df]).sample(frac=1).reset_index(drop=True)<br><br># Download and process the dataset files.<br>def download_and_load_datasets(force_download=False):<br>  dataset = tf.keras.utils.get_file(<br>      fname=&quot;aclImdb.tar.gz&quot;, <br>      origin=&quot;http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz&quot;, <br>      extract=True)<br><br>  train_df = load_dataset(os.path.join(os.path.dirname(dataset), <br>                                       &quot;aclImdb&quot;, &quot;train&quot;))<br>  test_df = load_dataset(os.path.join(os.path.dirname(dataset), <br>                                      &quot;aclImdb&quot;, &quot;test&quot;))<br><br>  return train_df, test_df<br><br># Reduce logging output.<br>tf.logging.set_verbosity(tf.logging.ERROR)<br><br>train_df, test_df = download_and_load_datasets()<br>train_df.head()</pre><p>We next process our data. Note that to use strings as input to a Keras model, we create a numpy array of objects. I’ve limited this data to the first 150 words for memory (ELMo embeddings are computationally intensive, so use a GPU!).</p><pre># Create datasets (Only take up to 150 words)<br>train_text = train_df[&#39;sentence&#39;].tolist()<br>train_text = [&#39; &#39;.join(t.split()[0:150]) for t in train_text]<br>train_text = np.array(train_text, dtype=object)[:, np.newaxis]<br>train_label = train_df[&#39;polarity&#39;].tolist()</pre><pre>test_text = test_df[&#39;sentence&#39;].tolist()<br>test_text = [&#39; &#39;.join(t.split()[0:150]) for t in test_text]<br>test_text = np.array(test_text, dtype=object)[:, np.newaxis]<br>test_label = test_df[&#39;polarity&#39;].tolist()</pre><p>To instantiate the Elmo Embeddings in Keras, we first have to create a custom layer to ensure that the embedding weights are trainable:</p><pre>class ElmoEmbeddingLayer(Layer):<br>    def __init__(self, **kwargs):<br>        self.dimensions = 1024<br>        self.trainable = True<br>        super(ElmoEmbeddingLayer, self).__init__(**kwargs)</pre><pre>def build(self, input_shape):<br>        self.elmo = hub.Module(&#39;<a href="https://tfhub.dev/google/elmo/2&#39;">https://tfhub.dev/google/elmo/2&#39;</a>, trainable=self.trainable, name=&quot;{}_module&quot;.format(self.name))</pre><pre>self.trainable_weights += K.tf.trainable_variables(scope=&quot;^{}_module/.*&quot;.format(self.name))<br>        super(ElmoEmbeddingLayer, self).build(input_shape)</pre><pre>def call(self, x, mask=None):<br>        result = self.elmo(K.squeeze(K.cast(x, tf.string), axis=1),<br>                      as_dict=True,<br>                      signature=&#39;default&#39;,<br>                      )[&#39;default&#39;]<br>        return result</pre><pre>def compute_mask(self, inputs, mask=None):<br>        return K.not_equal(inputs, &#39;--PAD--&#39;)</pre><pre>def compute_output_shape(self, input_shape):<br>        return (input_shape[0], self.dimensions)</pre><p>Now we can build and train our model with the ElmoEmbeddingLayer:</p><pre>input_text = layers.Input(shape=(1,), dtype=tf.string)<br>embedding = ElmoEmbeddingLayer()(input_text)<br>dense = layers.Dense(256, activation=&#39;relu&#39;)(embedding)<br>pred = layers.Dense(1, activation=&#39;sigmoid&#39;)(dense)</pre><pre>model = Model(inputs=[input_text], outputs=pred)</pre><pre>model.compile(loss=&#39;binary_crossentropy&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;accuracy&#39;])<br>model.summary()</pre><pre>model.fit(train_text, <br>          train_label,<br>          validation_data=(test_text, test_label),<br>          epochs=5,<br>          batch_size=32)</pre><p>And that’s it! There are lots of great models on tensorflow hub, make sure to experiment with them all!</p><p>See the IPython notebook here: <a href="https://github.com/strongio/keras-elmo/blob/master/Elmo%20Keras.ipynb">https://github.com/strongio/keras-elmo/blob/master/Elmo%20Keras.ipynb</a>’</p><p><strong><em>Want to work on challenging NLP, Machine Learning, and AI in a variety of industries with a team of top data scientists in Chicago? We’re hiring talented data scientists and engineers!</em></strong></p><p>Learn more at <a href="http://strong.io/">strong.io</a> and apply at <a href="https://careers.strong.io/">careers.strong.io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7eb6f0145440" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/elmo-embeddings-in-keras-with-tensorflow-hub-7eb6f0145440">Elmo Embeddings in Keras with TensorFlow hub</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Quantile Regression in Tensorflow]]></title>
            <link>https://medium.com/data-science/deep-quantile-regression-in-tensorflow-1dbc792fe597?source=rss-4459aa7bce57------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dbc792fe597</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[math]]></category>
            <dc:creator><![CDATA[Jacob Zweig]]></dc:creator>
            <pubDate>Wed, 28 Mar 2018 03:04:38 GMT</pubDate>
            <atom:updated>2019-04-08T15:53:50.984Z</atom:updated>
            <content:encoded><![CDATA[<p>A key challenge in deep learning is how to get estimates on the bounds of predictors. Quantile regression, first introduced in the 70’s by Koenker and Bassett [1], allows us to estimate percentiles of the underlying conditional data distribution even in cases where they are asymmetric, giving us insight on the relationship of the variability between predictors and responses.</p><p>As described by Koeneker and Hallock [2], the standard approach in OLS regression is to estimate the conditional <em>mean</em> of the data by drawing a line which minimizes distance between the line and all of the points on the graph. In contrast, the goal in quantile regression is to estimate the conditional <em>median, </em>or any other quantile. To do so, we instead weight the distances between points on the graph and our regression line based on the selected quantile. For example, if we selected the 90th quantile to estimate, we’d fit a regression line so that 90% of the data points are below the line and 10% are above.</p><h4>Tensorflow code</h4><p>A great <a href="https://towardsdatascience.com/deep-quantile-regression-c85481548b5a">recent post on medium</a> by Sachin Abeywardana demonstrated how to perform deep quantile regression using Keras. However, a limitation of this implementation is that it requires separate fitting of models per quantile. Using Tensorflow, however, we can instead fit an arbitrary number of quantiles simultaneously.</p><p>The <a href="https://github.com/strongio/quantile-regression-tensorflow/blob/master/Quantile%20Loss.ipynb">notebook for this implementation</a> can be found on the <a href="http://strong.io/">Strong Analytics</a> github.</p><p>We first instantiate a simple regression model, and add outputs for each of the quantiles we’d like to estimate</p><pre># Define the quantiles we’d like to estimate<br>quantiles = [.1, .5, .9]</pre><pre># Add placeholders for inputs to the model<br>x = tf.placeholder(tf.float32, shape=(None, in_shape))<br>y = tf.placeholder(tf.float32, shape=(None, out_shape))</pre><pre># Create model using tf.layers API<br>layer0 = tf.layers.dense(x, units=32, activation=tf.nn.relu)<br>layer1 = tf.layers.dense(layer0, units=32, activation=tf.nn.relu)</pre><pre># Now, create an output for each quantile<br>outputs = []<br>for i, quantile in enumerate(quantiles):<br>    output = tf.layers.dense(layer1, 1, name=”{}_q{}”.format(i, int(quantile*100)))<br>    outputs.append(output)</pre><p>Now, we create the losses for each quantile</p><pre>losses = []<br>for i, quantile in enumerate(quantiles):<br>   error = tf.subtract(y, output[i])<br>   loss = tf.reduce_mean(tf.maximum(quantile*error, (quantile-1)*error), axis=-1)<br>   losses.append(loss)</pre><p>Finally, we combine the losses and instantiate our optimizer</p><pre>combined_loss = tf.reduce_mean(tf.add_n(losses))<br>train_step = tf.train.AdamOptimizer().minimize(combined_loss)</pre><p>And that’s basically it! Now we can fit our model and simultaneously estimate all of the specified quantiles:</p><pre>for epoch in range(epochs):<br>   # Split data to batches<br>   for idx in range(0, data.shape[0], batch_size):<br>     batch_data = data[idx : min(idx + batch_size, data.shape[0]),:]<br>     batch_labels = labels[idx : min(idx + batch_size, labels.shape[0]),:]</pre><pre>    feed_dict = {x: batch_data,<br>                 y: batch_labels}</pre><pre>    _, c_loss = sess.run([train_step, combined_loss], feed_dict)</pre><p>Fitting this data on a dataset of motorcycle crashes (<a href="https://github.com/sachinruk/KerasQuantileModel">from here</a>) gives us the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*_lysFbib221Cyf1s4cG6Ng.png" /><figcaption>Estimated quantiles</figcaption></figure><h4>Refs</h4><p>1. Regression Quantiles. Roger Koenker; Gilbert Bassett, Jr. Econometrica, Vol. 46, №1. (Jan., 1978), pp. 33–50.</p><p>2. Quantile Regression. Roger Koenker; Kevin F. Hallock. Journal of Economic Perspectives · vol. 15, no. 4, Fall 2001. (pp. 143–156).</p><p><strong><em>Want to work on challenging Machine Learning and AI in a variety of industries with a team of top data scientists in Chicago? We’re hiring talented data scientists and engineers!</em></strong></p><p>Learn more at <a href="http://strong.io/">strong.io</a> and apply at <a href="https://careers.strong.io/">careers.strong.io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dbc792fe597" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/deep-quantile-regression-in-tensorflow-1dbc792fe597">Deep Quantile Regression in Tensorflow</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why data science consulting is my dream job]]></title>
            <link>https://medium.com/@jacob.zweig/why-data-science-consulting-is-my-dream-job-c3704b982dbe?source=rss-4459aa7bce57------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3704b982dbe</guid>
            <category><![CDATA[entrepreneur]]></category>
            <category><![CDATA[consulting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[careers]]></category>
            <dc:creator><![CDATA[Jacob Zweig]]></dc:creator>
            <pubDate>Wed, 28 Feb 2018 20:32:49 GMT</pubDate>
            <atom:updated>2019-04-08T15:55:16.985Z</atom:updated>
            <content:encoded><![CDATA[<p>Ask five different data scientists what their day to day is like and you’ll likely get five dramatically different answers.</p><p>When we started <a href="http://strong.io/">Strong Analytics</a>, we did so because we loved statistics, machine learning, and building software. What we didn’t know at the time, however, was how much being a data science <strong><em>consultant </em></strong>differed from being a typical data scientist, and <em>how much fun</em> being a data science consultant would be.</p><p>A <em>consultant</em>, you say? Isn’t that the realm of overpriced suits, ‘catalyzing human capital growth through cross-platform action items’, and 600 hour workweeks?</p><p>That couldn’t be farther from the truth! With almost 2 years under our belt, I thought I’d outline a few things I love most about this job.</p><h3><strong>We solve <em>incredibly</em> challenging problems</strong></h3><p>I, like most of us who find our way to data science, am naturally drawn to the challenge of solving difficult problems. As consultants, companies reach out to us with the most difficult problems they have — ones that can’t be solved internally. It’s our job to help them figure out <em>how</em> to tackle these problems and, in most cases, build the solutions for them.</p><p>Every day brings new challenges, from building deep learning models for tracking and detection on embedded devices, mobile applications that detect and respond automatically to critical user behaviors, and platforms that ingest and process hundreds of millions of datapoints per day. It’s always challenging, but never boring!</p><h3>We get to work in a variety of industries</h3><p>Being a data science consultant gives us the opportunity to work with clients across many industries — including automotives, gaming, pharmaceuticals, retail, biometrics, engineering, publishing, manufacturing, and IoT. Two weeks ago, I had a lab coat and hard hat on at food manufacturing plant; the week after, I was learning about retina scans in biosecurity.</p><p>It’s always exciting to learn about a new industry and see both how they currently use data science and how they can better use data science to improve their business.</p><h3>We use the ‘full-stack’ of data science</h3><p>Being data science consultants, we have to be familiar with a wide variety of tools and technologies to be self-sufficient. It’s not enough to know how to analyze data using R or Python — we need to be fluent in various SQL dialects, machine learning models, optimization techniques, distributed computation frameworks, cloud services, probabilistic programming languages, APIs and web applications, UX design, data visualization, and scalable software application deployment. PHEW!</p><p>I <em>definitely</em> didn’t know all of these when I first started (and I’m still learning a few!), which leads me to the next thing I love most about data science consulting…</p><h3>Every day is an opportunity to learn something new</h3><p>Being a data science consultant means that our clients rely on us to be on the bleeding edge. Whether it’s a new tool, technique, or technology, every project that we do is unique, and therefore presents an opportunity to learn something new and stay on the forefront of data science.</p><h3>We all grow together</h3><p>Without a doubt, the absolute best aspect of data science consulting is being surrounded by a team of awesome, passionate, talented data scientists who share the same goals as I do. Everyone on our team brings together diverse experiences and expertise both from their previous careers and from different projects they work on. Having a strong learning community gives us the amazing opportunity to grow together. From Friday lab meetings to impromptu discussions, it’s hard to convey how much fun it is to be a part of a great data science consulting team.</p><p>There’s still lots more learning and growing to do, and I’m thrilled to have the opportunity to do so at my dream job.</p><p><strong><em>Does this sound like your dream job too? Want to work on challenging Machine Learning and AI in a variety of industries with a team of top data scientists in Chicago? We’re hiring talented data scientists and engineers!</em></strong></p><p>Learn more at <a href="http://strong.io/">strong.io</a> and apply at <a href="https://careers.strong.io/">careers.strong.io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3704b982dbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>