import numpy as np
from utils.features import prepare_for_training # 预处理
import torch as t
# 现在开始构建线性回归
class LinearRegression():
"""
总结一下这个函数具体做了什么事情:
1. 预处理数据
2. 得到所有的特征个数,也就是θ的个数
3. 初始化参数矩阵
"""
# 对于我们的任务,我们首先需要传入的参数是:data数据,labels标签(因为我们的任务是有监督任务)
# polynomial_degree, sinusoid_degree ???
# normalize_data=True 表示我们的数据是否需要归一化
def __init__(self, data, labels, polynomial_degree=0, sinusoid_degree=0, normalize_data=True):
# 我们需要拿到预处理的结果,三个量分别表示:
# data_processed:预处理之后的数据
# features_mean:mean值->也就是所有数据的平均值
# features_deviation:标准差
(data_processed, features_mean, features_deviation) = prepare_for_training(data, polynomial_degree=0, sinusoid_degree=0, normalize_data=True)
self.data = data_processed
self.labels = labels
self.features_mean = features_mean
self.features_deviation = features_deviation
self.polynomial_degree = polynomial_degree
self.sinusoid_degree = sinusoid_degree
self.normalize_data = normalize_data
# 现在我们针对线性回归y = w1x1 + w2x2 + ... + wmxm + b, 我们已经有了x(data),y(labels),现在我们还缺少w
# w的个数也就是我们特征的个数
num_features = self.data.shape[1] # data.shape中行表示我们的数据的个数,列表示我们特征的个数
# θ是我们最终要求解的参数值,θ的个数也就是我们的特征的个数
# 先进行初始化,使用0矩阵,同时满足矩阵格式:
self.theta = t.zeros((num_features, 1))
def train(self, step, batch_size, epoch=500):
# 接下来构建我们的训练函数(训练模块,执行梯度下降)
# step学习率
# epoch迭代次数
# 这个地方使用梯度下降不单单能得到损失值,还能更新我们的参数
cost_history = self.gd(step, epoch)
# 最终我们想要的也就是θ和损失值
return self.theta, cost_history
def gd(self, step, epoch):
# 梯度下降(总)
# 由于我们需要看损失的变化,所以每一次梯度下降我们都需要记录一次损失值,而我们的损失值,需要我们的损失函数去计算
cost_history = []
for i in range(epoch):
self.gd_step(step)
#记录每一次的迭代所得到的损失
cost_history.append(self.cost_func(self.data, self.labels))
return cost_history
def gd_step(self, step):
# 梯度下降的单个步骤(梯度下降参数更新方法,注意是矩阵的运算)
# 样本的个数
num_examples = self.data.shape[0]
# 预测值: 也就是我们的 数据×参数
prediction = LinearRegression.hypothesis(self.data, self.theta) # 此处是因为我们使用了@staticmethod装饰器,从而使我们能够直接调用hypothesis类方法
# 残差: 预测值 - 真实值
delta = prediction - self.labels
theta = self.theta
theta = theta - step*(1/num_examples)*(t.dot(delta.T, self.data)).T # 根据我们的重要重要重要公式,注意我们的残差与data之间是矩阵的乘法,同时,残差需要进行转置(具体原因见手写笔记)
# 为了调用方便我们这里使用了静态方法装饰器 ???
"""
"""
@staticmethod
def hypothesis(data, theta):
# 使用我们的x值和θ值做预测得到y的预测值
# 这里的t.dot同np.dot,向量之间就是内积,矩阵之间就是线性代数中矩阵的乘法
# 我们通过x×θ我们得到了预测值y
prediction = t.dot(data, theta)
return prediction
def cost_func(self, data, labels):
num_examples = data.shape[0]
delta = self.hypothesis(data, self.theta) - labels
# 均方差损失函数(同最小二乘法)
# 注意这里的矩阵不能直接**平方,矩阵的平方在数学中我们可以使用:矩阵的转置×矩阵本身
cost = (1/2)*t.dot(delta.T, delta)
print(cost.shape) # $$$
print(cost) # $$$
return cost[0][0] ### 注意这里是为了把合适的值选出来,需要自己去找???
# 辅助函数,得到当前的损失
def cost_get(self, data, labels):
# 数据预处理,这里我们只要prepare_for_training函数的第一个返回值,也就是我们的data_processed
data_processed = prepare_for_training(data, self.polynomial_degree, self.sinusoid_degree, self.normalize_data)[0]
# 直接得到损失值
return self.cost_func(data, labels)
# 辅助函数,用训练好的参数得到预测结果
def predict(self, data):
data_processed = prepare_for_training(data, self.polynomial_degree, self.sinusoid_degree, self.normalize_data)[0]
return LinearRegression.hypothesis(data_processed, self.theta)