sklearn对父母子女身高数据集做线性分析

一、实验说明

实验环境

Anaconda + python3.6 + jupyter

实验说明

分别对 “父亲-儿子” 和 “母亲-儿子” 的身高数据做线性分析

数据集和源码

链接:https://pan.baidu.com/s/1qVCv03xuWp9OtIGmCGKmTA
提取码:b3mb

二、数据预处理

原始数据格式如下:

在这里插入图片描述

第一步,用excel筛选出子女性别为M的数据。

第二步,去掉家庭编号重复的数据。

结果如下:

在这里插入图片描述

三、sklearn 线性回归

1. “父亲-儿子” 线性回归分析

① 导入数据

import csv
import numpy as np
father = [] # 存放父亲身高
mother = [] # 存放母亲身高
son = [] # 存放儿子身高
# 数据读取
with open("Pretreatment.csv", 'r') as file:
    reader = csv.reader(file, dialect='excel')
    i = 0
    for row in reader:
        # 去掉第一行数据
        if i == 0:
            i = 1
            continue
        father.append(float(row[1]))
        mother.append(float(row[2]))
        son.append(float(row[4]))
x_father = np.array(father).reshape(-1, 1)
x_mother = np.array(mother).reshape(-1, 1)
y_son = np.array(son).reshape(-1, 1)

② sklearn 线性回归分析

from sklearn import linear_model
#创建线性回归对象
linear_regressor = linear_model.LinearRegression()
#用训练数据集训练模型,向fit方法中提供输入数据即可
linear_regressor.fit(x_father,y_son)

③ 绘图

import matplotlib.pyplot as plt
# 绘制散点
plt.figure("Linear Regression", facecolor="lightgray")
plt.title("Linear Regression", fontsize=16)
plt.grid(linestyle=":")
plt.scatter(x_father, y_son, s=70, color="dodgerblue", label="samples")
# 绘制拟合直线
prd_y = linear_regressor.predict(x_father)
plt.plot(x_father, prd_y, color="orangered", label="Predict")
plt.legend()
plt.tight_layout()
plt.show()

在这里插入图片描述

④ R-square(决定系数)

import sklearn.metrics as sm
print("权重:",linear_regressor.coef_)
print("截距:",linear_regressor.intercept_)
print("R2得分:", sm.r2_score(y_son, prd_y))

在这里插入图片描述

一些常用的评价指标具体可参考:回归——回归预测的评价指标

2. “母亲-儿子” 线性回归分析

步骤与上述步骤一致

linear_regressor.fit(x_mother,y_son)

# 绘制散点
plt.figure("Linear Regression", facecolor="lightgray")
plt.title("Linear Regression", fontsize=16)
plt.grid(linestyle=":")
plt.scatter(x_mother, y_son, s=70, color="dodgerblue", label="samples")
# 绘制拟合直线
prd_y = linear_regressor.predict(x_mother)
plt.plot(x_mother, prd_y, color="orangered", label="Predict")
plt.legend()
plt.tight_layout()
plt.show()
print("权重:",linear_regressor.coef_)
print("截距:",linear_regressor.intercept_)
print("R2得分:", sm.r2_score(y_son, prd_y))

在这里插入图片描述

四、参考🔗

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值