欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Matplotlib 课后练习

程序员文章站 2022-03-10 15:35:25
...
Exercise 11.1: Plotting a function
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()

Matplotlib 课后练习

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
Matplotlib 课后练习

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()
Matplotlib 课后练习
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()


Matplotlib 课后练习