Python Learn and Predict Examples

This article reviews examples of the Python learn and predict functionality. To learn more about Python learn and predict, click here.

In the following example, an SVM script is used to predict the purchase of bikes based on a customer's income and number of children.

import pandas from sklearn import svm __pyramidOutput=0 def pyramid_learn(df): X = df.iloc[:,0:2] y= df.iloc[:,2] clf = svm.SVC(gamma=0.001, C=1.0) clf.fit(X, y) return clf def pyramid_eval(model, df): X = df.iloc[:,0:2] y = df.iloc[:,2] output = model.predict(X) correctCount=0 for idx,item in enumerate(output): if item == y.iloc[idx]: correctCount+=1 return str(correctCount / len(y)) def pyramid_predict(model, df): X = df.iloc[:,0:2] output = model.predict(X) return pandas.DataFrame({'Prediction':output})

Learn

In the learn function, X = the first 2 columns given as the input, and Y = the last column given as the output.

def pyramid_learn(df): X = df.iloc[:,0:2] y= df.iloc[:,2]

clf is the ML model that will be returned by the learn function:

clf = svm.SVC(gamma=0.001, C=1.0) clf.fit(X, y) return clf

Eval

The eval function takes the model returned by the learn function (model) and runs it against a testing set (df):

def pyramid_eval(model, df): X = df.iloc[:,0:2] y = df.iloc[:,2]

The output is a set of predictions:

output = model.predict(X)

The predictions are then compared with the actual data, and this comparison returns the model score return str(correctCount / len(y)):

correctCount=0 for idx,item in enumerate(output): if item == y.iloc[idx]: correctCount+=1 return str(correctCount / len(y))

Predict

The predict function applies the ML model to the entire data set and returns the set of predictions:

def pyramid_predict(model, df): X = df.iloc[:,0:2] output = model.predict(X)