BLOG COMPETITIONS

Intro to machine learning competitions with ‘Numerai’ – example code.

https://secretdatascientist.com

In this post, I want to share, how simple it is to start competing in machine learning tournaments – Numerai. I will go step by step, line by line explaining what is doing what and why it is required.

Numerai is a global artificial intelligence competition to predict financial markets. Numerai is a little bit similar to Kaggle but with clean datasets, so we can pass over long data cleansing process.  You just download the data, build a model, and upload your predictions, that’s it. To extract most of the data you would initially do some feature engineering, but for simplicity of this intro, we will pass this bit over.  One more thing we will pass on is splitting out validation set, the main aim of this exercise is to fit ‘machine learning’ model to training dataset. Later using fitted model, generate a prediction.  All together it shouldn’t take more than 14 simple lines of python code, you can run them as one piece or run part by part in interactive mode.

Let’s go, let’s do some machine learning…

A first thing to do is to go to numer.ai, click on ‘Download Training Data’  and download datasets, after unzipping the archive, you will have few files in there, we are interested mainly in three of them. It is worth noting what is a path to the folder as we will need it later.

I assume you have installed python and required libraries, if not there is plenty of online tutorials on how to do it, I recommend installing Anaconda distribution. It it time to open whatever IDE you use, and start coding, first few lines will be just importing what we will use later, that is Pandas and ScikitLearn.

import pandas as pd 
from sklearn.ensemble import GradientBoostingClassifier

Pandas is used to import data from csv files and do some basic data manipulations, GradientBoostingClassifier as part of ScikitLearn will be the model we will use to fit and do predict. As we have required libraries imported let’s use them… in next three lines, we will import data from csv to memory.  We will use ‘read_csv’  method from pandas, all you need to do is amend the full path to each file, wherever you have extracted numerai_datasets.zip.

train = pd.read_csv("/home/m/Numerai/numerai_datasets/numerai_training_data.csv")
test  = pd.read_csv("/home/m/Numerai/numerai_datasets/numerai_tournament_data.csv")   
sub  = pd.read_csv("/home/m/Numerai/numerai_datasets/example_predictions.csv")

What above code does it creates three data frames and imports the csv files we have we have previously extracted from downloaded numerai_datasets.zip.

‘train’ –  this dataset contains all required data to train our model, so it has both ‘features’ and ‘labels’, so you can say it has both questions and answers that our model will ‘learn’

‘test’ – this one contains features but does not contain ‘labels’, you can say it contains questions and our model will deliver answers.

‘sub’ – it is just template for uploading our prediction

Let’s move on,  in next line will copy all unique row id’s from ‘test’ to ‘sub’ to make sure each predicted value will be assigned to a right set of features, let’s say we put question number next to our answer so whoever checks the test would now.

sub["t_id"]=test["t_id"]

As we have copied the ids to ‘sub’, we don’t need them anymore in ‘test’ (all rows will stay in same order), so we can get rid of them.

test.drop("t_id", axis=1,inplace=True)

In next two lines, we will separate ‘labels’ or target values from train dataset.

labels=train["target"]

train.drop("target", axis=1,inplace=True)

As we have prepared ‘train’ dataset, we can get our model to learn from it. First, we select model we want to use, it will be Gradient BoostingClassifier from ScikitLearn – no specific reason for using this one, you can use whatever you like eg. random forest, linear regression…

grd = GradientBoostingClassifier()

As we have a model defined, let’s have it learn from ‘train’ data.

grd.fit(train,labels)

Ok, now our model is well trained and ready to make predictions, as the task is called ‘classification’ we will predict what is a probability of each set of features belongs to one of two classes ‘0’ or ‘1’.

y_pred = grd.predict_proba(test)

We have a long list of predicted probabilities called ‘y_pred’, let’s attach it to ‘id’ we had separated previously.

sub["probability"]=y_pred[:,1]

And save it in csv format, to get uploaded.

sub.to_csv("/home/m/Numerai/numerai_datasets/SimplePrediction.csv", index=False)

The last thing to do is go back to numer.ai website and click on ‘Upload Predictions’… Good luck.

This was very simplistic and introductory example to start playing with numer.ai competitions and machine learning. I will try and come back with gradually more complicated versions, if you have any questions, suggestions or comments please go to ‘About’ section and contact me directly.

The full code below:

import pandas as pd 
from sklearn.ensemble import GradientBoostingClassifier 
train = pd.read_csv("C:/Users/Downloads/numerai_datasets/numerai_training_data.csv") 
test = pd.read_csv("C:/Users/Downloads/numerai_datasets/numerai_tournament_data.csv") 
sub = pd.read_csv("C:/Users/Downloads/numerai_datasets/example_predictions.csv") 
sub["t_id"]=test["t_id"] 
test.drop("t_id", axis=1,inplace=True) 
labels=train["target"] 
train.drop("target", axis=1,inplace=True)
grd = GradientBoostingClassifier() 
grd.fit(train,labels) 
y_pred = grd.predict_proba(test) 
sub["probability"]=y_pred[:,1] 
sub.to_csv("C:/Users/Downloads/numerai_datasets/SimplePrediction.csv", index=False)

Was the above useful? Please share with others on social media.

If you want to look for more information on data science/statistics, check some free online courses available at   coursera.orgedx.org or udemy.com.

Recommended reading list:

 

Data Science from Scratch: First Principles with Python

Data science libraries, frameworks, modules, and toolkits are great for doing data science, but they’re also a good way to dive into the discipline without actually understanding data science. In this book, you’ll learn how many of the most fundamental data science tools and algorithms work by implementing them from scratch.

If you have an aptitude for mathematics and some programming skills, author Joel Grus will help you get comfortable with the math and statistics at the core of data science, and with hacking skills you need to get started as a data scientist. Today’s messy glut of data holds answers to questions no one’s even thought to ask. This book provides you with the know-how to dig those answers out.

Get a crash course in Python
Learn the basics of linear algebra, statistics, and probability—and understand how and when they're used in data science
Collect, explore, clean, munge, and manipulate data
Dive into the fundamentals of machine learning
Implement models such as k-nearest Neighbors, Naive Bayes, linear and logistic regression, decision trees, neural networks, and clustering
Explore recommender systems, natural language processing, network analysis, MapReduce, and databases
Practical Statistics for Data Scientists: 50 Essential Concepts

Statistical methods are a key part of of data science, yet very few data scientists have any formal statistics training. Courses and books on basic statistics rarely cover the topic from a data science perspective. This practical guide explains how to apply various statistical methods to data science, tells you how to avoid their misuse, and gives you advice on what's important and what's not.

Many data science resources incorporate statistical methods but lack a deeper statistical perspective. If you’re familiar with the R programming language, and have some exposure to statistics, this quick reference bridges the gap in an accessible, readable format.

With this book, you’ll learn:

Why exploratory data analysis is a key preliminary step in data science
How random sampling can reduce bias and yield a higher quality dataset, even with big data
How the principles of experimental design yield definitive answers to questions
How to use regression to estimate outcomes and detect anomalies
Key classification techniques for predicting which categories a record belongs to
Statistical machine learning methods that “learn” from data
Unsupervised learning methods for extracting meaning from unlabeled data
Doing Data Science: Straight Talk from the Frontline

Now that people are aware that data can make the difference in an election or a business model, data science as an occupation is gaining ground. But how can you get started working in a wide-ranging, interdisciplinary field that’s so clouded in hype? This insightful book, based on Columbia University’s Introduction to Data Science class, tells you what you need to know.

In many of these chapter-long lectures, data scientists from companies such as Google, Microsoft, and eBay share new algorithms, methods, and models by presenting case studies and the code they use. If you’re familiar with linear algebra, probability, and statistics, and have programming experience, this book is an ideal introduction to data science.

Topics include:

Statistical inference, exploratory data analysis, and the data science process
Algorithms
Spam filters, Naive Bayes, and data wrangling
Logistic regression
Financial modeling
Recommendation engines and causality
Data visualization
Social networks and data journalism
Data engineering, MapReduce, Pregel, and Hadoop
The Data Science Handbook: Advice and Insights from 25 Amazing Data Scientists

The Data Science Handbook contains interviews with 25 of the world s best data scientists. We sat down with them, had in-depth conversations about their careers, personal stories, perspectives on data science and life advice. In The Data Science Handbook, you will find war stories from DJ Patil, US Chief Data Officer and one of the founders of the field. You ll learn industry veterans such as Kevin Novak and Riley Newman, who head the data science teams at Uber and Airbnb respectively. You ll also read about rising data scientists such as Clare Corthell, who crafted her own open source data science masters program. This book is perfect for aspiring or current data scientists to learn from the best. It s a reference book packed full of strategies, suggestions and recipes to launch and grow your own data science career.
Introduction to Machine Learning with Python: A Guide for Data Scientists

Machine learning has become an integral part of many commercial applications and research projects, but this field is not exclusive to large companies with extensive research teams. If you use Python, even as a beginner, this book will teach you practical ways to build your own machine learning solutions. With all the data available today, machine learning applications are limited only by your imagination.

You’ll learn the steps necessary to create a successful machine-learning application with Python and the scikit-learn library. Authors Andreas Müller and Sarah Guido focus on the practical aspects of using machine learning algorithms, rather than the math behind them. Familiarity with the NumPy and matplotlib libraries will help you get even more from this book.

With this book, you’ll learn:

Fundamental concepts and applications of machine learning
Advantages and shortcomings of widely used machine learning algorithms
How to represent data processed by machine learning, including which data aspects to focus on
Advanced methods for model evaluation and parameter tuning
The concept of pipelines for chaining models and encapsulating your workflow
Methods for working with text data, including text-specific processing techniques
Suggestions for improving your machine learning and data science skills