导入库

import numpy as np import pandas as pd from sklearn.linear_model import LinearRegression

创建数据集

data = {'advertising': [100, 200, 300, 400, 500], 'sales': [2000, 4000, 6000, 8000, 10000]} df = pd.DataFrame(data)

确定X和y

X = df[['advertising']] y = df['sales']

拟合线性模型

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

打印回归系数和截距

print('Coefficient:', model.coef_) print('Intercept:', model.intercept_)

主要参数说明:

  • fit_intercept: 布尔型,默认为 True。若参数值为 True 时,代表训练模型需要加一个截距项;若参数为 False 时,代表模型无需截距。
  • normalize: 布尔型,默认为 False。若 fit_intercept 参数设置为 False 时,normalize 参数无需设置。
    • 若 normalize 设置为 True 时,则输入的样本数据将被标准化处理((X - 均值) / X 的标准差)。
    • 若设置 normalize = False 时,在训练模型前,可以使用 sklearn.preprocessing.StandardScaler 进行标准化处理。
  • copy_X: 一个布尔值。如果为 True,则会拷贝 X。
  • n_jobs: 一个正数,指定任务并行时指定的 CPU 数量。如果为 -1 则使用所有可用的 CPU 核心。

属性:

  • coef_: 回归系数(斜率)
  • intercept_: 截距项
Python 线性回归实战:广告费用与销售收入预测

原文地址: https://www.cveoy.top/t/topic/echY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录