import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
for_mat = 'Advertising.csv'
advertising = pd.read_csv(for_mat)
advertising.head()
"""定义打印散点图函数plt_show()"""
def plt_show():
"""分别以三个变量为横轴,绘制散点图"""
plt.scatter("TV", "sales", data=advertising, label="TV", marker="D")
plt.scatter("radio", "sales", data=advertising, marker="o", label="radio")
plt.scatter("newspaper", "sales", data=advertising, marker="s", label="newspaper")
"""为图片增加图例,参数loc用于设置图例位置"""
plt.legend(loc="lower right")
plt.xlabel("Advertising Budgets", fontsize=16)
plt.ylabel("Sales", fontsize=16)
plt.show()
"""线性回归模型的预测函数linear_model()"""
def linear_model(input_i, weight, b):
prediction = np.sum(input_i * weight) + b
return prediction
# plt_show() #调用绘制散点图函数
b = 10
w = np.array([0.1, 0.1, 0.1]) # 给定自变量权重
def observe():
input_0 = advertising.values[0][0:3] # 获取输入
print("从第一个观测点的自变量向量为" + str(input_0))
# 使用线性回归模型得到input_0的预测值
pred = linear_model(input_0, w, b)
print("第一个观测点的预测值为" + str(pred))
"""
从数据advertising中得到第一行第四列的因变量target(sales)
并计算残差平方
"""
target = advertising.values[0][3]
loss = (pred - target) ** 2
print("残差平方为" + str(loss))
# observe() #调用第一个数据观测函数
"""
计算广告残差平方和
损失函数为 RSS(b,w)
"""
def rs_s():
rss = 0
for i in range(len(advertising)):
input_1 = advertising.values[i][0:3]
pred = linear_model(input_1, w, b)
target = advertising.values[0][3]
rss += (pred - target) ** 2 / 2 / len(advertising)
print(rss)
# rs_s() # 调用残差平方和计算函数
3.1.1线性回归模型简介
于 2023-04-23 23:06:33 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)