Created
October 10, 2012 13:38
-
-
Save chokkan/3865703 to your computer and use it in GitHub Desktop.
Logistic Regression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
import random | |
def train(w, D, T): | |
for t in range(1, T+1): | |
x, y = random.choice(D) | |
a = sum([w[i] * x[i] for i in range(len(w))]) # a(x) = w \cdot x | |
g = y - (1. / (1. + math.exp(-a))) if -100. < a else y # g = y - p | |
eta = 1. / t | |
for i in range(len(w)): # w ← w + eta * g * x | |
w[i] += eta * g * x[i] # | |
def prob(x): | |
a = sum([w[i] * x[i] for i in range(len(w))]) # a(x) = w \cdot x | |
return 1. / (1 + math.exp(-a)) if -100. < a else 0. # p = 1/(1 + exp(a)) | |
if __name__ == '__main__': | |
w = [0.] * 9 | |
D = ( | |
((1, 1, 1, 1, 1, 1, 0, 0, 0), 1), | |
((1, 0, 0, 0, 1, 1, 1, 1, 1), 0), | |
) | |
train(w, D, 10000) | |
print prob(D[0][0]), prob(D[1][0]) | |
print w |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment