建立一个Function类,构造函数的参数是一个函数
其中part的功能是求偏导,var_index表示是第几个变量,val表示这些变量的值
diff的功能是方便一元函数求导
为方便梯度进行线性代数运算,在定义grad函数时,返回值转化成了numpy.array类型
#求导所得为近似结果 from numpy import * #定义Function类 class Function: def __init__(self, _f): self.fun = _f def value(self, val): return self.fun(val) #求偏导 def part(self, var_index, val): a = self.fun(val) b = a + 1 i = 0 e = 1 e1 = 0.1 while e > 10 ** (-6) or e > e1: e1 = e a = b val_ = list(val) val_[var_index] += 10 ** i m = self.fun(val_) n = self.fun(val) b = (m - n) / 10 ** i i -= 2 e = abs(b - a) return a #一元函数求导 def diff(self, val): a = self.fun(val) b = a + 1 i = 0 e = 1 e1 = 0.1 while e > 10 ** (-6) or e > e1: e1 = e a = b val_ = val + 10 ** i m = self.fun(val_) n = self.fun(val) b = (m - n) / 10 ** i i -= 2 e = abs(b - a) return a #求梯度 def grad(self, val): g = array(val) for i in range(0, g.size): g[i] = self.part(i, val) return array(g) #求模 def norm(self, val): s = 0 for x in self.grad(val): s += x ** 2 return sqrt(s)
原文地址:https://www.cnblogs.com/kisetsu/p/9145393.html
时间: 2024-10-08 07:41:52