虽然这是一个非常简单的概念,但本书还是提供了一个Python代码示例。在这个示例中,我们将创建样本集,并用线图表示它,将整个集合的平均值标记为线,这条线应该位于样本的加权中心。它既可以作为Python语法的引见,也可以当作Jupyter Notebook的实验。代码如下。
import matplotlib.pyplot as plt #Import the plot librarydef mean(sampleset): #Definition header for the mean function total=0 for element in sampleset: total=total+element return total/len(sampleset)myset=[2.,10.,3.,6.,4.,6.,10.] #We create the data setmymean=mean(myset) #Call the mean funcionplt.plot(myset) #Plot the datasetplt.plot([mymean] * 7) #Plot a line of 7 points located on the mean
该程序将输入数据集元素的工夫序列,然后在平均高度上绘制一条线。
下面采用以前运用的库,编写示例代码来阐明这个概念。为了清楚起见,这里反复mean函数的声明。代码如下。
import math #This library is needed for the power operationdef mean(sampleset): #Definition header for the mean function total=0 for element in sampleset: total=total+element return total/len(sampleset)def variance(sampleset): #Definition header for the mean function total=0 setmean=mean(sampleset) for element in sampleset: total=total+(math.pow(element-setmean,2)) return total/len(sampleset)myset1=[2.,10.,3.,6.,4.,6.,10.] #We create the data setmyset2=[1.,-100.,15.,-100.,21.]print "Variance of first set:" + str(variance(myset1))print "Variance of second set:" + str(variance(myset2))
后面的代码将输入以下结果。
Variance of first set:8.69387755102Variance of second set:3070.64
正如下面的结果所示,当样本值非常分散时,第二组的方差要高得多。由于计算间隔平方的均值是一个二次运算,它有助于表示出它们之间的差异。