(Week 12)Python-Matplotlib_exercises

本文通过实例演示了如何使用Python进行函数绘图、最小二乘法求解参数估计及密度估计。具体包括正弦平方指数函数的绘制、通过随机生成的数据集估算参数,并对比真实值,最后展示了如何对大量数据进行密度估计。

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

Exercise 11.1: Plotting a function

Plot the function y=sin2(x2)ex2y=sin2(x−2)e−x2 over the interval [0, 2]. Add proper axis labels, a title, etc.

编写代码如下:

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(color_codes=True)   #show grid

def plot_a_fun():
    x = np.linspace(0, 2, 100)
    print(x)
    y1 = np.sin(x - 2) ** 2     
    y2 = np.exp(-(x ** 2))
    y = y1 * y2             #get y value
    plt.plot(x, y, label='$y=sin^2(x-2)e^{-x^2}$')
    plt.xlabel('x axis')
    plt.ylabel('y axis')
    plt.legend()            #show legend
    plt.show()

plot_a_fun()

运行结果如下:

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+zy=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

b^=argminb||Xby||2b^=argminb⁡||Xb−y||2

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

编写代码如下:

def least_square():
    X = np.random.random((20, 10)) * 10         #create X, b, z
    b = np.random.random(10) * 6 - 3
    z = np.random.randn(20)
    y = X.dot(b) + z                           #create y    
    b1 = np.linalg.lstsq(X, y, rcond=-1)[0]      #get least square solution of Xb = y
    index = np.linspace(0, 9, 10)               
    plt.plot(index, b, 'r*', label="True coefficients")
    plt.plot(index, b1, 'bo', label='Estimated coefficients')
    plt.hlines(0, 0, 9, colors='k', linestyles='solid') #show middle line
    plt.tight_layout()
    plt.legend()
    plt.savefig('p2.png')
    plt.show()

least_square()

运行结果如下:

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.

编写代码如下:

def density_estimation():
    x = np.random.normal(60, 10, 10000)
    sns.distplot(x, bins=25, kde=True)  #kde=True -- using Gaussian kernel density estimator
    plt.savefig('p3.png')
    plt.show()

density_estimation()

运行结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值