机器学习—数学基础【1】
1采用两种方法求取以下方程的解,并采用绘图的方式比较两种方法的结果。
#
import matplotlib.pyplot as plt
import numpy as np
import numpy.linalg as nl
import sympy as sp
#法一:
A=np.array([[3,-2,1],[2,-1,1],[1,1,1]])
#print(A)
B=np.array([-1,-1,2])
#print(B)
solve1=nl.solve(A,B)
print(solve1)
#法二
C=nl.inv(A)#矩阵求逆
#print(C)
solve2=np.dot(C,B)
print(solve2)
#法三
x,y,z=sp.symbols("x y z")
f1=3*x-2*y+z+1
f2=2*x-1*y+z+1
f3=x+y+z-2
s_3=sp.linsolve([f1,f2,f3],(x,y,z))
solve3=list(list(s_3)[0])
print(solve3)
#区别
plt.figure(figsize=(2,12))
plt.subplot(311)
plt.plot(solve1[0],solve1[1],marker='o',color='r',linestyle='')
plt.plot(solve2[0],solve2[1],marker='d',color='y',linestyle='')
plt.plot(solve3[0],solve3[1],marker='*',color='g',linestyle='')
label=['s1_XY','s2_XY','s3_XY']
plt.legend(label,loc='upper right')
plt.subplot(312)
plt.plot(solve1[1],solve1[2],marker='o',color='r',linestyle='')
plt.plot(solve2[1],solve2[2],marker='d',color='y',linestyle='')
plt.plot(solve3[1],solve3[2],marker='*',color='g',linestyle='')
label=['s1_YZ','s2_YZ',"s3_YZ"]
plt.legend(label,loc='upper right')
plt.subplot(313)
plt.plot(solve1[0],solve1[2],marker='o',color='r',linestyle='')
plt.plot(solve2[0],solve2[2],marker='d',color='y',linestyle='')
plt.plot(solve3[0],solve3[2],marker='*',color='g',linestyle='')
label=['s1_XZ','s2_XZ',"s3_XZ"]
plt.legend(label,loc='upper right')
plt.show()
2利用面向对象编程方法设计画圆类,实例化该类后可绘制指定半径的圆。
class Circle:
x0=0
y0=0
r=0
def __init__(self,x,y,radius):
self.x0=x
self.y0=y
self.r=radius
def Draw_Circle(self):
x=np.linspace(self.x0-self.r,self.x0+self.r,1500)
y1=self.y0+np.sqrt(np.power(self.r,2)-np.power(x-self.x0,2))
y2=self.y0-np.sqrt(np.power(self.r,2)-np.power(x-self.x0,2))
plt.figure()
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Circle_Draw")
plt.axis('equal')
plt.plot(x,y1,linestyle='-',color='r')
plt.plot(x,y2,linestyle='-',color='r')
plt.scatter(self.x0,self.y0,marker='o',color='k')
plt.grid()
plt.show()
c=Circle(0,0,2)
c.Draw_Circle()
3画出Logistic函数曲线及过点(0,0.5)的水平线(观察其与f(x)函数之间的关系)f(x)=1/(1+e^-x)
x=np.linspace(-6,6,1500)
y=1/(1+np.exp(-x))
plt.figure()
plt.xlim(-6,6)
plt.ylim(0,1.2)
plt.yticks(np.linspace(0,1,5,endpoint=True))
plt.scatter(0,0.5,marker='o')
plt.plot(x,y,linestyle='-',color='k')
plt.plot(x,np.ones(len(x))*0.5,linestyle='-.',color='grey')
plt.text(0.5,0.53,(0,0.5))
plt.grid(True)
plt.show()
总结: