◐ Shell
clean mode source ↗

Python Machine Learning Classifier Tutorial

Machine Learning Classifier

Machine Learning Classifiers can be used to predict. Given example data (measurements), the algorithm can predict the class the data belongs to.

Start with training data. Training data is fed to the classification algorithm. After training the classification algorithm (the fitting function), you can make predictions.

Related course: Complete Machine Learning Course with Python

Machine Learning Classification

In the example below we predict if it’s a male or female given vector data.

We start with training data. In this example we have a set of vectors (height, weight, shoe size) and the class this vector belongs to:


X = [[190,70,44],[166,65,45],[190,90,47],[175,64,39],[171,75,40],[177,80,42],[160,60,38],[144,54,37]]
Y = ['male','male','male','male','female','female','female','female']

Define a vector for your prediction in the same format (height, weight, size). If you want, you can also get this from console input:

P = [[190,80,46]]

Then we fit the training data and predict in this style:

c = Classifier()
c = c.fit(X,Y)
print "\nPrediction : " + str(c.predict(P))

predict

That gives us this code:

from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.ensemble import RandomForestClassifier


X = [[190,70,44],[166,65,45],[190,90,47],[175,64,39],[171,75,40],[177,80,42],[160,60,38],[144,54,37]]
Y = ['male','male','male','male','female','female','female','female']


P = [[190,80,46]]


clf = DecisionTreeClassifier()
clf = clf.fit(X,Y)
print "\n1) Using Decision Tree Prediction is " + str(clf.predict(P))


knn = KNeighborsClassifier()
knn.fit(X,Y)
print "2) Using K Neighbors Classifier Prediction is " + str(knn.predict(P))


mlpc = MLPClassifier()
mlpc.fit(X,Y)
print "3) Using MLPC Classifier Prediction is " + str(mlpc.predict(P))


rfor = RandomForestClassifier()
rfor.fit(X,Y)
print "4) Using RandomForestClassifier Prediction is " + str(rfor.predict(P)) +"\n"

Download examples

Run Python online: PythonAnywhere lets you host and run Python scripts in the cloud — free tier available.