首页 > 其他分享 >各种特殊损失函数

各种特殊损失函数

时间:2024-07-03 22:31:58浏览次数:15  
标签:plt 函数 epsilon 损失 特殊 values dx max np

死区损失函数


点击查看代码
import numpy as np
import matplotlib.pyplot as plt

# Define the parameters
a = 2
b = 5
epsilon = 0.1

# Define the loss function L(x) and its derivative
def L(x, a, b, epsilon):
    if x < a:
        return (x - a)**2 / (2 * epsilon)
    elif x > b:
        return (x - b)**2 / (2 * epsilon)
    else:
        return 0

def dL_dx(x, a, b, epsilon):
    if x < a:
        return (x - a) / epsilon
    elif x > b:
        return (x - b) / epsilon
    else:
        return 0

# Generate x values
x_values = np.linspace(0, 7, 500)
# Compute L(x) and its derivative for all x values
y_values = np.array([L(x, a, b, epsilon) for x in x_values])
dy_values = np.array([dL_dx(x, a, b, epsilon) for x in x_values])

# Plot the function and its derivative
plt.figure(figsize=(10, 6))
plt.subplot(2, 1, 1)
plt.plot(x_values, y_values, label=f'L(x) with a={a}, b={b}, epsilon={epsilon}')
plt.axvline(a, color='red', linestyle='--', label='a')
plt.axvline(b, color='green', linestyle='--', label='b')
plt.xlabel('x')
plt.ylabel('L(x)')
plt.title('Loss Function L(x)')
plt.legend()
plt.grid(True)

plt.subplot(2, 1, 2)
plt.plot(x_values, dy_values, label=f'dL/dx with a={a}, b={b}, epsilon={epsilon}', color='orange')
plt.axvline(a, color='red', linestyle='--', label='a')
plt.axvline(b, color='green', linestyle='--', label='b')
plt.xlabel('x')
plt.ylabel("L'(x)")
plt.title('Derivative of Loss Function L(x)')
plt.legend()
plt.grid(True)

plt.tight_layout()
plt.show()

max 损失函数

点击查看代码
import numpy as np
import matplotlib.pyplot as plt

# Define the parameters
k = 10
a = lambda x: x - 2
b = lambda x: -x + 5
c = lambda x: np.sin(x)
d = lambda x: 0.5 * x

# Define the smoothed max function and its derivative
def smooth_max(x, k):
    exp_terms = np.exp(k * np.array([a(x), b(x), c(x), d(x)]))
    return (1/k) * np.log(np.sum(exp_terms))

def dsmooth_max_dx(x, k):
    exp_terms = np.exp(k * np.array([a(x), b(x), c(x), d(x)]))
    exp_sum = np.sum(exp_terms)
    da_dx = 1
    db_dx = -1
    dc_dx = np.cos(x)
    dd_dx = 0.5
    derivs = np.array([da_dx, db_dx, dc_dx, dd_dx])
    return np.sum((exp_terms / exp_sum) * derivs)

# Generate x values
x_values = np.linspace(0, 7, 500)
# Compute smooth_max(x) and its derivative for all x values
y_values = np.array([smooth_max(x, k) for x in x_values])
dy_values = np.array([dsmooth_max_dx(x, k) for x in x_values])

# Plot the function and its derivative
plt.figure(figsize=(10, 6))
plt.subplot(2, 1, 1)
plt.plot(x_values, y_values, label=f'smooth_max(x) with k={k}')
plt.xlabel('x')
plt.ylabel('smooth_max(x)')
plt.title('Smoothed Max Function')
plt.legend()
plt.grid(True)

plt.subplot(2, 1, 2)
plt.plot(x_values, dy_values, label=f'd(smooth_max)/dx with k={k}', color='orange')
plt.xlabel('x')
plt.ylabel("d(smooth_max)/dx")
plt.title('Derivative of Smoothed Max Function')
plt.legend()
plt.grid(True)

plt.tight_layout()
plt.show()

标签:plt,函数,epsilon,损失,特殊,values,dx,max,np
From: https://www.cnblogs.com/long5683/p/18282669

相关文章

  • Cesium常见设置视角所用到函数
     1.左键拾取经纬度坐标consthandler=newCesium.ScreenSpaceEventHandler(viewer.canvas)//监听鼠标点击事件handler.setInputAction(function(click){//使用pick函数获取点击位置的实际位置varcartesian=viewer.scene.pickPositi......
  • STM32F407如何点亮一个呼吸灯(库函数)
    /*********************************************************************************@filemain.c*@author*@version*@date2024/07/03*@brief实现利用基本定时器TIM14实现定时10ms,每隔10ms从灭到亮逐渐变亮,再隔10ms从 亮到......
  • 关于自定义unordered_set\unordered_map中Hash和KeyEqual:函数对象和lambda表达式简单
    以unordered_set为例,首先在cppreference中查看其模板定义:可以看到Hash类默认是std::hash<Key,KeyEqual类似,本文将Hash以函数对象写出,将KeyEqual以lambda写出。classhashvec{ public: size_toperator()(constvector<int>&vec)const{ returnhash<int>()(vec[0])+hash......
  • 解析Kotlin中扩展函数与扩展属性【笔记摘要】
    1.扩展函数1.1作用域:扩展函数写的位置不同,作用域就也不同扩展函数可以写成顶层函数(Top-levelFunction),此时它只属于它所在的package。这样你就能在任何类里使用它:packagecom.rengwuxianfunString.method1(i:Int){...}..."rengwuxian".method1(1)扩展函数......
  • Nuxt3 的生命周期和钩子函数(九)
    title:Nuxt3的生命周期和钩子函数(九)date:2024/7/3updated:2024/7/3author:cmdragonexcerpt:摘要:本文介绍了Nuxt3中与Vite相关的五个生命周期钩子,包括vite:extend、vite:extendConfig、vite:configResolved、vite:serverCreated和vite:compiled,展示了如何在每个钩子中......
  • 复数与复变函数选题
    【参考】《复变函数论》钟玉泉编《复变函数论学习指导书》钟玉泉编......
  • VBA: 过程和函数
    过程(sub)无参数过程SubSayHello()Msgbox"HelloWorld"EndSub有参数过程'声明一个过程SubSayHello(nameAsString)Msgbox"Hello"&nameEndSub'在另一个过程,调用上述过程,调用时,提供一个实际的name参数SubMyCode()SayHello"World2"......
  • 排序函数
    1.std::sort(不稳定排序,时间复杂度为O(nlogn)) std::vector<int>list;std::sort(list.begin(),list.end());//默认升序std::less<int>();std::sort(list.begin(),list.end(),std::greater<int>());//降序autocmp=[](intx,inty){returnx<y;};std::s......
  • 02-JS函数基础
    01函数中的arguments1.1传多的参数也会存在里面<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1.0"><t......
  • strlen/strcpy/strncpy/strcat/strcmp/memset/memcmp不完成实现(部分函数跑过测试集)
    #include<klib.h>#include<klib-macros.h>#include<stdint.h>#if!defined(__ISA_NATIVE__)||defined(__NATIVE_USE_KLIB__)size_tstrlen(constchar*s){//panic("Notimplemented");assert(s!=NULL);size_tl=0;......