第十四周作业——jupyter

题目来源:

https://nbviewer.jupyter.org/github/schmit/cme193-ipython-notebooks-lecture/blob/master/Exercises.ipynb

1.

For each of the four datasets...

  • Compute the mean and variance of both x and y
  • Compute the correlation coefficient between x and y
  • Compute the linear regression line: y=β0+β1x+ϵy=β0+β1x+ϵ (hint: use statsmodels and look at the Statsmodels notebook)

import random
import numpy as np
import scipy as sp
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import statsmodels.api as sm
import statsmodels.formula.api as smf
sns.set_context("talk")

import math

xdata=[10,8,13,9,11]

ydata=[8.04,6.95,7.58,8.81,8.33]

xm=(10+8+13+9+11)/5
ym=(8.04+6.95+7.58+8.81+8.33)/5
xv=(pow((10-xm),2)+pow((8-xm),2)+pow((13-xm),2)+pow((9-xm),2)+pow((11-xm),2))/5
yv=(pow((8.04-ym),2)+pow((6.95-ym),2)+pow((7.58-ym),2)+pow((8.81-ym),2)+pow((8.33-ym),2))/5
c=10*8.04+8*6.95+13*7.58+9*8.81+11*8.33-xm*ym/pow(xv*yv,0.5)
b=(10-xm)*(8.04-ym)+(8-xm)*(6.95-ym)+(13-xm)*(7.58-ym)+(9-xm)*(8.81-ym)+(11-xm)*(8.33-ym)/pow(xv*5,0.5)*pow(yv*5,0.5)
a=ym-b*xm

print(" x mean:",xm,'\n',"y mean:",ym,'\n',"x variance:",xv,'\n',"y variance:",yv,'\n',"correlation coefficient",c,'\n',"linear regression line:y=",b,'x+',a)

执行结果:

第十四周作业——jupyter

2.

Using Seaborn, visualize all four datasets.

hint: use sns.FacetGrid combined with plt.scatter

画平均数、方差和相关系数的函数,在第一题上补充:

plt.plot(xm,ym,'k.')
plt.plot(xm,c,'k.') 
x = 10
y = b*x+a
plt.scatter(xdata,ydata)
plt.plot(x,y,'k.')

plt.show()

画线性回归图的函数:

import random
import numpy as np
import scipy as sp
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import statsmodels.api as sm
import statsmodels.formula.api as smf
import warnings
warnings.filterwarnings("ignore")
sns.set_context("talk")
df=pd.read_csv("data.csv") 
df.head()
sns.jointplot(x="x", y="y", data=df, kind='reg', size=6)#试了sns.FacetGrid()和plt.scatter()但效果不好
plt.show()

画平均数、方差和相关系数:

第十四周作业——jupyter

画线性回归图:

第十四周作业——jupyter

心得:花了很长时间进行python的配置,下了很多whl文件,充分锻炼了我的动手能力,开阔了我的眼见,相信今后能学得更好。