总结1_1:常用周期函数

1.周期函数调用顺序(PS:吐槽一句,不知道是不是转发的缘故,百度上好多写错的,把FixedUpdate->Update写反了):

Awake->OnEnable->Start->FixedUpdate->Update->LateUpdate->OnGUI->OnDisable->OnDestroy

1)挂载脚本:Reset
①Reset是脚本被挂上的时候执行一次,其他时候不执行,严格来说不算周期函数

2)物体(脚本所挂的游戏对象)加载:Awake->OnEnable->Start
①Awake:加载的时候第一个运行的方法,适合用来构建单例,还可以用来进行一些初始化操作。不知道Awake和OnEnable的顺序是不是被unity存在栈里了,最后挂的最先执行。

//单例
//然后在其他类里调这个类的实例:ClassA.instance.DebugCtr();
public class ClassA{
	public static ClassA instance;
	private void Awake()
	{
		if(instance == null)
		{
			instance = this;
		}
	}
	public void DebugCtr()
	{
		Debug.Log("This is ClassA instance");
	}
}

②OnEnable:物体显示时被调用
③Start:如果不在Awake里初始化,就可以放在在Start里;Start里面可以用来开启协程

3)物体加载完成:FixedUpdate->Update->LateUpdate->OnGUI
①FixedUpdate:每固定帧率(默认是0.02s,即1/50 s)调用一次,一般用作物理更新。自定义可以在Edit->Project Settings->Time里修改Fixed Timestep的数值
这里写图片描述
②Update:每帧调用一次(一般趋近0.02s,跟硬件性能和项目内容有关),用来检测事件;
③LateUpdate:与Update同步,紧随其后。摄像机的跟随可以放在里面。
④OnGUI:unity原生的GUI就需要在这里面写

	protected void OnGUI()
    {
        //DebugCtr(ref isOnGUI, "OnGUI()");
        GUILayout.BeginArea(new Rect(10,1,200,150));
        GUI.Box(new Rect(10, 1, 100, 100),"This is Unity GUI");
        GUILayout.EndArea();
    }

这里写图片描述

4)物体销毁:OnDisable->OnDestroy
①OnDisable:物体隐藏时调用,可以用来注销事件
②OnDestroy:物体被销毁时调用,可以用来注销事件

5)看到这里的童鞋有没有想过多个脚本之间,周期函数的规律?
(有脚本A、B,A先挂,B后挂)

B:Awake->B:OnEnable ->A:Awake->A:OnEnable->
B:Start->A:Start->B:FixedUpdate->A:FixedUpdate->B:Update->A:Update->B:LateUpdate->A:LateUpdate->B:OnGUI->A:OnGUI
A:OnDisable->B:OnDisable ->A:OnDistroy->B:OnDistroy
(注意,我分成三段了!!! )
总结:
①Awake和OnEnable先后一起出现;
②物体加载的时候,后挂的先执行;物体销毁的时候,先挂的先执行。

这里写图片描述


---------------最后,挂上测试的代码 0.0-------------------------------------------------

//**基类**
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScriptTestBase : MonoBehaviour {
    protected bool isStart, isAwake, isOnEnable, isNewBehaviourScriptTest,
        isUpdate, isLateUpdate, isFixedUpdate, isOnDisable, isOndestroy, isOnGUI,isReset;

    protected virtual void  DebugCtr(ref bool isDebug, string msg)
    {

    }
    protected void Reset()
    {
        DebugCtr(ref isReset, "Reset()");
    }
    protected void Awake()
    {
        DebugCtr(ref isAwake, "Awake()");
    }
    protected void Start()
    {
        DebugCtr(ref isStart, "Start ()");
    }
    protected void Update()
    {
        DebugCtr(ref isUpdate, "Update ()");
    }
    protected void LateUpdate()
    {
        DebugCtr(ref isLateUpdate, "LateUpdate()");
    }
    protected void FixedUpdate()
    {
        DebugCtr(ref isFixedUpdate, "FixedUpdate()");
    }
    protected void OnGUI()
    {
        DebugCtr(ref isOnGUI, "OnGUI()");
    }
    protected void OnDestroy()
    {
        DebugCtr(ref isOndestroy, "OnDestroy()");
    }
    protected void OnDisable()
    {
        DebugCtr(ref isOnDisable, "OnDisable()");
    }
    protected void OnEnable()
    {
        DebugCtr(ref isOnEnable, "OnEnable()");
    }
}

//**子类A**
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ClassA : NewBehaviourScriptTestBase {

    protected override void DebugCtr(ref bool isDebug, string msg)
    {
        if (!isDebug)
        {
            Debug.Log("A: " + msg);
            isDebug = true;
        }
    }
}
//**子类B**
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ClassB : NewBehaviourScriptTestBase {

    protected override void DebugCtr(ref bool isDebug, string msg)
    {
        if (!isDebug)
        {
            Debug.Log("B: " + msg);
            isDebug = true;
        }
    }
}

分析每一类核函数的优缺点:Depth## 高斯过程评估 - 训练RMSE: 241.1803, 训练R²: 0.3369 | 交叉验证RMSE: 252.8797, 交叉验证R²: 0.2674 | 训练时间: 33.63s | 最佳参数: {'random_state': 42, 'optimizer': 'fmin_l_bfgs_b', 'normalize_y': False, 'n_restarts_optimizer': 1, 'kernel': RationalQuadratic(alpha=10, length_scale=1), 'copy_X_train': True, 'alpha': 10.0} 所有参数组合评估: - {'random_state': 42, 'optimizer': 'fmin_l_bfgs_b', 'normalize_y': False, 'n_restarts_optimizer': 3, 'kernel': WhiteKernel(noise_level=1), 'copy_X_train': True, 'alpha': 100.0}: RMSE=318.4064, R²=-0.1614 - {'random_state': 42, 'optimizer': None, 'normalize_y': False, 'n_restarts_optimizer': 1, 'kernel': RBF(length_scale=1), 'copy_X_train': True, 'alpha': 10.0}: RMSE=293.6855, R²=0.0116 - {'random_state': 42, 'optimizer': 'fmin_l_bfgs_b', 'normalize_y': True, 'n_restarts_optimizer': 3, 'kernel': WhiteKernel(noise_level=0.01), 'copy_X_train': False, 'alpha': 0.5}: RMSE=296.1735, R²=-0.0044 - {'random_state': 42, 'optimizer': 'fmin_l_bfgs_b', 'normalize_y': False, 'n_restarts_optimizer': 3, 'kernel': 1**2 * RBF(length_scale=1) + WhiteKernel(noise_level=0.1), 'copy_X_train': False, 'alpha': 100.0}: RMSE=296.1786, R²=-0.0045 - {'random_state': 42, 'optimizer': 'fmin_l_bfgs_b', 'normalize_y': False, 'n_restarts_optimizer': 0, 'kernel': RationalQuadratic(alpha=0.1, length_scale=1), 'copy_X_train': True, 'alpha': 100.0}: RMSE=293.9921, R²=0.0103 - {'random_state': 42, 'optimizer': None, 'normalize_y': False, 'n_restarts_optimizer': 0, 'kernel': WhiteKernel(noise_level=0.01), 'copy_X_train': True, 'alpha': 100.0}: RMSE=318.4064, R²=-0.1614 - {'random_state': 42, 'optimizer': 'fmin_l_bfgs_b', 'normalize_y': True, 'n_restarts_optimizer': 3, 'kernel': RBF(length_scale=1) + WhiteKernel(noise_level=0.1), 'copy_X_train': False, 'alpha': 10.0}: RMSE=271.8304, R²=0.1540 - {'random_state': 42, 'optimizer': 'fmin_l_bfgs_b', 'normalize_y': True, 'n_restarts_optimizer': 0, 'kernel': 1**2 * RBF(length_scale=1) + WhiteKernel(noise_level=0.1), 'copy_X_train': True, 'alpha': 100.0}: RMSE=296.1735, R²=-0.0044 - {'random_state': 42, 'optimizer': 'fmin_l_bfgs_b', 'normalize_y': False, 'n_restarts_optimizer': 1, 'kernel': RationalQuadratic(alpha=10, length_scale=1), 'copy_X_train': True, 'alpha': 10.0}: RMSE=252.8797, R²=0.2674 - {'random_state': 42, 'optimizer': None, 'normalize_y': True, 'n_restarts_optimizer': 0, 'kernel': Matern(length_scale=10, nu=2.5), 'copy_X_train': True, 'alpha': 100.0}: RMSE=287.2155, R²=0.0556 - {'random_state': 42, 'optimizer': 'fmin_l_bfgs_b', 'normalize_y': False, 'n_restarts_optimizer': 3, 'kernel': ExpSineSquared(length_scale=1, periodicity=1), 'copy_X_train': False, 'alpha': 100.0}: RMSE=290.5389, R²=0.0333 - {'random_state': 42, 'optimizer': 'fmin_l_bfgs_b', 'normalize_y': False, 'n_restarts_optimizer': 0, 'kernel': RBF(length_scale=1) + WhiteKernel(noise_level=0.1), 'copy_X_train': False, 'alpha': 100.0}: RMSE=318.1899, R²=-0.1598 - {'random_state': 42, 'optimizer': 'fmin_l_bfgs_b', 'normalize_y': False, 'n_restarts_optimizer': 1, 'kernel': 1**2 * RBF(length_scale=1) + WhiteKernel(noise_level=0.1), 'copy_X_train': False, 'alpha': 100.0}: RMSE=296.1791, R²=-0.0045 - {'random_state': 42, 'optimizer': 'fmin_l_bfgs_b', 'normalize_y': False, 'n_restarts_optimizer': 1, 'kernel': RBF(length_scale=1) + WhiteKernel(noise_level=0.1), 'copy_X_train': True, 'alpha': 10.0}: RMSE=318.1898, R²=-0.1598 - {'random_state': 42, 'optimizer': None, 'normalize_y': False, 'n_restarts_optimizer': 0, 'kernel': 1**2 * RBF(length_scale=1) + WhiteKernel(noise_level=0.1), 'copy_X_train': True, 'alpha': 100.0}: RMSE=314.5399, R²=-0.1334
最新发布
07-17
<think>我们被要求分析每一类核函数的优缺点。根据提供的高斯过程评估结果,我们可以看到使用了多种核函数,包括: - RationalQuadratic - WhiteKernel - RBF (Radial Basis Function) - Matern - ExpSineSquared - 以及一些组合核函数(如RBF + WhiteKernel) 我们将根据这些核函数在评估中的表现,结合它们的一般特性,来分析各自的优缺点。 1. RationalQuadratic (有理二次核函数) 优点:可以看作是多个RBF核的叠加,适用于具有不同长度尺度的数据。它有一个额外的参数α,当α趋于无穷时,它等价于RBF核。因此,它比RBF更灵活。 缺点:计算复杂度可能稍高,因为涉及额外的参数优化。 在评估中,使用RationalQuadratic(alpha=10, length_scale=1)的模型在交叉验证中取得了最佳效果(RMSE=252.8797, R²=0.2674),说明它在这个数据集上表现最好。 2. WhiteKernel (白噪声核函数) 优点:用于建模数据中的噪声。通常与其他核函数组合使用,以表示独立同分布的噪声。 缺点:单独使用时,只能表示噪声,无法捕捉数据的任何结构。从评估中可以看出,单独使用WhiteKernel的模型表现很差(RMSE=318.4064, R²=-0.1614)。 3. RBF (径向基函数核,也称为平方指数核) 优点:平滑且无限可微,适用于建模平滑的函数。在机器学习中非常常用,尤其在高斯过程中。 缺点:假设目标函数是无限可微的,这可能过于严格,导致对某些数据(如具有不连续性的数据)拟合不佳。 在评估中,单独使用RBF核的模型表现一般(RMSE=293.6855, R²=0.0116),但与其他核(如WhiteKernel)组合后,表现有所提升(如:RBF+WhiteKernel在某个参数组合下得到RMSE=271.8304, R²=0.1540)。 4. Matern核 优点:通过参数nu控制平滑度,比RBF更灵活。当nu=1.5时,相当于一次可微的函数;当nu=2.5时,相当于二次可微的函数;当nu趋于无穷时,等同于RBF。因此,它可以适应不同平滑度的数据。 缺点:计算上比RBF稍复杂。 在评估中,使用Matern(nu=2.5)的模型表现一般(RMSE=287.2155, R²=0.0556),但优于单独使用RBF。 5. ExpSineSquared (周期核) 优点:适用于具有周期性模式的数据。 缺点:如果数据没有周期性,则效果会很差。 在评估中,使用ExpSineSquared的模型表现不佳(RMSE=290.5389, R²=0.0333),可能因为数据没有明显的周期性。 6. 组合核函数(如RBF+WhiteKernel) 优点:结合了RBF对主要模式的捕捉和WhiteKernel对噪声的建模,因此更适用于实际数据(通常包含噪声)。 缺点:参数更多,优化难度更大。 在评估中,组合核函数的表现有好有坏,取决于参数。例如,一个组合核在特定参数下得到RMSE=271.8304(R²=0.1540),而另一个组合核则表现较差(RMSE=318.1899, R²=-0.1598)。这说明组合核需要仔细调整参数。 总结: - 在这个具体任务中,RationalQuadratic核表现最佳,说明数据可能具有不同长度尺度的特征。 - 组合核(如RBF+WhiteKernel)在调整得当的情况下也能取得不错的效果,但需要调参。 - 单独使用WhiteKernel或ExpSineSquared效果较差,说明数据中噪声不是唯一因素,且可能没有明显的周期性。 根据以上分析,我们可以给出如下建议: - 在数据具有不同长度尺度的特征时,优先尝试RationalQuadratic核。 - 当数据包含噪声时,考虑使用组合核(如RBF+WhiteKernel)来同时建模信号和噪声。 - 对于周期性数据,使用ExpSineSquared核,但要注意验证数据是否具有周期性。 - 使用Matern核作为RBF的替代,尤其是当数据可能不是无限可微时。 注意:以上结论基于提供的数据集评估结果,不同的数据集可能表现不同。 由于问题要求分析每一类核函数的优缺点,我们不需要提供代码,但可以给出一个使用高斯过程回归并尝试不同核函数的示例代码。 以下是一个使用sklearn的高斯过程回归(GaussianProcessRegressor)并比较不同核函数的示例: ```python import numpy as np from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import RBF, RationalQuadratic, WhiteKernel, Matern, ExpSineSquared, ConstantKernel from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error, r2_score import time # 假设X, y是已经准备好的数据 # X, y = ... # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 定义不同的核函数 kernels = { 'RBF': RBF(), 'RationalQuadratic': RationalQuadratic(), 'Matern': Matern(), 'ExpSineSquared': ExpSineSquared(), 'RBF+WhiteKernel': RBF() + WhiteKernel(), # 可以添加更多 } results = {} for name, kernel in kernels.items(): print(f"Training with kernel: {name}") start_time = time.time() gp = GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=10, random_state=42) gp.fit(X_train, y_train) training_time = time.time() - start_time # 预测训练集和测试集 y_train_pred, y_test_pred = gp.predict(X_train), gp.predict(X_test) # 计算指标 train_rmse = np.sqrt(mean_squared_error(y_train, y_train_pred)) test_rmse = np.sqrt(mean_squared_error(y_test, y_test_pred)) train_r2 = r2_score(y_train, y_train_pred) test_r2 = r2_score(y_test, y_test_pred) results[name] = { 'train_rmse': train_rmse, 'test_rmse': test_rmse, 'train_r2': train_r2, 'test_r2': test_r2, 'training_time': training_time, 'kernel': kernel, 'trained_kernel': gp.kernel_ # 训练后得到的核函数(参数已优化) } print(f"Results for {name}:") print(f" Train RMSE: {train_rmse:.4f}, Test RMSE: {test_rmse:.4f}") print(f" Train R²: {train_r2:.4f}, Test R²: {test_r2:.4f}") print(f" Training time: {training_time:.2f}s") print("="*50) # 根据测试集RMSE排序 sorted_results = sorted(results.items(), key=lambda x: x[1]['test_rmse']) print("Ranking of kernels based on test RMSE:") for i, (name, res) in enumerate(sorted_results): print(f"{i+1}. {name}: Test RMSE={res['test_rmse']:.4f}, Test R²={res['test_r2']:.4f}") ``` 这段代码可以帮助我们比较不同核函数在同一个数据集上的表现。注意,我们使用了`n_restarts_optimizer=10`来增加优化的鲁棒性,因为优化核函数的参数是一个非凸问题。 最后,根据分析,我们提出以下相关问题: §§相关问题§§: 1. 如何选择高斯过程回归中的核函数? 2. 在什么情况下应该使用组合核函数?请举例说明。 3. 如何解释高斯过程回归中核函数的超参数? 4. 高斯过程回归在处理大规模数据时可能会遇到什么问题?有哪些解决方案?</think>### 核函数优缺点分析 根据高斯过程评估结果,以下是各类核函数的性能分析和优缺点总结: #### 1. **RationalQuadratic (有理二次核)** ```python RationalQuadratic(alpha=10, length_scale=1) ``` - **优点**: - 灵活性高,可视为多个RBF核的叠加 - 通过α参数控制长度尺度的混合比例 - 在本次评估中表现最佳(RMSE=252.88, R²=0.2674) - **缺点**: - 计算复杂度高于RBF核 - α参数需要仔细调优 - **适用场景**:多尺度特征的数据集 #### 2. **RBF (径向基函数核)** ```python RBF(length_scale=1) ``` - **优点**: - 通用性强,适合平滑函数 - 数学性质良好(无限可微) - 计算效率较高 - **缺点**: - 对非平稳数据敏感 - 单独使用易受噪声干扰(RMSE=293.69) - **改进方案**:通常需组合白噪声核(如 `RBF() + WhiteKernel()`) #### 3. **WhiteKernel (白噪声核)** ```python WhiteKernel(noise_level=0.1) ``` - **优点**: - 显式建模观测噪声 - 防止模型过拟合噪声 - **缺点**: - 单独使用无效(RMSE=318.41) - 需与其他核组合才有意义 - **最佳实践**:作为附加项使用,如 `主核 + WhiteKernel()` #### 4. **Matern (马滕核)** ```python Matern(length_scale=10, nu=2.5) ``` - **优点**: - 通过ν参数控制平滑度(ν=2.5适合二次可微函数) - 比RBF更适合不规则数据 - **缺点**: - 计算成本高于RBF - 参数优化更复杂 - **性能**:中等(RMSE=287.22) #### 5. **ExpSineSquared (周期核)** ```python ExpSineSquared(length_scale=1, periodicity=1) ``` - **优点**: - 专门处理周期性模式 - periodicity参数明确控制周期 - **缺点**: - 对非周期数据效果差(RMSE=290.54) - 参数敏感度高 - **适用场景**:温度变化、振动信号等周期性数据 #### 6. **组合核函数** ```python 1**2 * RBF(length_scale=1) + WhiteKernel(noise_level=0.1) ``` - **优势组合**: - RBF捕捉全局模式 + WhiteKernel处理噪声(RMSE=271.83) - 核乘法(如`RBF() * ExpSineSquared()`)可建模周期性非平稳过程 - **劣势**: - 参数优化空间指数增长 - 训练时间显著增加(如n_restarts_optimizer=3时) --- ### 关键发现与建议 1. **最佳实践**:RationalQuadratic在本次任务中表现最优,适合多尺度特征 2. **噪声处理**:所有表现良好的模型都包含显式噪声项(α参数或WhiteKernel) 3. **参数敏感**: - `n_restarts_optimizer=3` 相比 `=0` 提升显著 - `alpha=10.0`(正则化参数)优于极端值 4. **失败案例**: - 单独使用WhiteKernel导致负R² - 错误的周期核假设使性能下降7% --- ### 核函数选择流程图 ```mermaid graph TD A[数据特征] --> B{是否有明显周期?} B -->|是| C[ExpSineSquared] B -->|否| D{数据是否平滑?} D -->|是| E[RBF] D -->|部分区域| F[Matern] D -->|多尺度变化| G[RationalQuadratic] H[所有场景] --> I[+ WhiteKernel处理噪声] ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值