Matplotlib 课后练习
程序员文章站
2022-03-10 15:35:25
...
Exercise 11.1: Plotting a function
Plot the function
f(x) = sin2(x - 2)e-x2
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
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
Plot the function
f(x) = sin2(x - 2)e-x2
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 Thengenerate 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()
上一篇: centos安装mysql5.6
推荐阅读
-
Python利用matplotlib.pyplot绘图时如何设置坐标轴刻度
-
使用python 的matplotlib 画轨道实例
-
使用matplotlib可视化点云分割结果
-
Python用pandas和matplotlib分析1949-2016年中国各省市历年GDP数据
-
Mac python matplotlib Glyph xxxxx missing from current font的解决方案
-
python的绘图工具matplotlib使用实例
-
python绘图库Matplotlib的安装
-
使用pandas模块读取csv文件和excel表格,并用matplotlib画图的方法
-
机器学习之matplotlib实例笔记
-
Python Matplotlib库安装与基本作图示例