题目
Exercise 10.1: Least squares
Generate matrix A 2 Rmn with m > n. Also generate some vector b 2 Rm.
Now nd x = arg minx kAx �� bk2.
Print the norm of the residual.
Exercise 10.2: Optimization
Find the maximum of the function
f(x) = sin2(x �� 2)e��x2
CME 193 Introduction to Python Exercises
0 1 2 3 4 5 6 7 8 9
index
1.5
1.0
0.5
0.0
0.5
1.0
1.5
value
Exercise 10.3: Pairwise distances
Let X be a matrix with n rows and m columns. How can you compute the pairwise distances between
every two rows?
As an example application, consider n cities, and we are given their coordinates in two columns. Now
we want a nice table that tells us for each two cities, how far they are apart.
Again, make sure you make use of Scipy's functionality instead of writing your own routine.
题解
大致就是去找寻符合要求的函数。
# -*- coding: utf-8 -*-
import numpy as np
import scipy.linalg as sl
import scipy.optimize as so
import scipy.spatial.distance as dist
""" #1 """
A=np.random.normal(size=(100,30))
b=np.random.normal(size=100)
residual = sl.lstsq(A,b)[1]
print(residual,'\n')
""" #2 """
# use scipy.optimize.fmin
def f(x):
return -(np.sin(x-2)**2)*np.exp(-x**2)
max_x = so.fmin(lambda x : f(x),0,disp = False)
#max_x is an array.
print("Min_Point:",max_x[0],"Min_Value:",-f(max_x[0]),'\n')
""" #3 """
A = np.random.normal(size=(5,80))
C = dist.squareform(dist.pdist(A))
print(C)
运行结果
runfile('D:/OneDrive/Python Assignments/scipy_assignment.py', wdir='D:/OneDrive/Python Assignments')
43.1463773659
Min_Point: 0.21625 Min_Value: 0.911685411707
[[ 0. 12.67912292 12.31555536 12.15211374 12.24139044]
[ 12.67912292 0. 13.30742745 10.61905634 11.15010282]
[ 12.31555536 13.30742745 0. 12.08012517 11.72051934]
[ 12.15211374 10.61905634 12.08012517 0. 11.36012397]
[ 12.24139044 11.15010282 11.72051934 11.36012397 0. ]]