gpt4 book ai didi

python - 梯度下降

转载 作者:行者123 更新时间:2023-12-01 05:21:15 24 4
gpt4 key购买 nike

所以我正在编写一个处理梯度下降的程序。我使用这种方法来求解形式的方程

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

当我在随机矩阵和列上运行最陡距离方法时,我不断出现无限循环。当简单的 2x2 矩阵用于 A 时它工作得很好,但对于 10x10 矩阵它会无限循环。问题出在 np.linalg.norm((A * xNext) - b);它会无限期地增长。这就是为什么我给它设定了上限;然而,我不应该为算法这样做。谁能告诉我问题出在哪里?

最佳答案

用梯度下降求解线性系统 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 必须是正定的。如果存在负特征值,则下降将继续到负无穷大,找不到最小值。

<小时/>

一种解决方法是将 b 替换为 A^tb,将 A 替换为 a^t*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 的条件数的平方。

关于python - 梯度下降,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22306413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com