Could you guys tell me how I can make the following code more pythonic?
The code is correct. Full disclosure - Problem 1b in Handout No. 4 of this machine learning course. I have to use Newton's algorithm for two data sets to fit the logistic hypothesis. But they use matlab and I use scipy
For example, one question: I have matrices rounded to integers until I initialize one value to 0.0. Is there a better way?
thanks
import os.path
import math
from numpy import matrix
from scipy.linalg import inv
x = matrix( '0.0;0;1' )
y = 11
grad = matrix( '0.0;0;0' )
hess = matrix('0.0,0,0;0,0,0;0,0,0')
theta = matrix( '0.0;0;0' )
for i in range(1, 6):
grad = matrix( '0.0;0;0' )
hess = matrix('0.0,0,0;0,0,0;0,0,0')
xfile = open("q1x.dat", "r")
yfile = open("q1y.dat", "r")
for i in range(1, 100):
xline = xfile.readline()
s= xline.split(" ")
x[0] = float(s[1])
x[1] = float(s[2])
y = float(yfile.readline())
hypoth = 1/ (1+ math.exp(-(theta.transpose() * x)))
for j in range(0,3):
grad[j] = grad[j] + (y-hypoth)* x[j]
for k in range(0,3):
hess[j,k] = hess[j,k] - (hypoth *(1-hypoth)*x[j]*x[k])
theta = theta - inv(hess)*grad
xfile.close()
yfile.close()
print "done"
print theta
source
share