人工智能数学基础python学习:
##Day1 sympy库
1.
内置符号
sympy.E自然对数底e
sympy.oo 无穷大
sympy.pi 圆周周率
初等运算
sympy.log 对数运算
sympy.sin 正弦函数
sympy.sqrt 求平方根
sympy.factorial 求阶乘
求极限 sympy.limit
求导数 sympy.diff
import sympy //导入sympy库
x=sympy.Symbol('x') //定义x符号
fx=5*x+4
y=fx.evalf(subs={x:1}) //evalf函数传值
printf(y)
import sympy
x=sympy.Symbol('x')
f=(x**2-1)/(x-1)
result=sympy.limit(f,x,1) //求极限x=1时
print(result)
4。
import sympy
from sympy.abc import x, y 输出为x,y符号
y=sympy.asin(sympy.sqrt(sympy.sin(x))) ///定义表达式y=arcsin(sin(x)**(1/2))
result = sympy.diff(y)
print(result)
求偏导
import sympy
from sympy.abc import x,y,f
f=x**2+3*x*y+y**2
fx=sympy.diff(f,x) //x偏导数
fy=sympy.diff(f,y)
print (fx.evalf(subs={x:1,y:2}))
print(fy.evalf(subs={x:1,y:2}))
//方向导数,在P(1,0)出,从P(1,0)到Q(2,-1)方向导数
import sympy
from sympy.abc import x,y,z
z=x*sympy.exp(2**y)
zx=sympy.diff(z,x)
zy=sympy.diff(z,y)
result=zx.evalf(subs={x:1,y:0})*sympy.cos(-sympy.pi/4)+zy.evalf(subs={x:1,y:0})*sin(-sympy.pi/4)
print(result)
求梯度及最大值
1.
import sympy
from sympy.abc import x,y,z,u
u=x*y*z+z**2+5 //定义表达式
ux=sympy.diff(u,x)
uy=sympy.diff(u,y)
uz=sympy.diff(u,z)
gradu=[ux.subs({x:0,y:1,z:-1}), uy.subs({x:0,y:1,z:-1}),uz.subs({x:0,y:1,z:-1}) ]
print (gradu)
maxgradu=sympy.sqrt(gradu[0]**2+gradu[1]**2+gradu[2]**2)
print (maxgradu)
2.
import sympy
from sympy.abc import x,y,z
z=x**2+y**2
zx=sympy.diff(z,x)
zy=sympy.diff(z,y)
result=zx.evalf(subs={x:1,y:2})*sympy.cos(sympy.pi/3)+zy.evalf(subs={x:1,y:2})*sympy.sin(sympy..pi/3)
print(result)
gradz=[zx.subs({x:1,y:2}),zy.subs({x:1,y:2})]
print(gradz)
学习
梯度下降求函数最小值
import matplotilb.pyplot as plt
from mpl_toolk.mplot3d import Axes3D
import numpy as np
def Fun (x,y)
return x-y+2*x*x+2*x*y+y**2
def Fun(x,y)
return 1+4*x+2*y
def Fun (x,y)
return -1+2*x+2*y
step = 0.0008
x=0
y=0
tag_x=[x]
tag_y=[y];tag_z=[Fun(x,y)]
new_x=x
new_y=y
Over=False
while Over ==False:
new_x-=step*PxFun(x,y)
new_y-=step*PyFun(x,y)
if Fun(x,y)-Fun(new_x,new_y)<7*sympy.E-9:
Over=True
x=new_x
y=new_y
print(x,y)