Scipy

Scipy Exercises

这里写图片描述
这里写图片描述

Exercise 10.1: Least squares

import numpy as np
import scipy.optimize as opt

m = 10
n = 5
num = 20

A = np.random.randint(-num, num, size = m * n).reshape(m, n)
b = np.random.randint(-num, num, size = m * 1).reshape(m, 1)

# Least squares, solve (A.T)Ax = (A.T)b
x = np.dot(np.dot(np.linalg.inv(np.dot(A.T, A)), A.T), b)

# Compute the norm of the residual
print ("The norm of the residual:", np.linalg.norm(x))

Result of Exercise 10.1

这里写图片描述

Exercise 10.2: Optimization

import numpy as np
import scipy.optimize as opt

def f(x):
    """Compute f(x) = -sin^2(x - 2)exp(-x^2)"""
    return -np.power(np.sin(x - 2), 2) * np.exp(-np.power(x, 2))

print ("f(x) = -sin^2(x - 2)exp(-x^2)")

# find maximum by minimum of -f(x)
max = -opt.minimize_scalar(f).fun

print ("maximum of f(x):", max)
print ("when x =", opt.minimize_scalar(f).x)

Result of Exercise 10.2

这里写图片描述

Exercise 10.3: Pairwise distances

import numpy as np
from scipy.spatial import distance

n = 5
m = 5
num = 20

# Generate matrix X with 5 rows and 5 cols
X = np.random.randint(-num, num, size = n * m).reshape(n, m)

print ("Matrix X")
print (X)

for i in range(0, n):
    for j in range(i + 1, n):
        print ("The distance between row", i + 1, "and row", j + 1, "is ", end = "")
        print (distance.cityblock(X[i], X[j]))

Result of Exercise 10.3

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值