作业——Matplotlib

本文通过三个练习介绍了如何使用Matplotlib进行函数绘制、数据拟合参数估计及直方图与密度估计的实现。首先展示了如何绘制特定数学函数,并添加坐标轴标签和标题;接着演示了如何创建数据矩阵并估计未知参数;最后通过生成随机数据来制作直方图并估计其概率密度。

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

Matplotlib

Exercise 11.1: Plotting a function
Plot the function
        f(x) = [sin(x -2)]^2 *exp(-x)^2

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

x = np.arange(-5, 5, 0.1)
y = (np.sin(x-2)**2)*np.exp(-(x**2))
plt.xlabel('x')
plt.ylabel('f(x)')
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), nd an estimator for b, by solving
                            ^b = arg min ||Xb-y||2
Plot the true parameters b and estimated parameters ^b
def my_argmin(b0, X, y):
    b0 = np.reshape(b0, (10, 1))
    return np.linalg.norm(np.dot(X, b0) - y, ord=2)

#np.random.seed()
X = np.random.randint(-3, 3, (20, 10))
a = np.random.randint(-3, 3, (10, 1))
z = np.random.randn(20, 1)
y = np.dot(X, a) - z
y = np.array(y)

r = optimize.minimize(my_argmin, np.transpose(a), args=(X, y))
x = [0,1,2,3,4,5,6,7,8,9]

sca1 = plt.scatter(x, a, s = 10)
sca2 = plt.scatter(x, r.x, s = 10)
plt.xlabel('index')
plt.ylabel('value')
plt.axis([0, 10, -3, 3])
plt.title('Data')
plt.legend([sca1, sca2], ['True coefficents', 'Estimated coefficients'])
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).

data = stats.norm.rvs(loc = 1, scale = 0.3, size = 10000)
plt.hist(data, bins = 25, normed = 1, edgecolor = 'black', color = 'blue')
sns.kdeplot(data, color = 'red')
plt.show()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值