iOS Natural Language Processing in 6 lines of code

Determining people’s feelings from real tweets

Carlos Gonzalez
Towards Data Science

--

Photo by Hannes Wolf on Unsplash

An iOS and MacOS Natural language processing model for determining people’s feelings can be implemented and exported extremely easily using Apple’s CreateML library and text from people’s past tweets. Let’s download the data and test it out!

After unzipping the data from the link above, drag and drop the .csv file in to somewhere convenient. Next, open up a playground on Xcode, select MacOS, and select a blank file.

Make sure to select Mac OS

Once that’s done, import the needed libraries:

Next, import the data from the .csv file, make sure to change the file URL path to where you downloaded the data

Next, we need to split the data into training and testing, feel free to experiment with the split ratio

if you want to set the seed in order to keep track of the random split later, change the above line like this:

If you take a look at the data, you’ll see that it’s grouped into two columns: one is the label (positive, negative, or neutral) and the other contains the text of the tweet

A look at the csv data

Now we can train the model using our training data,

Your Xcode console should now start parsing the data,

Then it starts training,

And finally we can test it to see how well it did. This exceeds our 6 line limit, but the model is already done so this doesn’t count 😏

I was able to get the error down to 28%,

Let me know below if you were able to drive the error down even farther, and how you did it. And that’s it! You did it! If you want to use the model to test a random string of text to see if it is positive, negative or neutral, here’s an example:

My model was able to correctly predict “pos” when I ran it.

Correctly identified “pos” on last line

Finally, if you want to export the model,

Like all CreateML models, it will save as a .mlmodel

Conclusions And Full Source Code

So we learned 3 things:

  1. It’s possible to determine people’s emotions from their tweets if we have the right data
  2. Apple’s CreateML library makes this super simple
  3. The entire training and testing can be done in six lines of code

Now that you know this, what are you going to use it for? Are you gonna show it off to your friends? Are you going to try to make it even more accurate? Or are you bold and you’re going to build a stock predictor that uses the emotion from people’s tweets to determine price fluctuations? That last one might be tough, but I say you go for it! Best of luck! The full source code is below.

Questions? You can find me at www.cggonzalez.com

--

--