所以我正在写一个处理梯度下降的程序。我用这种方法来求解形式的方程
Ax = b
where A is a random 10x10 matrix and b is a random 10x1 matrix这是我的代码:
import numpy as np
import math
import random
def steepestDistance(A,b,xO, e):
xPrev = xO
dPrev = -((A * xPrev) - b)
magdPrev = np.linalg.norm(dPrev)
danger = np.asscalar(((magdPrev * magdPrev)/(np.dot(dPrev.T,A * dPrev))))
xNext = xPrev + (danger * dPrev)
step = 1
while (np.linalg.norm((A * xNext) - b) >= e and np.linalg.norm((A * xNext) - b) < math.pow(10,4)):
xPrev = xNext
dPrev = -((A * xPrev) - b)
magdPrev = np.linalg.norm(dPrev)
danger = np.asscalar((math.pow(magdPrev,2))/(np.dot(dPrev.T,A * dPrev)))
xNext = xPrev + (danger * dPrev)
step = step + 1
return xNext
##print(steepestDistance(np.matrix([[5,2],[2,1]]),np.matrix([[1],[1]]),np.matrix([[0.5],[0]]), math.pow(10,-5)))
def chooseRandMatrix():
matrix = np.zeros(shape = (10,10))
for i in range(10):
for a in range(10):
matrix[i][a] = random.randint(0,100)
return matrix.T * matrix
def chooseRandColArray():
arra = np.zeros(shape = (10,1))
for i in range(10):
arra[i][0] = random.randint(0,100)
return arra
for i in range(4):
matrix = np.asmatrix(chooseRandMatrix())
array = np.asmatrix(chooseRandColArray())
print(steepestDistance(matrix, array, np.asmatrix(chooseRandColArray()),math.pow(10,-5)))当我在随机矩阵和列上运行steepestDistance方法时,我总是得到一个无限循环。当A使用简单的2x2矩阵时,它工作得很好,但对于10x10矩阵,它却无限期地循环。问题在于np.linalg.norm((A * xNext) - b);它一直在无限期地增长。这就是为什么我在它上加了一个上限;但是,我不应该为算法这么做。有人能告诉我问题出在哪里吗?
发布于 2014-03-10 19:38:50
求解具有梯度下降均值的线性系统Ax=b最小化二次函数
f(x) = 0.5*x^t*A*x - b^t*x. 这只有当矩阵A是对称的,A=A^t,因为f的导数或梯度是
f'(x)^t = 0.5*(A+A^t)*x - b, 另外,A必须是正定的。如果有负特征值,那么下降将继续到负无穷大,就没有最小值。
一种方法是用A^tb代替b,用a^t*A代替A,即将函数最小化。
f(x) = 0.5*||A*x-b||^2
= 0.5*x^t*A^t*A*x - b^t*A*x + 0.5*b^t*b带梯度
f'(x)^t = A^t*A*x - A^t*b但是对于大矩阵A,这是不推荐的,因为A^t*A的条件数大约是A的条件数的平方。
https://stackoverflow.com/questions/22306413
复制相似问题