高级编程技术第十次作业

Exercise 11.1: Plotting a function

    Plot the function

                                F(x)=sin2(x-2)e-x^2 

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

在区间[0,2]画出f(x)并加上适合的轴标签,题目等信息。

代码如下

from numpy import *
from matplotlib.pyplot import *
import math
x=linspace(0,2)
y=[(sin(num-2)**2)*exp(-num**2) for num in x]
plot(x,y)
title('Plotting a function')
xlabel('x')
ylabel('f(x)')
text(1,0.6,'f(x)=sin^2(x−2)*e^(−x^2)')
show()

画图像的话先设置好x,y,再plot(x,y)设置标题,轴标签,等内容可以用title,xlabel,ylabel等函数完成,而

text(x0,y0,mes)则是在(x0,y0)处打印一条信息mes。最后一起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^=argminb||Xb-y||2

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

pdf中的Figure1 除了在exercise 11.1中的方法还多了一个标注的信息。

代码如下

from numpy import *
from matplotlib.pyplot import *
import math
X=random.rand(20,10)
b=random.rand(10,1)
z=random.normal(size=20).reshape(20,1)
print(b)
y=dot(X,b)+z
est_b=dot(dot(linalg.inv(dot(X.T,X)),X.T),y)
plot(b,'rx',est_b,'bo')
legend(labels=['True coefficients','Estimate coefficients'],loc=1)
xlabel('index')
ylabel('value')
show()
矩阵的随机生成,乘法,操作在上一次作业已经做出来,这里的^b可以用法方程方法解决最小二乘问题,而注释标注可以用legend的方法做出来,依次对应前面的rx,bo,红色x,蓝色o,后面的loc 可以自己调节图例的位置 loc=1 在右上角 =2左上角 =3 左下角 =4 右下角 一般 =‘best’ 自动调整,这里用1是为了达到pdf中的效果,标注在右上角。

截图如下:



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.

从你最喜欢的奇异分布中生成10000个矢量Z。绘制一个Z(25个bins)的直方图,然后用一个高斯核密度估计器(参见SimP.Stas)完成密度的估计。参见图2

代码如下:

from numpy import *
from matplotlib.pyplot import *
from scipy.stats import *
import math
z=sorted(random.randn(10000))
kernel= gaussian_kde(z)
hist(z,25,normed=True)
plot(z,kernel.pdf(z))
show()
生成奇异分布可以用numpy下的random的randn方法。高斯核密度估计器用scipy.stats下的gaussian_kde方法。最后画直方图用hist方法,要设normed=true,而连线要用plot方法。

截图如下:


猜你喜欢

转载自blog.csdn.net/liangjan/article/details/80487233
今日推荐