【机器学习实战】四、实现线性回归模型案例

news2024/10/6 4:01:13

线性回归案例

一、初始化方法

1.对数据进行预处理模块,调用prepare_for_training方法,得到返回值data_processed, features_mean, features_deviation
2.得到所有的特征个数,即data的特征维数的列(行shape[0],列shape[1])
3.初始化参数矩阵

 # data:数据 labels:有监督的标签 polynomial_degree、sinusoid_degree、normalize_data: 三个都是预训练需要用到的参数
    def __init__(self, data , labels,polynomial_degree = 0,sinusoid_degree =0,normalize_data=True):
        # data_processed, features_mean, features_deviation 是 prepare_for_training() 方法的三个返回值
        (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

        num_features = self.data.shape[1] # 获得数据的特征数目 即data的特征维数的列(行shape[0],列shape[1])
        self.theta = np.zeros((num_features,1)) # 参数θ 个数等于num_features  (num_features,1)转换成矩阵形式

预训练模块

"""Prepares the dataset for training"""
import numpy as np
from .normalize import normalize
from .generate_sinusoids import generate_sinusoids
from .generate_polynomials import generate_polynomials

def prepare_for_training(data, polynomial_degree=0, sinusoid_degree=0, normalize_data=True):
    # 计算样本总数
    num_examples = data.shape[0]
    data_processed = np.copy(data)

    # 预处理
    features_mean = 0
    features_deviation = 0
    data_normalized = data_processed
    if normalize_data:
        (
            data_normalized,
            features_mean,
            features_deviation
        ) = normalize(data_processed)

        data_processed = data_normalized

    # 特征变换sinusoidal
    if sinusoid_degree > 0:
        sinusoids = generate_sinusoids(data_normalized, sinusoid_degree)
        data_processed = np.concatenate((data_processed, sinusoids), axis=1)

    # 特征变换polynomial
    if polynomial_degree > 0:
        polynomials = generate_polynomials(data_normalized, polynomial_degree, normalize_data)
        data_processed = np.concatenate((data_processed, polynomials), axis=1)

    # 加一列1
    data_processed = np.hstack((np.ones((num_examples, 1)), data_processed))

    return data_processed, features_mean, features_deviation

二、定义计算梯度的方法

按照小批量梯度下降法计算:
在这里插入图片描述

# 定义每一步梯度下降的计算过程
    def gradient_step(self,alpha): # alpha 
    	'''
        梯度下降参数更新计算方法
        :param alpha: 学习率
        :return: 
   	 	'''
        # 样本个数 即data的特征维数的行shape[0]
        num_examples = self.data.shape[0]
        # 预测值
        prediction = LinearRegression.hypothesis(self.data,self.theta)
        delta = prediction - self.labels # 预测值 - 真实值
        # 初始化theta
        theta = self.theta
        # 更新theta 参照上述公式 delta.T 按照转置进行矩阵运算
        theta = theta - alpha * ( 1 / num_examples ) * (np.dot(delta.T , self.data)).T
        self.theta = theta
    # 定义静态方法hypothesis 计算预测值
    @staticmethod
    def hypothesis(data, theta):
        predictions = np.dot(data, theta) # 预测值为data 与 theta 做点乘运算
        return predictions

三、定义损失计算方法

损失函数采用均方误差

    def cost_function(self,data,labels):
        '''
        损失计算方法
        :param data: 样本数据
        :param labels: 真实值
        :return:cost[0][0] 损失值
        '''
        num_examples = data.shape[0] # 样本数目
        delta = LinearRegression.hypothesis(self.data,self.theta) - labels
        # 损失函数计算采用均方误差
        cost = (1/2) * np.dot(delta.T , delta) / num_examples
        return cost[0][0] # 损失值位于二维数组[0][0],只需要返回损失值

四、定义训练函数

# 定义训练方法 alpha:学习率(步长) num_iterations:迭代次数
    def train(self,alpha,num_iterations = 500):
        '''
        训练模块,执行梯度下降
        :param alpha:
        :param num_iterations:
        :return:
        '''
        cost_history = self.gradient_descent(alpha,num_iterations) # 调用该方法不仅可以得到每一步的损失值,而且对参数theta进行了更新
        return self.theta ,cost_history
# 定义梯度下降计算方法
    def gradient_descent(self,alpha,num_iterations):
        '''
        实际迭代模块,迭代num_iterations次
        :param alpha:
        :param num_iterations:
        :return:cost_history
        '''
        cost_history = [] # 列表存放损失
        for _ in range(num_iterations) :
            self.gradient_step(alpha) # 调用每一步具体的计算梯度方法
            cost_history.append(self.cost_function(self.data,self.labels))
        return cost_history # 返回每一步的损失值列表

五、定义获得损失值的方法

不仅仅是训练数据需要计算损失值,之后再进行预测时也需要计算损失值,传入得参数不一样,因此需要重新写一个获得损失值得方法,同时也方便后续进行可视化等操作。

    def get_cost(self,data,labels):
        data_processed = prepare_for_training(data,
                                              self.polynomial_degree,
                                              self.sinusoid_degree,
                                              self.normalize_data
                                              )[0]
        return self.cost_function(data_processed ,labels)

六、定义预测函数

用训练的参数模型,预测得到回归结果

    def predict(self,data):
        '''
        用训练的参数模型,预测得到回归结果
        :param data
        '''
        data_processed = prepare_for_training(data,
                                              self.polynomial_degree,
                                              self.sinusoid_degree,
                                              self.normalize_data
                                              )[0]
        predictions = LinearRegression.hypothesis(data_processed, self.theta)
        return predictions

那么以上线性回归模型的整体框架就已经搭建完成啦!
接下来利用实际数据进行模型验证

七、数据与标签定义

首先通过read_csv方法加载数据,接着通过matplotlib相关绘图方法绘制图像

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from linear_regression import LinearRegression

data = pd.read_csv('./data/world-happiness-report-2017.csv')
# 将数据划分成训练集和测试集
train_data = data.sample(frac= 0.8) # 80% 作为训练集
test_data = data.drop(train_data.index) # 将训练集索引对应的数据删除,剩下的即为测试集 也就是数据的20%
# 定义标签
input_param_name= 'Economy..GDP.per.Capita.'
output_param_name= 'Happiness.Score'

x_train = train_data[[input_param_name]].values # 将数据转换成numpy的ndarray格式(多维数组)
y_train = train_data[[output_param_name]].values

x_test = test_data[[input_param_name]].values
y_test = test_data[[output_param_name]].values

plt.scatter(x_train,y_train,label = 'Train data')
plt.scatter(x_test,y_test,label = 'Test data')
plt.xlabel(input_param_name)
plt.ylabel(output_param_name)
plt.title('Happiness')
plt.legend()
plt.show()

在这里插入图片描述

八、训练线性回归模型

# 模型迭代次数
num_iterations = 500
# 学习率
learning_rate = 0.01
linear_regression = LinearRegression(x_train, y_train)
(theta,cost_history) = linear_regression.train(learning_rate,num_iterations)
print('开始时的损失:',cost_history[0])
print('训练后的损失:',cost_history[-1])
plt.plot(range(num_iterations),cost_history)
plt.xlabel('num_iterations')
plt.ylabel('loss')
plt.title('Gradient_Descent')
plt.show()

在这里插入图片描述
在这里插入图片描述

九、得到线性回归方程

predicitions_num = 100
# linspace在指定的大间隔内(x_train.min(),x_train.max()),返回固定间隔的数据。返回predicitions_num个等间距的样本
x_predictions = np.linspace(x_train.min(),x_train.max(),predicitions_num).reshape(predicitions_num,1)
y_predictions = linear_regression.predict(x_predictions) # 调用预测函数

plt.scatter(x_train,y_train,label = 'Train data')
plt.scatter(x_test,y_test,label = 'Test data')
plt.plot(x_predictions,y_predictions,'r',label = 'Prediction')
plt.xlabel(input_param_name)
plt.ylabel(output_param_name)
plt.title('Happiness')
plt.legend()
plt.show()

在这里插入图片描述

十、多特征线性回归模型

导包 & 读入数据

# 导入第三方库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import plotly # 用于机器学习、数据挖掘等领域的数据可视化包
import plotly.graph_objs as go

plotly.offline.init_notebook_mode()
from linear_regression import LinearRegression

# 加载数据
data = pd.read_csv('./data/world-happiness-report-2017.csv')

划分数据集

# 划分数据集
train_data = data.sample(frac=0.8)
test_data = data.drop(train_data.index)

# 定义标签
input_param_name_1 = 'Economy..GDP.per.Capita.'
input_param_name_2 = 'Freedom'
output_param_name = 'Happiness.Score'

# 得到训练集数据
x_train = train_data[[input_param_name_1 , input_param_name_2]].values
y_train = train_data[[output_param_name]].values

# 得到测试集数据
x_test = test_data[[input_param_name_1 , input_param_name_2]].values
y_test = test_data[[output_param_name]].values

配置绘图

# Configure the plot with training dataset 配置训练集数据进行绘图
plot_training_trace = go.Scatter3d(
    x = x_train[:,0].flatten(), # 第一维特征
    y = x_train[:,1].flatten(), # 第二维特征
    z = y_train.flatten(), # 真实值
    name = 'Training Set',
    mode= 'markers',
    marker = {
        'size' : 10 ,
        'opacity' : 1 ,
        'line' : {
            'color' : 'rgb(255,255,255)',
            'width' : 1
        }
    },
)
# Configure the plot with test dataset 配置测试集数据进行绘图
plot_test_trace = go.Scatter3d(
    x = x_test[:,0].flatten(), # 第一维特征
    y = x_test[:,1].flatten(), # 第二维特征
    z = y_test.flatten(), # 真实值
    name = 'Test Set',
    mode= 'markers',
    marker = {
        'size' : 10 ,
        'opacity' : 1 ,
        'line' : {
            'color' : 'rgb(255,255,255)',
            'width' : 1
        }
    },
)
plot_layout = go.Layout(
    title = 'Date Sets',
    scene = {
        'xaxis' : {'title' : input_param_name_1},
        'yaxis' : {'title' : input_param_name_2},
        'zaxis' : {'title' : output_param_name}
    },
    margin={'l':0,'r':0,'b':0,'t':0}
)
plot_data = [plot_training_trace , plot_test_trace]
plot_figure = go.Figure(data = plot_data, layout = plot_layout)
plotly.offline.plot(plot_figure)

在这里插入图片描述

训练多维特征线性回归模型

num_iterations = 500
learning_rate = 0.01
polynomial_degree = 0
sinusoid_degree = 0
linear_regression = LinearRegression(x_train,y_train,polynomial_degree,sinusoid_degree)
# 调用训练模型方法
(theta , cost_history) = linear_regression.train(
    learning_rate ,
    num_iterations
)
print('开始损失',cost_history[0])
print('结束损失',cost_history[-1])

plt.plot(range(num_iterations) , cost_history)
plt.xlabel('Lterations')
plt.ylabel('Cost')
plt.title('Gradient Descent Progress')
plt.show()

在这里插入图片描述
在这里插入图片描述
绘制回归面图

predictions_num  = 10
x_min = x_train[:,0].min()
x_max = x_train[:,0].max()

y_min = x_train[:,1].min()
y_max = x_train[:,1].max()

x_axis = np.linspace(x_min , x_max , predictions_num)
y_axis = np.linspace(y_min , y_max , predictions_num)

x_predictions = np.zeros((predictions_num * predictions_num, 1))
y_predictions = np.zeros((predictions_num * predictions_num, 1))

x_y_index = 0
for x_index , x_value in enumerate(x_axis):
    for y_index , y_value in enumerate(y_axis):
        x_predictions[x_y_index] = x_value
        y_predictions[x_y_index] = y_value
        x_y_index += 1

z_predictions = linear_regression.predict(np.hstack((x_predictions , y_predictions)))
plot_predictions_trace = go.Scatter3d(
    x = x_predictions.flatten(),
    y = y_predictions.flatten(),
    z = z_predictions.flatten(),
    name = 'Prediction Plane',
    mode = 'markers',
    marker={
        'size':1,
    },
    opacity = 0.8,
    surfaceaxis = 2 ,
)
plot_data = [plot_training_trace , plot_test_trace , plot_predictions_trace]
plot_figure = go.Figure(data = plot_data , layout= plot_layout)
plotly.offline.plot(plot_figure)

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/137026.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

怎么获取level2行情接口数据?

怎么获取level2行情接口数据比较方便呢?其实level2行情接口可以实时计算沪深所有股票数据,主要是可以让交易者方便引用和计算公式再进入股票池,就比如说一个分笔数据含有10-20个分笔数据,用分笔数据计算的资金流入数据不准确&…

< Linux > 进程控制

目录 1、进程创建 fork函数 fork函数返回值 写时拷贝 fork常规用法 fork调用失败的原因 2、进程终止 2.1、进程退出常见场景 2.2、进程退出码 2.3、进程常见退出方法 _exit函数 exit函数 return退出 2.4、关于终止,内核做了什么 3、进程等待 3.1、进程等待必要性…

解决VS2019+Qt5+Vcpkg工程无法调试但Release正常运行的问题

前言——这个问题可能比较小众,但是因为解决了我自己的问题,所以特此把解决方法分享出来,以给特定的人提供必要的帮助。 项目原因,一直使用VS2019Qt5Vcpkg,无奈程序一直无法进行调试,Release模式倒是正常运…

计算机图形学 Ray Trace 学习笔记

屏幕上的一个像素,是通过各种反射、折射而共同组成的,每个反射折射的点,都会考虑光源是否有直接照射到反射折射的点上,反射与折射之间会存在能量衰减,最终汇总在屏幕的像素上。 计算是哪一个三角形被射线打中&#xff…

Hive SQL 每日SQL

1、查询订单明细表(order_detail)中销量(下单件数)排名第二的商品id,如果不存在返回null,如果存在多个排名第二的商品则需要全部返回。 需要用到的表: 订单明细表:order_detail 代码…

【谷粒商城基础篇】仓储服务:仓库维护

谷粒商城笔记合集 分布式基础篇分布式高级篇高可用集群篇简介&环境搭建项目简介与分布式概念(第一、二章)基础环境搭建(第三章)整合SpringCloud整合SpringCloud、SpringCloud alibaba(第四、五章)前端知…

android 创建aar包

1. 背景 由于新入职公司在做硬件接入的项目,需要接入多款硬件,而且,几个app的功能不太一样。于是,需要模块化开发,并且许多东西都是可以复用的(像网络框架、log、shareprefrence、权限申请等)。…

嵌入式HLS 案例开发步骤分享——Zynq-7010/20工业开发板(1)

目 录 前 言 3 1 HLS 开发流程说明 5 1.1 HLS 工程导入 5 1.2 编译与仿真 6 1.3 综合 8 1.4 IP 核封装 10 1.5 IP 核测试 14 前 言 本文主要介绍 HLS 案例的使用说明,适用开发环境: Windows 7/10 64bit、Xilinx Vivado 2017.4 、Xilinx Vivado HLS 2017.4 、Xilinx…

数据结构|排序算法详解

​​​​​​​目录 一.插入类 1.直接插入排序 2.希尔排序 二.选择类,排一次选出一个最值 1.选择排序 2.堆排序 三.交换类,通过一直交换一次确定数字的位置 1.冒泡排序 2.快速排序 2.1 hoare版本 2.2挖坑法 2.3前后指针法 四.归并类 1.归并…

Go第 5 章:程序流程控制

第五章程序流程控制 5.1程序流程控制介绍 在程序中,程序运行的流程控制决定程序是如何执行的,是我们必须掌握的,主要有三大流程控 制语句。 1)顺序控制 2)分支控制 3)循环控制 5.2 顺序控制 程序从上到下逐行地执行,中间没有任…

C++标准库的智能指针:shared_ptr、weak_ptr和unique_ptr

文章目录智能指针shared_ptr模版类week_ptr模版类unique_ptrC中是没有内存回收机制的,我在之前的一篇文章中提到使用指针的一些基本方法。C在std标准库中也提供了三种封装过的指针模版类,称作为智能指针:shared_ptrunique_ptrweek_ptr 我这里…

JVM性能调优详解

前面我们学习了整个JVM系列,最终目标的不仅仅是了解JVM的基础知识,也是为了进行JVM性能调优做准备。这篇文章带领大家学习JVM性能调优的知识。 性能调优 性能调优包含多个层次,比如:架构调优、代码调优、JVM调优、数据库调优、操…

最优二叉树(哈夫曼树)

一、最优二叉树 1、定义 官方定义:在权值为w1,w2,…,wn的 n个叶子所构成的所有二叉树中,带权路径长度最小(即代价最小)的二叉树称为最优二叉树或哈夫曼树。 通俗来讲,就是给定N个权值作为N个叶子结点&…

仿牛客论坛项目总结

一.数据库中每一张表有哪些字段 user表 用户表 (1)id 用户的id (2) username 用户名 (3)password 密码 (4)salt 盐 (5)emai邮箱 (6&…

PAT甲级1008 Elevator C++/C语言

1008 Elevator 分数 20 作者 CHEN, Yue 单位 浙江大学 The highest building in our city has only one elevator. A request list is made up with N positive numbers. The numbers denote at which floors the elevator will stop, in specified order. It costs 6 seconds …

联邦学习将如何影响您的日常生活?

人工智能 (AI) 被认为是下一次工业革命的最大创新之一,其中包括机器学习。另一方面,随着原油和电力成为现代工业的基础资源,数据成为人工智能和机器学习的关键要素。 数据隐私与需求之间的冲突 训练的数据样本的大小决定了可用于增强 AI 性能…

CPT203-Software Engineering(2)

文章目录5. Scrum Framework5.1 Scrum Roles5.2 Scrum Activities and Artifacts6. Requirements Engineering6.1 User requirements and system requirements6.2 Functional & Non-functional requirements6.2.1 Functional requirements6.2.2 Non-functional requirement…

第一章:C++算法基础之基础算法

系列文章目录 文章目录系列文章目录前言一、排序(1)快速排序核心思想思路分析模板(2)归并排序核心思想思路分析模板稳定性时间复杂度二分查找(1)整数二分核心思想思路分析模板(2)浮点…

jetson nano系统引导安装(无外设安装方式)

文章目录一.硬件设置二.系统设置一.硬件设置 插入烧写好系统的SD卡将micro USB线接到jetson nano上,另一端USB A接到电脑上为jetson nano插入电源,开机等待电脑检测到如下盘符说明jetson nano连接成功 二.系统设置 进入电脑的设备管理器,查…

【linux】三种权限的使用和更改、粘滞位和yum的使用

目录 1.权限问题 ①什么是权限? ②小问题 ③默认权限 ④如何更改“人”的权限呢? ⑤更改权限的八进制方案 ⑥强制改权限里的“人”(权限人文件属性) 2.粘滞位 2.yum的使用 1.权限问题 ①什么是权限? 权限人&a…