Matplotlib 课后练习

本文通过三个实例展示了如何使用Matplotlib进行数据可视化,包括绘制函数图像、对比真实与估计参数以及生成直方图和密度估计。每个实例都涵盖了从数据生成到图形展示的完整过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Exercise 11.1: Plotting a function
Plot the function
f ( x ) = sin 2 ( x - 2) e - x 2

over the interval [0; 2]. Add proper axis labels, a title, etc.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0,2,200)
y = np.square(np.sin((x - 2) * np.e**(-x ** 2)))

plt.plot(x, y)
plt.show()

Exercise 11.2: Data

Create a data matrix X with 20 observations of 10 variables. Generate a vector b with parameters Then
generate the response vector
y = Xb + z where z is a vector with standard normally distributed variables.
Now (by only using y and X), find an estimator for
b , by solving

Plot the true parameters b and estimated parameters ^b. See Figure 1 for an example plot.

import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt  

def min(b, X, y):        
    return np.linalg.norm(np.dot(X, np.reshape(b, (10, 1))) - y, ord = 2) 

observations = 20
variables = 10

X = np.random.randint(1, 4, (observations, variables)).reshape(observations, variables)
b = np.random.randint(-3, 3, (variables, 1))
z = np.random.normal(0, 1, observations).reshape(observations, 1)
y = X.dot(b) + z
  
t = opt.minimize(min, np.zeros((10, 1)), args=(X, y))  
b_ = t.x  

range = np.linspace(0, 9, 10)  
true = plt.scatter(range, b, marker='o', c = (0,0,1))    
esti = plt.scatter(range, b_, marker='x', c = (1,0,0)) 

plt.xlabel('index')  
plt.ylabel('value')  
plt.legend([true, esti], ['True coefficents', 'Estimated parameters'])
plt.show()

Exercise 11.3: Histogram and density estimation
Generate a vector z of 10000 observations from your favorite exotic distribution. Then make a plot that
shows a histogram of
z (with 25 bins), along with an estimate for the density, using a Gaussian kernel

density estimator (see scipy.stats). See Figure 2 for an example plot.

import matplotlib.pyplot as plt
import numpy as np
from scipy import stats

A = np.random.normal(0, 100, 10000)
plt.hist(A, 25, normed = 1, edgecolor = 'black')
x = np.linspace(-400, 400, 10000)
y = stats.gaussian_kde(A).pdf(x)
plt.plot(x, y)  
plt.show()



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值