第十二周作业 11 Matplotlib

Exercise 11.1: Plotting a function

Plot the functionf(x) = sin^2 (x − 2) e ^(−x2) over the interval [0,2]. Add proper axis labels, a title, etc.

import numpy as np
from matplotlib import pyplot as plt

# 11.1
x = np.linspace(0, 2, 100)
y = np.power(np.sin(x - 1), 2) * np.exp(-np.power(x, 2))

plt.plot(x, y)
plt.title('Exercise 11.1: Plotting a function', fontsize = 24)
plt.xlabel('x', fontsize = 14)
plt.ylabel('f(x)', fontsize = 14)
plt.tick_params(axis = 'both', labelsize = 14)

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

                                                                            b^ = arg min(b) || Xb − y || 2

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

import numpy as np
import matplotlib.pyplot as plt
from numpy import random as rd
from numpy import linalg as lna


X = rd.randn(20, 10)
b = rd.randn(10, 1)
z = rd.randn(20, 1)
y = np.dot(X, b) + z
b_ = np.dot(np.dot(lna.inv(np.dot(X.T, X)), X.T), y)


x = np.linspace(0, 9, 10)


plt.scatter(x, b, c = 'blue', label = 'origin b')
plt.scatter(x, b_, c = 'red', label = 'estimated b^')
plt.title('Exercise 11.2: Data')
plt.xlabel('x')
plt.ylabel('value')
plt.legend()
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 numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
from numpy import random as rd


z = rd.normal(200, 100, 1000)
k = gaussian_kde(z)
x = np.linspace(-200, 600, 1000)
plt.hist(z, bins = 25, rwidth = 0.5, color = 'blue', density = True)
plt.plot(x, k.evaluate(x), c = 'red')
plt.title('Exercise 11.3: Histogram and density estimation')
plt.xlabel('x')
plt.ylabel('y')
plt.show()


                                   

猜你喜欢

转载自blog.csdn.net/guo_lx/article/details/80640717