Python 实战 SciPy作业

题目

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.        ]]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值