やっている間、勾配降下の単純な実装(サンプルポイントを入力としてstラインを予測する)だけで、反復法でラインをかなり正確に予測しましたが、fmin_cg()を使用すると精度が低下し、最初に考えたのは増加することでした関数の 'maxiter' パラメーターを使用しましたが、驚くべきことに、まったく影響がありませんでした (結果は maxiters = 1 と 1000 で同じです)。私の頭の中の 2 つの質問: fmin_cg() は、f と fprime を計算しますが、結果の精度はそれに比例するべきではありません.. 2. fmin_cg() (apt fprime が提供されている場合) は、f が可能な限り最小であるパラメーターを返すことを保証します。
私のコード:
def gradDesc(theta, data, alpha = None, iterations = None):
X = data[:, 0]
y = data[:, 1]
m = shape(X)[0]
X = c_[ones((m, 1)), X]
y = y.reshape(m, 1)
hypo = X.dot(theta)
grad = zeros((2, 1))
if alpha is not None : #"""iterative method"""
for i in range (0, iterations):
hypo = X.dot(grad)
ausi = X.T.dot(hypo - y)
grad -= alpha / m * ausi
else: #returns derivative of cost(), to use fmin_cg in run()
grad = X.T.dot(hypo.reshape(m, 1) - y)/m
# print(grad)
return grad.flatten()
def run(theta, data ):
result = scipy.optimize.fmin_cg( cost, fprime=gradDesc, x0=theta, \
args = (data, ), maxiter=1, disp=False, full_output=True )
theta = result[0]
minCost = result[1]
return theta, minCost
コスト関数 :
def cost( theta, data ):
X, y = data[:, 0], data[:, 1]
m = shape(X)[0]
y = y.reshape(m, 1)
X = c_[ones((m, 1)), X]
J = X.dot(theta) - y
# print((J.T.dot(J) / (2*m)) [0, 0])
return (J.T.dot(J) / (2*m)) [0, 0]
完全なコード: http://ideone.com/IbB3Gb (どちらのバージョンも、4 行目と 5 行目を切り替える必要があるとコメントしただけです) :)