Python 对Anscombe四组数据的分析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_36326096/article/details/80679244

Part 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+ϵ

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")

anascombe = pd.read_csv('anscombe.csv')

#计算x和y的均值和方差
x_avg = anascombe['x'].mean()
y_avg = anascombe['y'].mean()
x_var = anascombe['x'].var()
y_var = anascombe['y'].var()

print('Average of x =', x_avg)  
print('Average of y =', y_avg)  
print('Variance of x =', x_var)  
print('Variance of y =', y_var)  

#计算x和y的相关系数
corr = anascombe['x'].corr(anascombe['y'])  
print('Correlation coefficient between x and y =', corr)

#计算线性回归
X = sm.add_constant(anascombe['x'])
est = sm.OLS(anascombe['y'], X)
est = est.fit()
print('y = %.3f + %.3fx + ϵ'%(est.params[0], est.params[1])) 

运行结果:
这里写图片描述

Part 2

Using Seaborn, visualize all four datasets.

hint: use sns.FacetGrid combined with plt.scatter

代码:

#数据可视化
sns.FacetGrid(data = anascombe, col = 'dataset', col_wrap = 2).map(plt.scatter, 'x', 'y')  
plt.show()  

运行结果:
这里写图片描述

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页