import numpy as np
from scipy.optimize import leastsq
m = 20
n = 12
A = np.random.randint(1, 100, size = (m , n))
b = np.random.randint(1, 100, size = (m, 1))
x0 = np.random.randint(1, 100, size = (1, n))
A = np.mat(A)
b = np.mat(b)
def func(x):
x = x.reshape(n , 1)
x = np.mat(x)
r = A * x - b
r = np.array(r)
return np.array(r.T).reshape(m)
l = leastsq(func, x0)
x = l[0].reshape(n, 1)
print('x = ', x)
print('residal = ', A * np.mat(x) - b)
print('norm = ', np.linalg.norm(A * np.mat(x) - b))
运行
x = [[ 0.80420686]
[ 0.62469073]
[-0.19798721]
[-0.24153484]
[-0.09265393]
[ 0.76398557]
[ 0.22034202]
[-0.17669824]
[ 0.04719834]
[-0.06067864]
[-0.64575209]
[ 0.19693909]]
residal = [[ -3.33044561]
[ 9.29616319]
[ 11.38514723]
[-22.06835924]
[ 5.98869136]
[ 11.43222131]
[-20.964829 ]
[ 9.52452761]
[ 10.66786616]
[-15.4983632 ]
[-13.98776675]
[ 13.83945544]
[-30.41646446]
[ 15.19362674]
[ 6.14056642]
[ 3.24390932]
[-13.7308669 ]
[ 21.8667791 ]
[-19.56388707]
[ 8.93166629]]
norm = 66.97451994397635
------------------
(program exited with code: 0)
请按任意键继续. . .
求函数f(x)的最大值
import numpy as np
import math
import scipy.optimize as sc
f = lambda x : -math.pow( math.sin(x-2), 2) * math.pow(math.e , -x*x)
b = sc.minimize(f, 0)
print('在 x = ' , b.x[0], ' 处有最大值 ', -b.fun)
在函数前加上一个负号后求的最小值的相反数就是原函数的最大值。
运行结果
在 x = 0.21624131913960304 处有最大值 0.9116854118471545

import numpy as np
from scipy.spatial.distance import pdist
n = 5
m = 4
X = []
for i in range(1, m + 1):
x = [i for y in range(n)]
X.append(x)
X = np.array(X)
print(X)
d = pdist(X, metric = 'euclidean')
count = 0
for i in range(1, m):
for j in range(i + 1, m+1):
print(X[i-1],' and ',X[j-1], ' distance = ', d[count])
count += 1
运行结果
[[1 1 1 1 1]
[2 2 2 2 2]
[3 3 3 3 3]
[4 4 4 4 4]]
[1 1 1 1 1] and [2 2 2 2 2] distance = 2.23606797749979
[1 1 1 1 1] and [3 3 3 3 3] distance = 4.47213595499958
[1 1 1 1 1] and [4 4 4 4 4] distance = 6.708203932499369
[2 2 2 2 2] and [3 3 3 3 3] distance = 2.23606797749979
[2 2 2 2 2] and [4 4 4 4 4] distance = 4.47213595499958
[3 3 3 3 3] and [4 4 4 4 4] distance = 2.23606797749979
------------------
(program exited with code: 0)
请按任意键继续. . .