工具使用模板
import matplotlib.pyplot as plt
import math
import numpy as np
import numpy.linalg as LA
from sympy import *
import sympy as sp
import scipy
from scipy.integrate import quad
from scipy.optimize import fsolve,fminbound,fmin,minimize
from scipy.optimize import linprog,curve_fit
from sklearn.preprocessing import minmax_scale,scale
import matplotlib.pyplot as plt
import cvxpy as cp
def fuhaojisuan():
x,y,z=symbols('x y z')
expr1 = y**2+sin(y)*cos(x)+sin(z)
print("expr1=",expr1)
print("x=1,y=1,z=1时,expr1=",expr1.subs({x:1,y:1,z:1}))
print(limit(sin(x)/x,x,0))
print(limit(pow(1+1/x,x),x,oo))
z = sin(x)+x**2*exp(y)
print("关于x的二阶偏导数为",diff(z,x,2))
k,n= symbols('k n')
print(summation(k**2,(k,1,n)))
print(factor(summation(k**2,(k,1,n))))
print(summation(1/k**2,(k,1,oo)))
y = sin(x)
for k in range(3,8,2):
print(y.series(x,0,k))
plot(y,series(y,x,0,3).removeO(),series(y,x,0,5).removeO(),series(y,x,0,7).removeO(),(x,0,2),xlabel='x',ylabel='y')
print(integrate(sin(2*x),(x,0,pi)))
print(integrate(sin(x)/x,(x,0,oo)))
x,y=symbols('x y')
print(solve(x**3-1,x))
print(solve((x-2)**2*(x-1)**3,x))
print(roots((x-2)**2*(x-1)**3,x))
print(solve([x**2+y**2-1,x-y],[x,y]))
x = symbols('x')
y = symbols('y',cls=Function)
eq1 = diff(y(x),x,2)-5*diff(y(x),x)+6*y(x)
eq2 = diff(y(x),x,2)-5*diff(y(x),x)+6*y(x)-x*exp(2*x)
print("齐次方程的解为:",dsolve(eq1,y(x)))
print("非齐次方程的解为:",dsolve(eq2,y(x)))
def shuzhijisuan():
def diff(f, dx=1E-8):
return lambda x: (f(x + dx) - f(x - dx)) / (2 * dx)
def diff2(f, dx=1E-8):
return lambda x: (f(x + dx) + f(x - dx) - f(x) * 2) / (dx * dx)
def trapezoid(f,n,a,b):
xi = np.linspace(a,b,n)
h = (b-a)/(n-1)
return h*(np.sum(f(xi))-(f(a)+f(b))/2)
def simpson(f,n,a,b):
xi,h =np.linspace(a,b,2*n+1),(b-a)/(2.0*n)
xe = [f(xi[i]) for i in range(len(xi)) if i%2==0]
xo = [f(xi[i]) for i in range(len(xi)) if i%2!=0]
return h*(2*np.sum(xe)+4*np.sum(xo)-f(a)-f(b))/3.0
a=0;b=1;n=1000
f=lambda x:np.sin(np.sqrt(np.cos(x)+x**2))
print("梯形法求得的积分为:",trapezoid(f,n,a,b))
print("辛普森公式法求得的积分为:",simpson(f,n,a,b))
print("Scipy求得的积分为:",quad(f,a,b))
def binary_search(f, eps, a, b):
c = (a + b) / 2
while np.abs(f(c)) > eps:
if f(a) * f(c) < 0:
b = c
else:
a = c
c = (a + b) / 2
return c
def newton_iter(f, eps, x0, dx=1E-8):
def diff(f, dx=dx):
return lambda x: (f(x + dx) - f(x - dx)) / (2 * dx)
df = diff(f, dx)
x1 = x0 - f(x0) / df(x0)
while np.abs(x1 - x0) >= eps:
x1, x0 = x1 - f(x1) / df(x1), x1
return x1
f=lambda x:x**3+1.1*x**2+0.9*x-1.4
print("二分法求得的根为:",binary_search(f,1E-6,0,1))
print("牛顿迭代法求得的根为:",newton_iter(f,1E-6,0))
print("直接调用Scipy求得的根为:",fsolve(f,0))
f=lambda x:np.exp(x)*np.cos(2*x)
x0 = fminbound(f,0,3)
print("fminbound求得的极小点为:{},极小值为:{}".format(x0,f(x0)))
x0 = fmin(f,0)
print("fmin求得的极小点为:{},极小值为:{}".format(x0,f(x0)))
f=lambda x:100*(x[1]-x[0]**2)**2+(1-x[0])**2
x0 = minimize(f,[2.0,2.0])
print("minimize求得的极小点为:{},极小值为:{}".format(x0.x,x0.fun))
def xianxingdaishu():
A=sp.Matrix([[1],[2],[3]])
B=sp.Matrix([[4],[5],[6]])
print("A的模为:",A.norm())
print("A的模的浮点数为:",A.norm().evalf())
print("A的转置矩阵为:",A.T)
print("A和B的点乘为:",A.dot(B))
print("A和B的叉乘为:",A.cross(B))
A = sp.Matrix(np.arange(1,17).reshape(4,4))
B = sp.eye(4)
print("A的行列式为:",sp.det(A))
print("A的秩为:",A.rank())
print("A的转置矩阵为:",A.transpose())
print("A+B的逆矩阵为:",(A+B).inv())
print("A的平方为:",A**2)
print("A,B的乘积为:",A*B)
print("横连矩阵为:",A.row_join(B))
print("纵连矩阵为:",A.col_join(B))
print("A1为",A[0:2,0:2])
A2=A.copy()
A2.row_del(3)
print("A2为",A2)
print("A的行最简形以及所在的列为:\n",A.rref())
print("A的特征值为:",A.eigenvals())
print("A的特征向量为:",A.eigenvects())
a=np.arange(1,4)
b=np.arange(4,7)
print("a的二范数为:",np.linalg.norm(a))
print("a点乘b=",a.dot(b))
print("a,b的内积=",np.inner(a,b))
print("a叉乘b=",np.cross(a,b))
A = np.arange(1,17).reshape(4,4)
B = np.eye(4)
print("A的行列式为:",np.linalg.det(A))
print("A的秩为:",np.linalg.matrix_rank(A))
print("A的转置矩阵为:",A.transpose())
print("A+B的逆矩阵为:",np.linalg.inv(A+B))
print("A的平方为:",A.dot(A))
print("A,B的乘积为:",A.dot(B))
print("横连矩阵为:",np.c_[A,B])
print("纵连矩阵为:",np.r_[A,B])
print("A1为:\n",A[0:2,0:2])
A2=A.copy()
A2=np.delete(A2,3,axis=0)
print("A2为:\n",A2)
A = np.array([[1,-5,2,-3],[5,3,6,-1],[2,4,2,1]])
print("A的零空间(即基础解系)为:",scipy.linalg.null_space(A))
A = np.array([[0,-2,2],[-2,-3,4],[2,4,3]])
values,vectors=np.linalg.eig(A)
print("A的特征值为:",values)
print("A的特征向量为:",vectors)
def guihua():
def biaozhun(c,A,b,Aeq,beq,Lb,Ub):
bounds = tuple(zip(Lb,Ub))
res = linprog(c,A,b,Aeq,beq,bounds)
print(res.fun)
print(res.x)
print(res.slack)
c = np.array([[4,8,7,15,12],[7,9,17,14,10],[6,9,12,8,7],[6,7,12,8,7],[6,9,12,10,6]])
x = cp.Variable((5,5),integer=True)
obj = cp.Minimize(cp.sum(cp.multiply(c,x)))
con = [0<=x,x<=1,cp.sum(x,axis=0,keepdims=True)==1,cp.sum(x,axis=1,keepdims=True)==1]
prob = cp.Problem(obj,con)
prob.solve(solver='GLPK_MI')
print("最优值为:",prob.value)
print("最优解为:\n",x.value)
def obj2(x):
x1,x2,x3 =x
return (2+x1)/(1+x2)-3*x1+4*x3
LB=[0.1]*3
UB=[0.9]*3
bound = tuple(zip(LB,UB))
res = minimize(obj2,np.ones(3),bounds = bound)
print(res.fun,'\n',res.success,'\n',res.x)
def chazhi():
def h(x,y,a):
s = 0.0
for i in range(len(y)):
t = y[i]
for j in range(len(y)):
if i!=j:
t*=(a-x[j])/(x[i]-x[j])
s += t
return s
from scipy.interpolate import interp1d
x = np.arange(0,25,2)
y = np.array([12,9,9,10,18,24,28,27,25,20,18,15,13])
xnew = np.linspace(0,24,500)
f1 = interp1d(x,y)
y1 = f1(xnew)
f2 = interp1d(x,y,'cubic')
y2 = f2(xnew)
plt.subplot(121)
plt.plot(xnew,y1)
plt.subplot(122)
plt.plot(xnew,y2)
plt.savefig("figure1.png",dpi=500)
plt.show()
def nihe():
def two_match(X, Y):
return np.pinv(X * X.T) * X.T * Y
y = lambda x,a,b,c:a*x**2+b*x+c
x0 = np.arange(0,1.1,0.1)
y0 = np.array([-0.447,1.978,3.28,6.16,7.08,7.34,7.66,9.56,9.48,9.30,11.2])
popt,pcov = curve_fit(y,x0,y0)
print("拟合的参数值为:",popt)
print("预测值分别为:",y(np.array([0.25,0.35]),*popt))
def duoyuan():
def get_uL(a):
n,m = a.shape
u = np.sum(a,axis = 0)/n
L = np.zeros((n,m))
for i in range(n):
L = L+(a[i,:]-u)*(a[i,:]-u).T
return u,L
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(get_uL(a))
def orthonormalization(a):
b = np.zeros(a.shape)
for i in range(len(a)):
b[i] = a[i]
for j in range(0, i):
b[i] -= np.dot(a[i], b[j]) / np.dot(b[j], b[j]) * b[j]
for i in range(len(b)):
b[i] = b[i] / np.sqrt(np.dot(b[i], b[i]))
return b
def myPCA(a, lada=0.85):
b = scale(a)
n, m = b.shape
r = np.zeros((m, m))
for i in range(m):
for j in range(m):
r[i, j] = b[:, i].T @ b[:, j] / n
e, u = LA.eig(r)
u = orthonormalization(u)
print(r, '\n', e, '\n', u)
sum = np.sum(e) * lada
x = 0
for i in range(len(e)):
x = x + e[i]
if x >= sum:
e = e[:i + 1]
u = u[:i + 1, :]
break
print(e, '\n', u, '\n')
return r, e, u
def factor_analysis(a, lada=0.85):
r, e, u = myPCA(a, lada)
e = np.sqrt(e)
print(e)
A = np.array([np.array(e[i] * u[i, :]) for i in range(len(e))]).T
d = np.diagonal(r - A @ A.T)
print(A, '\n', d)
return A, d
def lingming():
X = np.array(
[[1, 7, 26], [1, 1, 29], [1, 11, 56], [1, 11, 51], [1, 7, 52], [1, 11, 55], [1, 3, 71], [1, 1, 31], [1, 2, 54],
[1, 21, 47], [1, 1, 40], [1, 11, 66], [1, 10, 68]])
Y = np.array([78.5, 74.3, 104.3, 87.6, 95.9, 109.2, 102.7, 72.5, 93.1, 115.9, 83.8, 113.3, 109.4]).T
n, m = X.shape
def two_match(X, Y):
return LA.pinv(X.T @ X) @ X.T @ Y
b = two_match(X, Y)
y = X @ b
def xianzhuxin(X,Y,y):
def get_sse(Y, y):
return np.sum(np.multiply(Y - y, Y - y))
def get_sst(Y):
u = np.sum(Y) / n
return np.sum(np.multiply(Y - u, Y - u))
def get_ssr(Y, y):
u = np.sum(Y) / n
return np.sum(np.multiply(y - u, y - u))
sse = get_sse(Y,y)
sst = get_sst(Y)
ssr = sst-sse
ssr = get_ssr(Y,y)
F = (ssr/m)/(sse/(n-m-1))
from scipy.stats import f
alpha = 0.05
sa=f.isf(q=alpha, dfn=m, dfd=n-m-1)
return F<sa
print(xianzhuxin(X,Y,y))
def xgxs(X,Y,y):
def var(Y):
u = np.sum(Y)/n
return np.sum(np.multiply(Y-u,Y-u))
def cov(Y,y):
u = np.sum(Y)/n
return np.sum(np.multiply(Y-u,y-u))
vY = var(Y)
vy = var(y)
return cov(Y,y)/np.sqrt(vY*vy)
print(xgxs(X,Y,y))
def xgzs(X,Y,y):
def get_sse(Y, y):
return np.sum(np.multiply(Y - y, Y - y))
def get_sst(Y):
u = np.sum(Y) / n
return np.sum(np.multiply(Y - u, Y - u))
sse = get_sse(Y, y)
sst = get_sst(Y)
r = np.sqrt(1-sse/sst)
return r
print(xgzs(X,Y,y))
def xdwc(X,Y,y):
k = (Y-y)/Y
e0 = 0.6745*np.sqrt(np.sum(k*k))
return e0
print(xdwc(X,Y,y))
def lingmingdu(f,x,dx = 0.01):
y0 = []
for i in range(-100,100):
y0.append(f(x+dx*i))
x0 = [i for i in range(-100,100)]
plot(x0,y0)
def monte_carlo(f,x,v,N=10000):
N =10000
mu = x
cov = np.diag(v)
a = np.random.multivariate_normal(mu,cov,size = N)
y = np.array([f(a[i,:]) for i in range(N)])
def zhineng():
def GASA(s, cost, change, T=1, af=0.999, esp=0.1 ** 30):
while (T < esp):
c = cost(s)
s0 = change(s)
c0 = cost(s)
if c0 < c:
s = s0
else:
if math.exp(-(c0 - c) / T) >= np.random.rand(1):
s = s0
T = T * af
return s, cost(s)
def genetic(s, cost, change, G=10):
n = len(s)
for g in range(G):
s0 = change(s)
w0 = [cost(i) for i in s0]
x = np.argsort(w0)
s = s0[x[:n]]
return s[0], cost[s[0]]
if __name__ == '__main__':
lingming()
部分算法模板
import matplotlib.pyplot as plt
import pandas as pd
import math
import numpy as np
from numpy.linalg import *
from matplotlib.pyplot import *
from sklearn.preprocessing import minmax_scale,scale
def read():
data = pd.read_excel("附件.xlsx",header=None)
data = data.values
return tuple(zip(list(data[0])[1:],list(data[1])[1:]))
def plot_line_pic(x,y1,y2,x_label='时间/s',y_label={'温度/℃'},mytitle='电路板炉温曲线',label1 = '原始数据',label2 = '拟合曲线'):
rc('font',size=16)
rc('font',family='SimHei')
plot(x,y1, '--b',label = label1,linewidth=1.6, markeredgecolor='k', markersize=8)
plot(x, y2, '--r',label = label2,linewidth=1.6, markeredgecolor='k', markersize=8)
xlabel(x_label, fontweight='bold', fontsize=12)
ylabel(y_label, fontweight='bold', fontsize=12)
title(mytitle, fontweight='bold', fontsize=12)
legend()
plt.savefig('figure1.png')
show()
def savedata(x,y):
pdata = pd.DataFrame(np.vstack((np.array(x),np.array(y))).T,columns = ['时间(s)','温度(摄氏度)'])
pdata.to_csv('Result1.csv', index = 0,encoding='utf_8_sig')
def binary_search(f,eps,a,b):
c = (a+b)/2
while np.abs(f(c))>eps:
if f(a)*f(c)<0: b=c
else : a=c
c = (a+b)/2
return c
def diff(f,dx=1E-8):
return lambda x:(f(x+dx)-f(x-dx))/(2*dx)
def newton_iter(f,eps,x0,dx=1E-8):
def diff(f, dx = dx):
return lambda x: (f(x + dx) - f(x - dx)) / (2 * dx)
df = diff(f,dx)
x1 = x0-f(x0)/df(x0)
while np.abs(x1-x0)>=eps:
x1,x0 = x1 - f(x1)/df(x1),x1
return x1
def normalization1(a):
amax = np.max(a,axis=0)
amax = np.tile(amax,(a.shape[0],1))
amin = np.min(a,axis=0)
amin = np.tile(amin,(a.shape[0],1))
b = (a-amin)/(amax-amin)
b1 = minmax_scale(a)
print(amax,'\n',amin,'\n',b,'\n\n',b1)
return b
def normalization2(a):
n = a.shape[0]
u = np.sum(a,axis=0)/n
u = np.tile(u,(n,1))
s = np.sqrt(np.sum(np.multiply(a-u,a-u),axis=0)/(n-0))
s = np.tile(s,(n,1))
b = (a-u)/s
b1 = scale(a,axis=0)
print(u,'\n',s,'\n',b,'\n',b1)
return b
def check_gray11(x):
n = len(x)
jibi = x[:-1]/x[1:]
bd1 = [jibi.min(),jibi.max()]
bd2 = [np.exp(-2/(n+1)),np.exp(2/n+1)]
if bd2[0]<=bd1[0] and bd1[1]<=bd2[1]:return True
else:return False
def two_match(X, Y):
return np.linalg.pinv(X.T @ X) @ X.T @ Y
def GASA(s,cost,change,T=1,af=0.999,esp = 0.1**30):
while(T<esp):
c = cost(s)
s0 = change(s)
c0 = cost(s0)
if c0<c:
s =s0
else:
if math.exp(-(c0-c)/T)>=np.random.rand(1):
s = s0
T = T*af
return s,cost(s)
def genetic(s,cost,change,G=10):
n = len(s)
for g in range(G):
s0 = change(s)
w0 = [cost(i) for i in s0]
x = np.argsort(w0)
s = s0[x[:n]]
return s[0],cost[s[0]]
def entropy(b):
n = b.shape[0]
cs = b.sum(axis=0)
p = 1/cs*b
e = -(p*np.log(p)).sum(axis=0)/np.log(n)
g = 1-e
w = g/sum(g)
F = p@w
return F
def myPCA(a,lada=0.85):
b = scale(a)
n,m = b.shape
r = np.zeros((m,m))
for i in range(m):
for j in range(m):
r[i,j] = b[:,i].T@b[:,j]/n
e,u = eig(r)
u = orthonormalization(u)
print(r,'\n',e,'\n',u)
sum = np.sum(e)*lada
x = 0
for i in range(len(e)):
x = x+e[i]
if x>=sum:
e = e[:i+1]
u = u[:i+1,:]
break
print(e,'\n',u,'\n')
return r,e,u
def orthonormalization(a):
b = np.zeros(a.shape)
for i in range(len(a)):
b[i] = a[i]
for j in range(0, i):
b[i] -= np.dot(a[i], b[j]) / np.dot(b[j], b[j]) * b[j]
for i in range(len(b)):
b[i] = b[i] / np.sqrt(np.dot(b[i], b[i]))
return b
def factor_analysis(a,lada=0.85):
r,e,u= myPCA(a,lada)
e = np.sqrt(e)
print(e)
A = np.array([np.array(e[i]*u[i,:]) for i in range(len(e))]).T
d = np.diagonal(r-A@A.T)
print(A,'\n',d)
return A,d
if __name__ == '__main__':
a2 = np.array([[149.5,69.5,38.5],[162.5,77,55.5],[162.7,78.5,50.8],[162.2,87.5,65.5],[156.5,74.5,49.0],
[156.1,74.5,45.5],[172.0,76.5,51.0],[173.2,81.5,59.5],[159.5,74.5,43.5],[157.7,79,53.5]])
x = [1,2,3]
y1 = [1,2,3]
y2 = [3,4,5]
plot_line_pic(x,y1,y2)