你如何使这个代码更pythonic?

Mer*_*nel 3 python machine-learning scipy

你能告诉我如何使下面的代码更加pythonic吗?

代码是正确的.全面披露-它的问题1B在单张#4 机学习课程.我应该在两个数据集上使用牛顿算法来拟合逻辑假设.但是他们使用matlab而我正在使用scipy

例如我有一个问题是矩阵保持四舍五入到整数,直到我将一个值初始化为0.0.有没有更好的办法?

谢谢

import os.path
import math
from numpy import matrix
from scipy.linalg import inv #, det, eig

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'  ) 


# run until convergence=6or7
for i in range(1, 6):
  #reset
  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")


  #over whole set=99 items  
  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 #update theta after construction

  xfile.close()
  yfile.close()

print "done"
print theta
Run Code Online (Sandbox Code Playgroud)

Bri*_*ian 9

一个明显的变化是摆脱"for i in range(1,100):"并迭代文件行.要迭代这两个文件(xfile和yfile),请压缩它们.即用以下内容替换该块:

 import itertools

 for xline, yline in itertools.izip(xfile, yfile):
    s= xline.split("  ")
    x[0] = float(s[1])
    x[1] = float(s[2])
    y = float(yline)
    ...
Run Code Online (Sandbox Code Playgroud)

(这假设文件是​​100行,(即你想要整个文件).如果你故意限制 100行,你可以使用类似的东西:

 for i, xline, yline in itertools.izip(range(100), xfile, yfile):
Run Code Online (Sandbox Code Playgroud)

但是,在同一个文件上迭代6次效率也很低 - 最好先将它加载到内存中,然后在那里循环,即.在你的循环之外,有:

xfile = open("q1x.dat", "r")
yfile = open("q1y.dat", "r")
data = zip([line.split("  ")[1:3] for line in xfile], map(float, yfile))
Run Code Online (Sandbox Code Playgroud)

内部只是:

for (x1,x2), y in data:
    x[0] = x1
    x[1] = x2
     ...
Run Code Online (Sandbox Code Playgroud)