PySpark ML Example 1

Here is my first Spark Code in PySpark. I am using Spark with some commodity Hardware.

The first line is to tell Zepplin(Browser Editor like Jupyter) that code is written in PySpark. As you can see, we have used LabeledPoint for creating data points. We have used a LogisticRegression model for this classification job.

The overall goal of this example is to show how easy is to do ML in Spark.

%pyspark

from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.classification import LogisticRegressionWithLBFGS

## Data
data = [LabeledPoint(0.0, [0.0, 1.0]), LabeledPoint(1.0, [1.0, 0.0])]

## Modelling
lrm = LogisticRegressionWithLBFGS.train(sc.parallelize(data), iterations=10)

## Prediction
print(lrm.predict([0.0, 0.1]))
print(lrm.predict([0.5, 0.4]))
print(lrm.predict([1.0, 0.1]))

And here is our favorite Iris dataset problem.

%pyspark

from sklearn import datasets
from pyspark.mllib.tree import RandomForest

## Data
iris = datasets.load_iris()
X = iris.data
Y = iris.target
data = map(lambda (x,y): LabeledPoint(y, x), zip(X, Y))

## Modelling
model = RandomForest.trainClassifier(sc.parallelize(data), 3, {}, 3, seed=42)

## Prediction
preds = [model.predict(_) for _ in X]

## Accuracy
print(sum(preds == Y) * 1.0/ len(Y))

To summarise

  1. Get your imports
  2. Prepare the data
    1. Numeric Data. If not get labeled
    2. LabelPoint the Data.
  3. Model creation
    1. Prone to issues a lot
  4. Check Accuracy
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s