Logistic regression/ Simple NN in Python
Published in
2 min readJan 19, 2018
sklearn
Preprocessing
#Sigmoid function
s = 1/(1+np.exp(-x))#Sigmoid gradient
s = sigmoid(x)
ds = s*(1-s)#Reshaping arrays
v = v.reshape(v.shape[0]*v.shape[1]*v.shape[2],1)
v = v.reshape(v.shape[0], -1).T#Normalizing rows
x_norm = np.linalg.norm(x,axis=1,keepdims=True)
x = x/x_norm#Sums each row
np.sum(x, axis=1, keepdims=True)#Vector square
X2 = np.dot((y-yhat),(y-yhat)) = sum(np.square(y-yhat))
Linear Logistic Regression
#Train the logistic regression classifier
clf = sklearn.linear_model.LogisticRegressionCV();
clf.fit(X, Y);#Plot the decision boundary for logistic regression
plot_decision_boundary(lambda x: clf.predict(x), X, Y)#Accuracy
LR_predictions = clf.predict(X.T)
accuracy = float((np.dot(Y,LR_predictions) + np.dot(1-Y,1-LR_predictions))/float(Y.size)*100)
Neural Network model
#Initialize the parameters
W1 = np.random.randn(n_h, n_x)*0.01
b1 = np.zeros((n_h, 1))
W2 = np.random.randn(n_y, n_h)*0.01
b2 = np.zeros((n_y, 1))----FOR LOOP----
#Forward propagation
#Retrieve each parameter from the dictionary "parameters"
W1 = parameters['W1']
b1 = parameters['b1']
W2 = parameters['W2']
b2 = parameters['b2']#Implement Forward Propagation to calculate
Z1 = np.dot(W1,X)+b1
A1 = np.tanh(Z1)
Z2 = np.dot(W2,A1)+b2
A2 = sigmoid(Z2)#Compute cost
logprobs = np.multiply(np.log(A2),Y)+np.multiply(np.log(1-A2),1-Y)
cost = -(1/m)*np.sum(logprobs)
cost = np.squeeze(cost)
# makes sure cost is the dimension we expect.
# E.g., turns [[17]] into 17#Backward propagation
dZ2= A2-Y
dW2 = (1/m)*np.dot(dZ2,A1.T)
db2 = (1/m)*np.sum(dZ2,axis=1,keepdims=True)
dZ1 = np.dot(W2.T,dZ2)*(1-np.power(A1,2))
dW1 = (1/m)*np.dot(dZ1,X.T)
db1 = (1/m)*np.sum(dZ1,axis=1,keepdims=True)#Update parameter
W1 = W1-dW1*learning_rate
b1 = b1-db1*learning_rate
W2 = W2-dW2*learning_rate
b2 = b2-db2*learning_rate----FOR LOOP END----