To create a function class, the parameters of the constructor function are
Where part is the function of the bias Guide, Var_index is the number of variables, Val represents the values of these variables
The function of diff is to facilitate the derivation of a unary function
In order to facilitate the linear algebra operation of the gradient, the return value is converted to the Numpy.array type when the GRAD function is defined.
#the derivative obtained is an approximate result fromNumPyImport*#Defining function ClassesclassFunction:def __init__(self, _f): Self.fun=_fdefvalue (Self, val):returnSelf.fun (val)#biased Guide defPart (self, Var_index, Val): a=Self.fun (val) b= A + 1I=0 E= 1E1= 0.1 whileE > 10 * * (-6)orE >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-= 2e= ABS (b-a)returna#derivation of a unary function defdiff (Self, val): a=Self.fun (val) b= A + 1I=0 E= 1E1= 0.1 whileE > 10 * * (-6)orE >e1:e1=e a=b val_= val + 10 * *i m=Self.fun (VAL_) n=Self.fun (val) b= (m-n)/10 * *I i-= 2e= ABS (b-a)returna#Seeking gradients defGrad (Self, val): G=Array (val) forIinchRange (0, g.size): G[i]=Self.part (i, Val)returnArray (g)#die-Finding defNorm (Self, Val): s=0 forXinchSelf.grad (val): s+ = x * * 2returnsqrt (s)
Using Python to realize the derivation, gradient and modulus of two-times function