Machine Learning practice using R and k-means on your own twitter feed

Prerequisits

You will need:

Learn about unsupervised clustering in general

Warning

Many tutorials use nice clean (and boring) data sets with no issues. In this tutorial, you will be using your own data and it may not be clean. By "clean" we mean that there are no zeros at data points when that can't be handled; there are no so called NaN's which means, "Not a Number". NaN is a placeholder for a data point that is meant to be numeric but is not. You may also have plus or minus Inf which implies a number too big or too small to represent in the computer and is assumed to be infinite. We need to deal with that in the original data set. Sometimes it's ok to add 1, and it may be acceptable to simply remove the data point from the set.

In the twitter data, most of the numbers are squished together and there are a few distant ones. This does not make a good data set for cluster separation, but all is not lost. We can do a non-linear coordinate transformation. This means to do something like square all the data values or take the log and so on. The choice is not particularly fixed as what works depends on the data. All we are trying to do is to make a distribution that approximates a normal (Gaussian) distribution where possible, otherwise, just try to find ways to separate the features in a better spread for analysis.

In this code we found a need to:

  1. Clean up the code from zero values (by forcing the data point to 1 if it is zero or even negative)
  2. Take the log of each point to spread things out.

In real data analysis expect to spend a lot of time understanding and cleaning up the data before deciding which algorithm is relevant. Also expect to get many errors and have to solve many problems.

MANY thanks to JULIANHI where this code largely came from. The problem was, It did not work for me and I had a few things to fix up. Hopefully, this version will work for you. If not, let me know.

Get ready part 1

Follow instructions here :

https://support.twitter.com/articles/110250-adding-your-mobile-number-to-your-account-via-web

This will redirect you to

https://twitter.com/settings/devices

Have your phone ready because once you give the country and number, then you should get an SMS code. Use that to proceed. Note: When you choose the country - like (say) +61 then the phone number of the mobile is entered without a leading zero.

Next you see lots of "opt-out of notifications" that would be sent to your phone upon twitter activity. Untick what you don't want.

[Save Changes]



Get ready - part 2

Now you will need to generate some keys and tokens. There are four in all.

Two keys are called:

  • Consumer Key
  • Consumer Secret.

The tokens are called:

  • Access Token
  • Access Token Secret

They look like long strings of random characters. Keep your secrets secret otherwise anyone who gets hold of them might be able to control your account.

Go here and log in with twitter account https://apps.twitter.com/

Create a new application.

There is a form to fill in.

Application name: (Use what you like)

Description: (Free form text to tell people what your application does.)

URL of the website: (For this exercise you don't need to actually have a website, but you do need to put something there. I created and used a Weebly web site.)

Callback: IMPORTANT... leave it blank otherwise you are expected to write code at the designated web landing page that can complete an authorization. We won't need that and as a result will get the Access Tokens as well as the Consumer Keys.

Click [Create App]

Click [Test Oauth] and on this page you should find the four keys. Leave this page open because you will need to use the strings in the code below.

Do NOT publish your secrets.



Get R and R-Studio

Install R ( http://www.r-project.org/ )

Install R Studio ( http://www.rstudio.com/products/rstudio/download/ )

Start up R-Studio

The default R-Studio Integrated Development Environment

Load some library source (once only)

R has a keyword called library and you use that every time you run a program to instantiate code-modules. But many are not installed at first. So you need to do the following ONCE after installing R.

Copy This code and and paste it into the console pane in R-Studio. That's the lower pane.

install.packages(c("devtools", "rjson", "bit64", "httr")) 
install_github("geoffjentry/twitteR") 
install_github('ramnathv/rCharts')

Copy and paste this code into R

Your R-Studio may not have the top-left panel visible. To get to it, use

File -> New File -> R-Script

It will display a text entry panel called 'Untitled' which will get named if you save it.

In my screenshot above, you can see two untitled panels. You will only have one. Paste the following code into that panel. Nothing will 'run' at this stage, and you will need to edit it anyway. (refer to the strings of asterisks).

library(devtools)
library(twitteR)
library(rCharts)
# Get the following keys and tokens from twitter development web site.
# Change the things pointed out with ***
api_key <- "apiapiapiapiapiapiapiapiapiapiapiapi" # ***
api_secret <- "apisecretapisecretapisecretapisecretapisecret" # ***
access_token <- "toktoktoktoktoktoktoktoktoktoktoktoktok" # ***
access_token_secret <- "toksecrettoksecrettoksecrettoksecrettoksecret" # **********************************
setup_twitter_oauth(api_key,api_secret,access_token,access_token_secret)
user <- getUser("p u t y o u r n a m e ") # *** Set YOUR username ***
userFriends <- user$getFriends()
userFollowers <- user$getFollowers()
userNeighbors <- union(userFollowers, userFriends) #merge followers and friends
userNeighbors.df = twListToDF(userNeighbors) #create the dataframe
userNeighbors.df[userNeighbors.df<=0]<-1 # This is to prevent Inf and NaN when log is taken
userNeighbors.df$logFollowersCount <-log(userNeighbors.df$followersCount) # Non linear coordinate transformation
userNeighbors.df$logFriendsCount <-log(userNeighbors.df$friendsCount)
kObject.log <- data.frame(userNeighbors.df$logFriendsCount,userNeighbors.df$logFollowersCount)
mydata <- kObject.log
wss <- (nrow(mydata)-1)*sum(apply(mydata,2,var))
for (i in 2:15) wss[i] <- sum(kmeans(mydata,centers=i)$withinss)
plot(1:15, wss, type="b", xlab="Number of Clusters",
 ylab="Within groups sum of squares") # When you see the knee-plot, choose cluster=K number near the knee

Modify the code with your keys, tokens and user name

In the code that you pasted into the script edit window in R-Studio, go to the twitter developer web page and locate each of the keys and tokens. Cut and paste them into the placeholders marked:


  1. apiapiapiapiapiapiapiapiapiapiapiapi
  2. apisecretapisecretapisecretapisecretapisecret
  3. toktoktoktoktoktoktoktoktoktoktoktoktok
  4. toksecrettoksecrettoksecrettoksecrettoksecret
  5. p u t y o u r n a m e

Make sure you preserve the quote marks "" and you should see something similar to these pretend keys:

api_key <- "DVqBfVsgR1GErF1g7xwH8jkte"
api_secret <- "xjmKxx58YOMgwNOUvVM13lbqjtpFvfRXfq8K633Gg576"
access_token <- "1250mcUoNapC9yJ3fmc36MVoYwLHxzHIau8oUqc7"
access_token_secret <- "nOBl5nMUGioT2TesgEeEbqjtpFvfR18XFoUsRkL"
setup_twitter_oauth(api_key,api_secret,access_token,access_token_secret)
user <- getUser("youttwit") #Set the username


How to run code line by line

In the screenshot above, I've highlighted the RUN icon, and also the current cursor position. Put your cursor on the first line of code, and click RUN. This will execute ONLY that line of code and the cursor will progress one line down. In the meantime, the panel below it will show the line of code and execute it, returning results.

Run each line one by one and check that it completes and you get no errors. I can't predict which errors you might get as there are so many things that can go wrong when programming. That's when the fun starts. Try searching for the error on the internet in the context of twitter or R-Studio (or both) as required. Usually, someone else has had the same issue.

NOTE: You may get some warnings (can ignore), and you WILL need to respond after one particular line of code because it will ask you to enter a number. This is the line:

setup_twitter_oauth(api_key,api_secret,access_token,access_token_secret)


(See the picture below for the input question)

Enter 1

Note that some of the lines of code will take a while to run because of connecting to the internet twitter Application Programmer Interface (API) and downloading data. You will see a small red activity indicator in the lower panel when it is busy.

If all goes well, you will get a "Knee curve". This curve is telling you about the number of clusters discover-able in your data. You should choose a number where the curve starts to turn. For me, K=4 was ok. I could have used K=3. This will later tell k-means to look for K clusters.

Knee curve

Now for the clustering graph.

It's likely that your curve also bends at cluster 3 or 4. Set the value (K from above) to centers=

#Run the K Means algorithm, specifying N centers (You have to tell K Means how many clusters to find)
user2Means.log <- kmeans(kObject.log, centers=4, iter.max=10, nstart=100)
#Add the vector of specified clusters back to the original vector as a factor
userNeighbors.df$cluster <- factor(user2Means.log$cluster)
p2 <- nPlot(logFollowersCount ~ logFriendsCount, group = 'cluster', data = userNeighbors.df, type = 'scatterChart')
p2$xAxis(axisLabel = 'Followers Count')
p2$yAxis(axisLabel = 'Friends Count')
p2$chart(tooltipContent = "#! function(key, x, y, e){
return e.point.screenName + ' Followers: ' + e.point.followersCount +' Friends: ' + e.point.friendsCount
} !#")
p2 # This will take a while. I crashed Windows with my twitter details and had to do it on a Mac

My clustered twitter feed using k-means

What does this mean?

As always, you need to be able to interpret the output. Typically, clustering is supposed to separate data into reasonably distinct groups. You expect to find groups of data where the data belongs in the same classification to give you some insight about the data.

There seems to be a definite linear relationship between followers count and friends count but its interesting how the nature of that relationship changes at around 7 or 8 followers. From there on up, it looks like twitter is enforcing a rule because there is a linear lower bound. This might be when people reach a follow limit, as I have done. I can't follow any more people unless more start following me.

When data is 'separable' in the sense that machine learning experts agree, it means there is a way for the given hypothesis to perfectly group data with no overlap. in practice, this is a rare thing indeed, therefore many simple algorithms are adjusted to permit at least some unavoidable bleeding between clusters that don't separate perfectly. Some algorithms won't converge (finish) on non-separable data. Some are sensitive to it, and some behave well.

The graph that we see from this twitter data does not have strong clusters, but there is a vague agreeable grouping. It will take some more study to work out whether the results are useful.

I am:

  • New to R
  • An old hand
  • Confused as can be
  • Happy to find something that works
  • Going to earn gobs of money as a data scientist
  • Just a little bit enriched now
See results without voting

Please rate this work

Cast your vote for K-means in R-Studio on your Twitter data

More by this Author


1 comment

torrilynn profile image

torrilynn 18 months ago

An interesting and informative hub that you have here. thanks.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working