线性回归模型案例:广告投放效果预测

一、数据集说明:

Advertising 数据集: https://www.kaggle.com/datasets/tawfikelmetwally/advertising-dataset.

ID:序号

TV:电视广告投放金额,单位千元

Radio:广播广告投放金额,单位千元

Newspaper:报纸广告投放金额,单位千元

Sales:销售额,单位百万元

二、代码实现

复制代码
import pandas as pd
from sklearn.preprocessing import StandardScaler # 标准化
from sklearn.model_selection import train_test_split # 划分数据集
from sklearn.linear_model import LinearRegression, SGDRegressor # 线性
回归-正规方程,线性回归-随机梯度下降
from sklearn.metrics import mean_squared_error # 均方误差

# 加载数据集
advertising = pd.read_csv("data/advertising.csv")
advertising.drop(advertising.columns[0], axis=1, inplace=True)
advertising.dropna(inplace=True)
advertising.info()
print(advertising.head())

# 划分训练集与测试集
X = advertising.drop("Sales", axis=1)
y = advertising["Sales"]
x_train, x_test, y_train, y_test = train_test_split(X, y,
test_size=0.3, random_state=0)

# 标准化
preprocessor = StandardScaler()
x_train = preprocessor.fit_transform(x_train) # 计算训练集的均值和标准差,并标准化训练集
x_test = preprocessor.transform(x_test) # 使用训练集的均值和标准差对测试集标准化

# 使用正规方程法拟合线性回归模型
normal_equation = LinearRegression()
normal_equation.fit(x_train, y_train)
print("正规方程法解得模型系数:", normal_equation.coef_)
print("正规方程法解得模型偏置:", normal_equation.intercept_)

# 使用随机梯度下降法拟合线性回归模型
gradient_descent = SGDRegressor()
gradient_descent.fit(x_train, y_train)
print("随机梯度下降法解得模型系数:", gradient_descent.coef_)
print("随机梯度下降法解得模型偏置:", gradient_descent.intercept_)

# 使用均方误差评估模型
print("正规方程法均方误差:", mean_squared_error(y_test,
normal_equation.predict(x_test)))
print("随机梯度下降法均方误差:", mean_squared_error(y_test,
gradient_descent.predict(x_test))
相关推荐
汉克老师9 小时前
GESP6级C++考试语法知识(二十七、广度优先搜索(二、二维BFS))
c++·算法·图论·宽度优先·广度优先搜索·gesp6级·gesp六级
此生决int9 小时前
算法从入门到精通——位运算
数据结构·c++·算法·蓝桥杯
春栀怡铃声9 小时前
【C++修仙录02】筑基篇:vector 使用
开发语言·c++·算法
Loli_Wolf9 小时前
AI 原生研发闭环:从提需到线上监测,再自动回到提需
人工智能·深度学习·算法·microsoft·ai·ai编程·harness
计算机安禾9 小时前
【算法分析与设计】第4篇:分治策略的理论框架与经典案例
数据结构·算法·排序算法
Kiling_07049 小时前
面向对象和集合编程题 ( 二 )
java·开发语言·数据结构·算法
过期动态9 小时前
【LeetCode 热题 100】两数之和— 暴力法与哈希表法详解
java·数据结构·算法·leetcode·散列表
葫三生9 小时前
开源社区为《论三生原理》系列提供“第二评价体系”?
人工智能·科技·深度学习·算法·机器学习·开源
故事和你919 小时前
洛谷-【动态规划1】动态规划的引入4
开发语言·数据结构·c++·算法·动态规划·图论
用户938515635079 小时前
移除数组里的指定元素,你学会了吗?
javascript·算法