scipy练习

题目来自高级编程课程的课件。


# 10.1 Least squares
from scipy.optimize import least_squares
import numpy as np

n = 5
m = 8

A = []
for i in range(n):
    temp = []
    for j in range(m):
        temp += [np.random.randint(1, 100)]
    A += [temp]

print("A:")
for i in A:
    print(i)

b = []
for j in range(n):
    b += [np.random.randint(1, 100)]

print("b:")
print(b)

x = [0, 0, 0, 0, 0, 0, 0, 0]


def func(x):
    return np.linalg.norm(np.matmul(A, x)-np.array(b))


solutions = least_squares(func, x)
print("solution:")
print(solutions.x)
print("residual:")
print(func(solutions.x))

输出:

A:
[3, 78, 35, 57, 43, 48, 97, 66]
[14, 54, 3, 67, 22, 73, 20, 10]
[45, 95, 68, 46, 38, 79, 28, 12]
[17, 17, 75, 78, 60, 76, 15, 62]
[10, 60, 42, 36, 87, 78, 17, 64]
b:
[1, 28, 40, 54, 97]
solution:
[-0.04053965  0.14680695 -0.13608394 -0.27262632  0.75309927  0.44620533
 -0.60086573  0.21903286]
residual:
1.9376753415496063e-05

import math
from scipy.optimize import fmin


def func(x):
    return 1/((math.sin(x-2))**2*math.e**(-x**2))


fmin(func, 0)

输出:

Optimization terminated successfully.
         Current function value: 1.096870
         Iterations: 20
         Function evaluations: 40

函数的最大值是1.09。


import numpy as np
from scipy.linalg import norm

n = 5
m = 8

A = []
for i in range(n):
    temp = []
    for j in range(m):
        temp += [np.random.randint(1, 100)]
    A += [temp]

print("A:")
for i in A:
    print(i)

distances = []

for i in range(n):
    temp = []
    for j in range(n):
        temp += [norm(np.subtract(A[i], A[j]))]
    distances += [temp]

print("distances:")
for i in distances:
    print(i)

输出:

A:
[57, 44, 32, 40, 50, 69, 58, 77]
[61, 78, 3, 32, 84, 66, 75, 76]
[4, 91, 41, 74, 17, 52, 7, 7]
[91, 4, 28, 49, 59, 14, 9, 41]
[1, 57, 5, 97, 99, 95, 57, 27]
distances:
[0.0, 59.430631832414505, 123.02032352420473, 98.26494797230598, 113.4063490286148]
[59.430631832414505, 0.0, 143.86104406683555, 127.27922061357856, 109.82258419833327]
[123.02032352420473, 143.86104406683555, 0.0, 142.47806848775008, 120.26221351696466]
[98.26494797230598, 127.27922061357856, 142.47806848775008, 0.0, 156.2145959889792]
[113.4063490286148, 109.82258419833327, 120.26221351696466, 156.2145959889792, 0.0]


猜你喜欢

转载自blog.csdn.net/qq_35783731/article/details/80572092