Python习题——2018-05-23作业

Matplotlib 练习题

Exercise 11.1: Plotting a function
  Plot the function

f ( x ) = s i n 2 ( x 2 ) e x 2

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_style("darkgrid")

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


plt.xlim((0, 2))
plt.ylim((0, 1))
plt.xlabel('x label')
plt.ylabel('y label')
plt.title('$f(x)=sin^2(x-2)e^{-x^2}$')

plt.plot(x, y)
plt.savefig("Figure_1.png")
plt.show()

Output:

Figure_1.png

 
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 = X b + 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 X b 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 scipy.optimize import leastsq


def error(b, X, y):
    '''返回误差'''
    result = np.ravel(X @ b - y)
    return result


x = np.linspace(0, 9, 10)
X = np.random.random((20, 10))
b = np.random.random((10, 1))
z = np.random.normal(loc=0, scale=1, size=(20,1))

y = X @ b + z

b_ = np.random.random((10, 1))
b_ = leastsq(error, b_, args=(X,y))[0]

plt.plot(x, b,  '.', label='True coefficients')
plt.plot(x, b_, 'x', label='Estimated coefficients')
plt.xlim((0, 9))
plt.ylim((-1.5, 1.5))
plt.xlabel('index')
plt.ylabel('value')
plt.legend()

plt.savefig("Figure_2.png")
plt.show()

Output:

Figure_2.png

 
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.

扫描二维码关注公众号,回复: 3329142 查看本文章
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
import seaborn as sns

sns.set_style("darkgrid")

z = np.random.random(size=10000)
kde = gaussian_kde(z)
x = np.linspace(0, 0.9999, 10000)
plt.xlim((0, 1))
plt.hist(z, bins=25, normed=True, color='b')
plt.plot(x, kde(x), 'r-')
plt.savefig('Figure_3.png')
plt.show()

Output:

Figure_3.png

猜你喜欢

转载自blog.csdn.net/Draymond_666/article/details/80437997