gpt4 book ai didi

numpy - 使用scikit-learn LinearRegression绘制线性拟合

转载 作者:行者123 更新时间:2023-12-04 16:42:35 26 4
gpt4 key购买 nike

我正在尝试建立线性回归模型,以根据父亲的高度预测儿子的高度

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
%matplotlib inline
from sklearn.linear_model import LinearRegression


Headings_cols = ['Father', 'Son']
df = pd.read_csv('http://www.math.uah.edu/stat/data/Pearson.txt',
delim_whitespace=True, names=Headings_cols)



X = df['Father']
y = df['Son']

model2 = LinearRegression()
model2.fit(y, X)

plt.scatter(X, y,color='g')
plt.plot(X, model.predict(X),color='g')

plt.scatter(y, X, color='r')
plt.plot(y, X, color='r')

我得到错误
ValueError: could not convert string to float: 'Father'

第二件事是计算儿子的平均身长,以及均值的标准误?

最佳答案

这里有两个主要问题:

  • 从源
  • 中获取数据
  • 使数据成为 sklearn.LinearRegression.fit 理解
  • 的形状

    1.取出数据
    源文件包含带有列名称的标题行。我们不想在数据中使用列名,因此在将整个数据读入数据帧 df后,我们可以告诉它使用第一行作为标题 df.head()。这样一来,以后就可以照常按列名查询数据帧,即 df['Father']

    2.使数据变形为
    sklearn.LinearRegression.fit 有两个参数。首先是“训练数据”,它应该是一个2D数组,其次是“目标值”。在这里考虑的情况下,我们只是简单地进行拟合,因此我们不太关心这些概念,但是我们需要将对该函数的第一个输入转换为所需的形状。通过为数组之一创建新轴即可轻松完成此操作,即 df['Father'].values[:,np.newaxis]
    完整的工作样本:
    import numpy as np
    import pandas as pd
    from matplotlib import pyplot as plt
    import seaborn as sns

    from sklearn.linear_model import LinearRegression

    df = pd.read_csv('http://www.math.uah.edu/stat/data/Pearson.txt',
    delim_whitespace=True)
    df.head() # prodce a header from the first data row


    # LinearRegression will expect an array of shape (n, 1)
    # for the "Training data"
    X = df['Father'].values[:,np.newaxis]
    # target data is array of shape (n,)
    y = df['Son'].values


    model2 = LinearRegression()
    model2.fit(X, y)

    plt.scatter(X, y,color='g')
    plt.plot(X, model2.predict(X),color='k')

    plt.show()

    enter image description here

    关于numpy - 使用scikit-learn LinearRegression绘制线性拟合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40941542/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com