机器学习1

news2024/10/7 10:19:43

 

 

 

 

 

 核心梯度下降算法:

import numpy as np
from utils.features import prepare_for_training

class LinearRegression:

    def __init__(self,data,labels,polynomial_degree = 0,sinusoid_degree = 0,normalize_data=True):
        """
        1.对数据进行预处理操作
        2.先得到所有的特征个数
        3.初始化参数矩阵
        """
        (data_processed, #预处理完之后的数据(标准化之后的数据)
         features_mean,  #预处理完之后的平均值和标准差
         features_deviation)  = prepare_for_training(data, polynomial_degree, sinusoid_degree,normalize_data=True)
        # 在数据预处理中,对数据进行标准化(normalize)时,通常会使用数据的均值和标准差。标准化是一种常见的数据预处理技术,
        # 它通过减去均值并除以标准差,将数据转换为具有零均值和单位方差的形式。这样做可以使得不同尺度的特征具有相似的重要性,有助于提高模型的性能和收敛速度。

        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]

        #最终求解的 theta 值,初始化theta参数矩阵
        self.theta = np.zeros((num_features,1))


    #alpha为学习率,也就是步长,越小越好;num_iterations为迭代次数
    def train(self,alpha,num_iterations = 500):
        """
                    训练模块,执行梯度下降
        """
        #cost_history记录损失变化
        cost_history = self.gradient_descent(alpha,num_iterations)
        return self.theta,cost_history

    #梯度下降
    def gradient_descent(self,alpha,num_iterations):
        """
                    实际迭代模块,会迭代num_iterations次
        """
        #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 gradient_step(self,alpha):    
        """
                    梯度下降参数更新计算方法,注意是矩阵运算
        """
        #样本个数
        num_examples = self.data.shape[0]
        #预测值
        prediction = LinearRegression.hypothesis(self.data, self.theta)
        #误差值delta = 预测值-真实值
        delta = prediction - self.labels

        #通过步长来,对theta参数进行迭代更新
        theta = self.theta
        #使用矩阵可以避免for循环
        theta = theta - alpha*(1/num_examples)*(np.dot(delta.T,self.data)).T
        self.theta = theta
        

    #损失函数计算方法
    def cost_function(self,data,labels):
        """
                    损失计算方法
        """
        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]
        
        
    #预测值 = theta * 数据, 返回矩阵点乘数据    y = theta1*x1 + theta2*x2 + ……
    @staticmethod
    def hypothesis(data,theta):   
        predictions = np.dot(data,theta)
        return predictions


    #获取损失值
    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):
        """
                    用训练的参数模型,与预测得到回归值结果
        """
        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
        
        
        
        
"""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

绘图:

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)
test_data = data.drop(train_data.index)

input_param_name = 'Economy..GDP.per.Capita.'
output_param_name = 'Happiness.Score'

x_train = train_data[[input_param_name]].values
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('Happy')
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('Iter')
plt.ylabel('cost')
plt.title('GD')
plt.show()

predictions_num = 100
x_predictions = np.linspace(x_train.min(),x_train.max(),predictions_num).reshape(predictions_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('Happy')
plt.legend()
plt.show()

 

 

 两个变量的线性回归模型,建议使用plotly进行绘图

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
        },
    }
)


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('Iterations')
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/766728.html

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

相关文章

【Linux】进程信号 -- 信号产生 | 系统调用、硬件、软件的信号发送

信号的旧识引入信号引入signal调用 系统调用向目标进程发送信号模拟实现一个kill命令raise给自己发送任意信号abort给自己发送指定信号(6)SIGABRT 硬件异常产生信号除0异常野指针访问异常 软件条件产生信号拓展 总结思考进程退出时核心转储问题小实验 信号的旧识引入 kill -l是…

手动实现 Tomcat 底层机制+ 自己设Servlet 问题分析

文章目录 手动实现 Tomcat 底层机制 自己设Servlet问题分析完成小案例运行效果 此项目用maven至于怎么配置在下一篇文章创建cal.htmlCalServlet.java# 实现步骤 web.xmlWebUtils 问题:Tomcat 整体架构分析测试分析:抓包情况 手动实现 Tomcat 底层机制 自己设Servlet…

ALPAGASUS : TRAINING A BETTER ALPACA WITH FEWER DATA♢

ALPAGASUS : TRAINING A BETTER ALPACA WITH FEWER DATA♢ IntroductionMethod参考 Introduction 本文证明了数据的质量的重要性要大于数量。作者通过与GPT交互的方法过滤了Alpaca52k的数据,剩下9k,对二者分别微调,通过实验对比,…

软件测试行业的困境和迷局

中国的软件测试虽然起点较高,但是软件测试的发展似乎没有想象中那么顺利。 其实每个行业除了有自身领域外,还有属于自己的“生态系统”。属于软件测试的生态系统主要包括后备软件测试人员、软件开发人员和软件管理决策者。后备软件测试人员是软件测试的…

获取gitlab上项目列表过程及脚本

一、使用Gitlab API查询项目列表 1、首先获取访问令牌&#xff1a;在Gitlab上生成一个访问令牌&#xff0c;以便能够使用API进行身份验证。可以在GitLab的用户设置中创建一个访问令牌。 2、使用curl发送GET请求的命令&#xff1a; curl --header "PRIVATE-TOKEN: <you…

若依字典使用

若依字典使用 此文章使用的若依是大于3.7.0版本的 JS文件配置 main.js中引入全局变量和方法 import DictData from /components/DictData DictData.install()DictData.js配置 可以从DictData.js中看出在install方法中调用了字典查询接口&#xff0c;在install方法中可以做…

Atom配置Java开发环境

第1步&#xff1a; 从Oracle网站下载安装最新的Java开发包&#xff08;JDK&#xff09; 将JDK添加到环境变量中 参考链接&#xff1a;传送门1&#xff08;外网&#xff09;&#xff0c; 传送门2&#xff08;国内&#xff09; 第2步&#xff1a;现在要在Atom编辑器上运行Jav…

【C++修炼之路】list 模拟实现

&#x1f451;作者主页&#xff1a;安 度 因 &#x1f3e0;学习社区&#xff1a;StackFrame &#x1f4d6;专栏链接&#xff1a;C修炼之路 文章目录 一、读源码二、成员三、默认成员函数1、构造2、析构3、拷贝构造4、赋值重载 四、迭代器五、其他接口 如果无聊的话&#xff0c;…

Pytorch自动求导机制详解

目录 1. 自动求导 1.1 梯度计算 1.1.1 一阶导数 1.1.2 二阶导数 1.1.3 向量 1.2 线性回归实战 1. 自动求导 在深度学习中&#xff0c;我们通常需要训练一个模型来最小化损失函数。这个过程可以通过梯度下降等优化算法来实现。梯度是函数在某一点上的变化率&#xff0c;可以告…

vue代码格式化,Prettier - Code formatter格式化规则文件

vue2&#xff0c;vue3格式化代码使用方法&#xff1a; 1、新建文件名&#xff1a; .prettierrc.cjs&#xff0c;里面放上下面的代码片段&#xff0c;直接粘贴即可 2、把 .prettierrc.cjs文件放在项目的根目录中 // prettier的默认配置文件 module.exports {// 一行最多 100 …

Final Cut Pro中文新手教程 (52绿幕抠图)FCPX透明通道基础使用方法

今天小编为大家分享的是FCPX透明通道基础教程&#xff0c;究竟什么是透明通道呢&#xff1f;透明通道就是一个阿尔法(alpha)通道&#xff0c;也叫做通明阿尔法通道。只要带有alpha的图片或者视频&#xff0c;他们的背景就是透明的只会显示他们的形状和内容。这种技术经常应用在…

VLAN :虚拟局域网

目录 VLAN&#xff1a;虚拟局域网 VLAN种类&#xff1a; 接口分配链路类型 接口划分VLAN 跨网段的通讯 VLAN&#xff1a;虚拟局域网 LAN &#xff1a;局域网 MAN&#xff1a;城域网 WAN&#xff1a;广域网 1.一个VLAN相当于一个广播域 VLAN&#xff1a;通过路由器和交换机…

OpenCv之图像形态学

目录 一、形态学 二、图像全局二值化 三、自适应阈值二值化 四、腐蚀操作 五、获取形态学卷积核 六、膨胀操作 七、开运算 八、闭运算 一、形态学 定义: 指一系列处理图像形状特征的图像处理技术形态学的基本思想是利用一种特殊的结构元(本质上就是卷积核)来测量或提取输…

数据结构--图的基本操作

数据结构–图的基本操作 使用的存储模式&#xff1a; 图的基本操作&#xff1a; • Adjacent(G,x,y)&#xff1a;判断图G是否存在边<x, y>或(x, y)。 • Neighbors(G,x)&#xff1a;列出图G中与结点x邻接的边。 • InsertVertex(G,x)&#xff1a;在图G中插入顶点x。 • …

VSCode 注释后光标快速定位下一行

VSCode默认用 Ctrl / 注释一行时&#xff0c;光标停留在该行中。下面介绍如何注释后&#xff0c;光标会自动移动到下一行。 1.【View】 ->【Extensions】->【查找并安装Multi-command 扩展】 2.【File 】 -> 【Preferences 】->【Keyboard Shortcuts】&#xff08…

怎样优雅地增删查改(八):按用户关系查询

文章目录 原理实现正向用户关系反向用户关系 使用测试 用户关系&#xff08;Relation&#xff09;是描述业务系统中人员与人员之间的关系&#xff0c;如&#xff1a;签约、关注&#xff0c;或者朋友关系。 之前我们在扩展身份管理模块的时候&#xff0c;已经实现了用户关系管理…

Spark(30):Spark性能调优之常规性能调优

目录 0. 相关文章链接 1. 最优资源配置 2. RDD优化 2.1. RDD复用 2.2. RDD持久化 2.3. RDD尽可能早的 filter 操作 3. 并行度调节 4. 广播大变量 5. Kryo序列化 6. 调节本地化等待时长 0. 相关文章链接 Spark文章汇总 1. 最优资源配置 Spark 性能调优的第一步&…

9.Ceph部署

文章目录 Ceph部署前期环境准备实验部署软件安装部署Ceph集群部署mon节点部署OSD存储节点部署mgr节点开启监控模块管理pool Ceph部署 前期环境准备 主机名public网络cluster网络角色admin192.168.242.69admin(管理节点)node01192.168.242.66192.168.242.100.11mon、mgr、osdn…

【Elemnt-UI——el-popover点击出现多个弹框】

效果图 解决 :append-to-body"false"添加这个属性就可以了 <el-popoverv-model"item.contextmenuVisible"placement"bottom-end":append-to-body"false"trigger"click":visible-arrow"false"hide"item.…

[PCIE体系结构导读]PCIE总结(一)

什么是PCIE PCIe Peripheral Component Interconnect express 快速外部组件互联 高速串行计算机扩展总线标准 处理器系统的局部总线 连接外部设备 高速、低时延支持热插拔可靠扩展性好复杂度高点对点串行连接 附一个博主写的总结文章&#xff0c;非常好 《PCI EXPRESS体系结…