# Import the required modules
%pylab inline
from theano import tensor as T
from theano import function
from theano import pp
from theano import Param
from theano import grad
from theano import shared
import numpy as np
class LogisticRegression:
'''
This class performs logistic regression.
'''
def __init__(self, alpha=0.001, iterations=10000, threshold=.5):
'''
1. alpha is the learning rate.
The default value of alpha is 0.001.
2. iterations is the number of times the weights will be updated.
The default value is 1000
3. threshold is the threshold used to convert the probability
to either 0 or 1 class label
'''
# Set the learning rate
self.alpha = alpha
# Set the number of iterations
self.iterations = iterations
# Set the threshold value
self.threshold = threshold
# Define the symbolic Variables
X, W = T.dmatrices('training-set', 'weights')
y = T.matrix('testing-set')
m, a = T.scalars('no-of-samples', 'learning-rate')
# Define the cost function and the gradient functions
sigmoid_fn = 1/(1 + T.exp(-T.dot(X, W)))
h = sigmoid_fn
cost_fn = -((T.dot(y, T.transpose(h)) + T.dot(1 - y, T.transpose(1 - h)))/(1 * m)).sum()
grad_fn = (T.dot(T.transpose(X), h - y))/(m)
updated_wts = W - a * grad_fn
# Compile the Theano functions
self.cost = function([X, y, W, m], cost_fn)
self.new_wts = function([X, y, W, m, a], updated_wts)
self.pred = function([X, W], h)
def fit(self, X, y):
'''
The fit member function is used to train the classifier.
1. X is array-like data vector
2. y is array-like target vector
'''
# Add the bias feature to the data samples
bias = np.ones((X.shape[0], 1))
X = np.hstack((X, bias))
# m is the number of data samples used
m = X.shape[0]
# Initialize all weights to 0
self.W = np.zeros((X[0].shape[0],1), dtype=np.float)
# Iterate and update the cost function and the weights
for i in xrange(self.iterations):
cst = self.cost(X, y, self.W, m)
self.W = self.new_wts(X, y, self.W, m, self.alpha)
# Set the coef_ and intercept_
self.coef_ = self.W[:-1]
self.intercept_ = self.W[-1]
def predict(self, X):
'''
This is function to predict target value.
1. X is array-like data vector whose target vector is predicted
'''
# Add the bias feature to the data samples
bias = np.ones((X.shape[0], 1))
X = np.hstack((X, bias))
# Return the predicted target label
return (self.pred(X, self.W) > self.threshold) * 1
def predict_proba(self, X):
'''
This is function gives the probability of how sure.
1. X is array-like data vector whose target vector is predicted
'''
# Add the bias feature to the data samples
bias = np.ones((X.shape[0], 1))
X = np.hstack((X, bias))
# Return the predicted target label
prob = self.pred(X, self.W)
for index, value in enumerate(prob < self.threshold):
if value:
prob[index] = 1 - prob[index]
return prob