@@ -31,13 +31,16 @@ def sigmoid_function(z):
3131def cost_function (h , y ):
3232 return (- y * np .log (h ) - (1 - y ) * np .log (1 - h )).mean ()
3333
34+ def log_likelihood (X , Y , weights ):
35+ scores = np .dot (X , weights )
36+ return np .sum (Y * scores - np .log (1 + np .exp (scores )) )
3437
3538# here alpha is the learning rate, X is the feature matrix,y is the target matrix
36-
3739def logistic_reg (
3840 alpha ,
3941 X ,
4042 y ,
43+ num_steps ,
4144 max_iterations = 70000 ,
4245 ):
4346 converged = False
@@ -49,21 +52,24 @@ def logistic_reg(
4952 h = sigmoid_function (z )
5053 gradient = np .dot (X .T , h - y ) / y .size
5154 theta = theta - alpha * gradient
52-
5355 z = np .dot (X , theta )
5456 h = sigmoid_function (z )
5557 J = cost_function (h , y )
56-
5758 iterations += 1 # update iterations
58-
59- if iterations == max_iterations :
60- print ('Maximum iterations exceeded!' )
61- print ('Minimal cost function J=' , J )
62- converged = True
63-
59+ weights = np .zeros (X .shape [1 ])
60+ for step in range (num_steps ):
61+ scores = np .dot (X , weights )
62+ predictions = sigmoid_function (scores )
63+ if step % 10000 == 0 :
64+ print (log_likelihood (X ,y ,weights )) # Print log-likelihood every so often
65+ return weights
66+
67+ if iterations == max_iterations :
68+ print ('Maximum iterations exceeded!' )
69+ print ('Minimal cost function J=' , J )
70+ converged = True
6471 return theta
6572
66-
6773# In[68]:
6874
6975if __name__ == '__main__' :
@@ -72,7 +78,7 @@ def logistic_reg(
7278 y = (iris .target != 0 ) * 1
7379
7480 alpha = 0.1
75- theta = logistic_reg (alpha , X , y , max_iterations = 70000 )
81+ theta = logistic_reg (alpha ,X , y , max_iterations = 70000 , num_steps = 30000 )
7682 print (theta )
7783
7884
0 commit comments