当前位置: 首页 > news >正文

简述7个流行的强化学习算法及代码实现!

目前流行的强化学习算法包括 Q-learning、SARSA、DDPG、A2C、PPO、DQN 和 TRPO。这些算法已被用于在游戏、机器人和决策制定等各种应用中,并且这些流行的算法还在不断发展和改进,本文我们将对其做一个简单的介绍。

1、Q-learning

Q-learning:Q-learning 是一种无模型、非策略的强化学习算法。它使用 Bellman 方程估计最佳动作值函数,该方程迭代地更新给定状态动作对的估计值。Q-learning 以其简单性和处理大型连续状态空间的能力而闻名。

下面是一个使用 Python 实现 Q-learning 的简单示例:

import numpy as np# Define the Q-table and the learning rate
Q = np.zeros((state_space_size, action_space_size))
alpha = 0.1# Define the exploration rate and discount factor
epsilon = 0.1
gamma = 0.99for episode in range(num_episodes):current_state = initial_statewhile not done:# Choose an action using an epsilon-greedy policyif np.random.uniform(0, 1) < epsilon:action = np.random.randint(0, action_space_size)else:action = np.argmax(Q[current_state])# Take the action and observe the next state and rewardnext_state, reward, done = take_action(current_state, action)# Update the Q-table using the Bellman equationQ[current_state, action] = Q[current_state, action] + alpha * (reward + gamma * np.max(Q[next_state]) - Q[current_state, action])current_state = next_state

上面的示例中,state_space_size 和 action_space_size 分别是环境中的状态数和动作数。num_episodes 是要为运行算法的轮次数。initial_state 是环境的起始状态。take_action(current_state, action) 是一个函数,它将当前状态和一个动作作为输入,并返回下一个状态、奖励和一个指示轮次是否完成的布尔值。

在 while 循环中,使用 epsilon-greedy 策略根据当前状态选择一个动作。使用概率 epsilon选择一个随机动作,使用概率 1-epsilon选择对当前状态具有最高 Q 值的动作。

采取行动后,观察下一个状态和奖励,使用Bellman方程更新q。并将当前状态更新为下一个状态。这只是 Q-learning 的一个简单示例,并未考虑 Q-table 的初始化和要解决的问题的具体细节。

2、SARSA

SARSA:SARSA 是一种无模型、基于策略的强化学习算法。它也使用Bellman方程来估计动作价值函数,但它是基于下一个动作的期望值,而不是像 Q-learning 中的最优动作。SARSA 以其处理随机动力学问题的能力而闻名。

import numpy as np# Define the Q-table and the learning rate
Q = np.zeros((state_space_size, action_space_size))
alpha = 0.1# Define the exploration rate and discount factor
epsilon = 0.1
gamma = 0.99for episode in range(num_episodes):current_state = initial_stateaction = epsilon_greedy_policy(epsilon, Q, current_state)while not done:# Take the action and observe the next state and rewardnext_state, reward, done = take_action(current_state, action)# Choose next action using epsilon-greedy policynext_action = epsilon_greedy_policy(epsilon, Q, next_state)# Update the Q-table using the Bellman equationQ[current_state, action] = Q[current_state, action] + alpha * (reward + gamma * Q[next_state, next_action] - Q[current_state, action])current_state = next_stateaction = next_action

state_space_size和action_space_size分别是环境中的状态和操作的数量。num_episodes是您想要运行SARSA算法的轮次数。Initial_state是环境的初始状态。take_action(current_state, action)是一个将当前状态和作为操作输入的函数,并返回下一个状态、奖励和一个指示情节是否完成的布尔值。

在while循环中,使用在单独的函数epsilon_greedy_policy(epsilon, Q, current_state)中定义的epsilon-greedy策略来根据当前状态选择操作。使用概率 epsilon选择一个随机动作,使用概率 1-epsilon对当前状态具有最高 Q 值的动作。

上面与Q-learning相同,但是采取了一个行动后,在观察下一个状态和奖励时它然后使用贪心策略选择下一个行动。并使用Bellman方程更新q表。

3、DDPG

DDPG 是一种用于连续动作空间的无模型、非策略算法。它是一种actor-critic算法,其中actor网络用于选择动作,而critic网络用于评估动作。DDPG 对于机器人控制和其他连续控制任务特别有用。

import numpy as np
from keras.models import Model, Sequential
from keras.layers import Dense, Input
from keras.optimizers import Adam# Define the actor and critic models
actor = Sequential()
actor.add(Dense(32, input_dim=state_space_size, activation='relu'))
actor.add(Dense(32, activation='relu'))
actor.add(Dense(action_space_size, activation='tanh'))
actor.compile(loss='mse', optimizer=Adam(lr=0.001))critic = Sequential()
critic.add(Dense(32, input_dim=state_space_size, activation='relu'))
critic.add(Dense(32, activation='relu'))
critic.add(Dense(1, activation='linear'))
critic.compile(loss='mse', optimizer=Adam(lr=0.001))# Define the replay buffer
replay_buffer = []# Define the exploration noise
exploration_noise = OrnsteinUhlenbeckProcess(size=action_space_size, theta=0.15, mu=0, sigma=0.2)for episode in range(num_episodes):current_state = initial_statewhile not done:# Select an action using the actor model and add exploration noiseaction = actor.predict(current_state)[0] + exploration_noise.sample()action = np.clip(action, -1, 1)# Take the action and observe the next state and rewardnext_state, reward, done = take_action(current_state, action)# Add the experience to the replay bufferreplay_buffer.append((current_state, action, reward, next_state, done))# Sample a batch of experiences from the replay bufferbatch = sample(replay_buffer, batch_size)# Update the critic modelstates = np.array([x[0] for x in batch])actions = np.array([x[1] for x in batch])rewards = np.array([x[2] for x in batch])next_states = np.array([x[3] for x in batch])target_q_values = rewards + gamma * critic.predict(next_states)critic.train_on_batch(states, target_q_values)# Update the actor modelaction_gradients = np.array(critic.get_gradients(states, actions))actor.train_on_batch(states, action_gradients)current_state = next_state

在本例中,state_space_size和action_space_size分别是环境中的状态和操作的数量。num_episodes是轮次数。Initial_state是环境的初始状态。Take_action (current_state, action)是一个函数,它接受当前状态和操作作为输入,并返回下一个操作。

4、A2C

A2C(Advantage Actor-Critic)是一种有策略的actor-critic算法,它使用Advantage函数来更新策略。该算法实现简单,可以处理离散和连续的动作空间。

import numpy as np
from keras.models import Model, Sequential
from keras.layers import Dense, Input
from keras.optimizers import Adam
from keras.utils import to_categorical# Define the actor and critic models
state_input = Input(shape=(state_space_size,))
actor = Dense(32, activation='relu')(state_input)
actor = Dense(32, activation='relu')(actor)
actor = Dense(action_space_size, activation='softmax')(actor)
actor_model = Model(inputs=state_input, outputs=actor)
actor_model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=0.001))state_input = Input(shape=(state_space_size,))
critic = Dense(32, activation='relu')(state_input)
critic = Dense(32, activation='relu')(critic)
critic = Dense(1, activation='linear')(critic)
critic_model = Model(inputs=state_input, outputs=critic)
critic_model.compile(loss='mse', optimizer=Adam(lr=0.001))for episode in range(num_episodes):current_state = initial_statedone = Falsewhile not done:# Select an action using the actor model and add exploration noiseaction_probs = actor_model.predict(np.array([current_state]))[0]action = np.random.choice(range(action_space_size), p=action_probs)# Take the action and observe the next state and rewardnext_state, reward, done = take_action(current_state, action)# Calculate the advantagetarget_value = critic_model.predict(np.array([next_state]))[0][0]advantage = reward + gamma * target_value - critic_model.predict(np.array([current_state]))[0][0]# Update the actor modelaction_one_hot = to_categorical(action, action_space_size)actor_model.train_on_batch(np.array([current_state]), advantage * action_one_hot)# Update the critic modelcritic_model.train_on_batch(np.array([current_state]), reward + gamma * target_value)current_state = next_state

在这个例子中,actor模型是一个神经网络,它有2个隐藏层,每个隐藏层有32个神经元,具有relu激活函数,输出层具有softmax激活函数。critic模型也是一个神经网络,它有2个隐含层,每层32个神经元,具有relu激活函数,输出层具有线性激活函数。

使用分类交叉熵损失函数训练actor模型,使用均方误差损失函数训练critic模型。动作是根据actor模型预测选择的,并添加了用于探索的噪声。

5、PPO

PPO(Proximal Policy Optimization)是一种策略算法,它使用信任域优化的方法来更新策略。它在具有高维观察和连续动作空间的环境中特别有用。PPO 以其稳定性和高样品效率而著称。

import numpy as np
from keras.models import Model, Sequential
from keras.layers import Dense, Input
from keras.optimizers import Adam# Define the policy model
state_input = Input(shape=(state_space_size,))
policy = Dense(32, activation='relu')(state_input)
policy = Dense(32, activation='relu')(policy)
policy = Dense(action_space_size, activation='softmax')(policy)
policy_model = Model(inputs=state_input, outputs=policy)# Define the value model
value_model = Model(inputs=state_input, outputs=Dense(1, activation='linear')(policy))# Define the optimizer
optimizer = Adam(lr=0.001)for episode in range(num_episodes):current_state = initial_statewhile not done:# Select an action using the policy modelaction_probs = policy_model.predict(np.array([current_state]))[0]action = np.random.choice(range(action_space_size), p=action_probs)# Take the action and observe the next state and rewardnext_state, reward, done = take_action(current_state, action)# Calculate the advantagetarget_value = value_model.predict(np.array([next_state]))[0][0]advantage = reward + gamma * target_value - value_model.predict(np.array([current_state]))[0][0]# Calculate the old and new policy probabilitiesold_policy_prob = action_probs[action]new_policy_prob = policy_model.predict(np.array([next_state]))[0][action]# Calculate the ratio and the surrogate lossratio = new_policy_prob / old_policy_probsurrogate_loss = np.minimum(ratio * advantage, np.clip(ratio, 1 - epsilon, 1 + epsilon) * advantage)# Update the policy and value modelspolicy_model.trainable_weights = value_model.trainable_weightspolicy_model.compile(optimizer=optimizer, loss=-surrogate_loss)policy_model.train_on_batch(np.array([current_state]), np.array([action_one_hot]))value_model.train_on_batch(np.array([current_state]), reward + gamma * target_value)current_state = next_state

6、DQN

DQN(深度 Q 网络)是一种无模型、非策略算法,它使用神经网络来逼近 Q 函数。DQN 特别适用于 Atari 游戏和其他类似问题,其中状态空间是高维的,并使用神经网络近似 Q 函数。

import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Input
from keras.optimizers import Adam
from collections import deque# Define the Q-network model
model = Sequential()
model.add(Dense(32, input_dim=state_space_size, activation='relu'))
model.add(Dense(32, activation='relu'))
model.add(Dense(action_space_size, activation='linear'))
model.compile(loss='mse', optimizer=Adam(lr=0.001))# Define the replay buffer
replay_buffer = deque(maxlen=replay_buffer_size)for episode in range(num_episodes):current_state = initial_statewhile not done:# Select an action using an epsilon-greedy policyif np.random.rand() < epsilon:action = np.random.randint(0, action_space_size)else:action = np.argmax(model.predict(np.array([current_state]))[0])# Take the action and observe the next state and rewardnext_state, reward, done = take_action(current_state, action)# Add the experience to the replay bufferreplay_buffer.append((current_state, action, reward, next_state, done))# Sample a batch of experiences from the replay bufferbatch = random.sample(replay_buffer, batch_size)# Prepare the inputs and targets for the Q-networkinputs = np.array([x[0] for x in batch])targets = model.predict(inputs)for i, (state, action, reward, next_state, done) in enumerate(batch):if done:targets[i, action] = rewardelse:targets[i, action] = reward + gamma * np.max(model.predict(np.array([next_state]))[0])# Update the Q-networkmodel.train_on_batch(inputs, targets)current_state = next_state

上面的代码,Q-network有2个隐藏层,每个隐藏层有32个神经元,使用relu激活函数。该网络使用均方误差损失函数和Adam优化器进行训练。

7、TRPO

TRPO (Trust Region Policy Optimization)是一种无模型的策略算法,它使用信任域优化方法来更新策略。它在具有高维观察和连续动作空间的环境中特别有用。

TRPO 是一个复杂的算法,需要多个步骤和组件来实现。TRPO不是用几行代码就能实现的简单算法。

所以我们这里使用实现了TRPO的现有库,例如OpenAI Baselines,它提供了包括TRPO在内的各种预先实现的强化学习算法,。

要在OpenAI Baselines中使用TRPO,我们需要安装:

pip install baselines

然后可以使用baselines库中的trpo_mpi模块在你的环境中训练TRPO代理,这里有一个简单的例子:

import gym
from baselines.common.vec_env.dummy_vec_env import DummyVecEnv
from baselines.trpo_mpi import trpo_mpi# Initialize the environment
env = gym.make("CartPole-v1")
env = DummyVecEnv([lambda: env])# Define the policy network
policy_fn = mlp_policy# Train the TRPO model
model = trpo_mpi.learn(env, policy_fn, max_iters=1000)

我们使用Gym库初始化环境。然后定义策略网络,并调用TRPO模块中的learn()函数来训练模型。

还有许多其他库也提供了TRPO的实现,例如TensorFlow、PyTorch和RLLib。下面时一个使用TF 2.0实现的样例

import tensorflow as tf
import gym# Define the policy network
class PolicyNetwork(tf.keras.Model):def __init__(self):super(PolicyNetwork, self).__init__()self.dense1 = tf.keras.layers.Dense(16, activation='relu')self.dense2 = tf.keras.layers.Dense(16, activation='relu')self.dense3 = tf.keras.layers.Dense(1, activation='sigmoid')def call(self, inputs):x = self.dense1(inputs)x = self.dense2(x)x = self.dense3(x)return x# Initialize the environment
env = gym.make("CartPole-v1")# Initialize the policy network
policy_network = PolicyNetwork()# Define the optimizer
optimizer = tf.optimizers.Adam()# Define the loss function
loss_fn = tf.losses.BinaryCrossentropy()# Set the maximum number of iterations
max_iters = 1000# Start the training loop
for i in range(max_iters):# Sample an action from the policy networkaction = tf.squeeze(tf.random.categorical(policy_network(observation), 1))# Take a step in the environmentobservation, reward, done, _ = env.step(action)with tf.GradientTape() as tape:# Compute the lossloss = loss_fn(reward, policy_network(observation))# Compute the gradientsgrads = tape.gradient(loss, policy_network.trainable_variables)# Perform the update stepoptimizer.apply_gradients(zip(grads, policy_network.trainable_variables))if done:# Reset the environmentobservation = env.reset()

在这个例子中,我们首先使用TensorFlow的Keras API定义一个策略网络。然后使用Gym库和策略网络初始化环境。然后定义用于训练策略网络的优化器和损失函数。

在训练循环中,从策略网络中采样一个动作,在环境中前进一步,然后使用TensorFlow的GradientTape计算损失和梯度。然后我们使用优化器执行更新步骤。

这是一个简单的例子,只展示了如何在TensorFlow 2.0中实现TRPO。TRPO是一个非常复杂的算法,这个例子没有涵盖所有的细节,但它是试验TRPO的一个很好的起点。

总结

以上就是我们总结的7个常用的强化学习算法,这些算法并不相互排斥,通常与其他技术(如值函数逼近、基于模型的方法和集成方法)结合使用,可以获得更好的结果。

相关文章:

简述7个流行的强化学习算法及代码实现!

目前流行的强化学习算法包括 Q-learning、SARSA、DDPG、A2C、PPO、DQN 和 TRPO。这些算法已被用于在游戏、机器人和决策制定等各种应用中&#xff0c;并且这些流行的算法还在不断发展和改进&#xff0c;本文我们将对其做一个简单的介绍。1、Q-learningQ-learning&#xff1a;Q-…...

朗润国际期货招商:地方政府工作报告中对于促进消费

地方政府工作报告中对于促进消费 北京&#xff1a;把恢复和扩大消费摆在优先位置。加紧推进国际消费中心城市建设、深化商圈改造提升行动、统筹推进物流基地规划建设&#xff0c;强化新消费地标载体建设、试点建设80个“一刻钟便民生活圈”&#xff0c;提高生活性服务重品质。…...

前端性能优化的一些技巧(90% chatGpt生成)

终于弄好了chatGpt的账号&#xff0c;赶紧来体验一波。先来一波结论&#xff0c;这篇文章的主要内容来源&#xff0c;90%是用chatGpt生成的。先上chatGpt的生成的结果&#xff1a;作为一名懒惰的程序员&#xff0c;chatGpt会帮助我变得更懒...&#xff0c;好了下面开始文章的正…...

[软件工程导论(第六版)]第8章 维护(复习笔记)

文章目录8.1 软件维护的定义8.2 软件维护的特点8.3 软件维护过程8.4 软件的可维护性8.5 预防性维护8.6 软件再工程过程维护的基本任务&#xff1a;保证软件在一个相当长的时期能够正常运行软件工程的主要目的就是要提高软件的可维护性&#xff0c;减少软件维护所需要的工作量&a…...

Python - 绘制人体生物节律

文章目录项目说明关于人体生物节律用到的技术代码实现获取每月有多少天计算每天到生日过了多少天计算节律绘图结果项目说明 这里仿照 http://www.4qx.net/The_Human_Body_Clock.php 做一个人体生物节律的计算和展示 关于人体生物节律 百度/维基百科 解释 https://zh.wikiped…...

【NVMEM子系统】二、NVMEM驱动框架

个人主页&#xff1a;董哥聊技术我是董哥&#xff0c;嵌入式领域新星创作者创作理念&#xff1a;专注分享高质量嵌入式文章&#xff0c;让大家读有所得&#xff01;文章目录1、前言2、驱动框架3、源码目录结构4、用户空间下的目录结构1、前言 NVMEM SUBSYSTEM&#xff0c;该子系…...

小波神经网络(WNN)的实现(Python,附源码及数据集)

文章目录一、理论基础1、小波神经网络结构2、前向传播过程3、反向传播过程4、建模步骤二、小波神经网络的实现1、训练过程&#xff08;WNN.py&#xff09;2、测试过程&#xff08;test.py&#xff09;3、测试结果4、参考源码及实验数据集一、理论基础 小波神经网络&#xff08…...

商标干货!所有企业都值得收藏!

商标&#xff0c;是用于识别和区分不同商品或服务来源的标志&#xff0c;代表了企业的产品质量和服务保证&#xff0c;可以说&#xff0c;商标承载了一个企业的信誉&#xff0c;是企业参与市场竞争的重要工具&#xff0c;对于企业及其产品的重要性不言而喻。 根据《商标法》四十…...

4次迭代,让我的 Client 优化 100倍!泄漏一个 人人可用的极品方案!

4次迭代&#xff0c;让我的HttpClient提速100倍 在大家的生产项目中&#xff0c;经常需要通过Client组件&#xff08;HttpClient/OkHttp/JDK Connection)调用第三方接口。 尼恩的一个生产项目也不例外。 在一个高并发的中台生产项目中。有一个比较特殊的请求&#xff0c;一次…...

并查集(高级数据结构)-蓝桥杯

一、并查集并查集(Disioint Set)&#xff1a;一种非常精巧而实用的数据结构用于处理不相交集合的合并问题。用于处理不相交集合的合并问题。经典应用&#xff1a;连通子图。最小生成树Kruskal算法。最近公共祖先。二、应用场景有n个人&#xff0c;他们属于不同的帮派。 已知这些…...

你是真的“C”——C语言详解求两个正数最小公倍数的3种境界

C语言详解求两个正数最小公倍数的3种境界~&#x1f60e;前言&#x1f64c;必备小知识~&#x1f618;求最小公倍数境界1~ &#x1f60a;求最小公倍数境界2~ &#x1f60a;求最小公倍数境界3~ &#x1f60a;总结撒花&#x1f49e;博客昵称&#xff1a;博客小梦&#x1f60a; 最喜…...

【java】Spring Cloud --Feign Client超时时间配置以及单独给某接口设置超时时间方法

文章目录feign配置&#xff08;最常用&#xff09;ribbon配置hystrix配置单独给某接口设置超时时间FeignClient面对服务级有三种超时时间配置feign配置&#xff08;最常用&#xff09; feign:sentinel:enabled: trueclient:config:default://全部服务配置connectTimeout: 5000…...

spark代码

RDD Tom,DataBase,80 Tom,Algorithm,50 Tom,DataStructure,60 Jim,DataBase,90 Jim,Algorithm,60 Jim,DataStructure,80 该系总共有多少学生&#xff1b; val lines sc.textFile("file:///usr/local/spark/sparksqldata/Data01.txt") val par lines.map(ro…...

利用OpenCV的函数equalizeHist()对图像作直方图均衡化处理

如果一幅图像的灰度值集中在某个比较窄的区域&#xff0c;则图像的对比度会显得比较小&#xff0c;不便于对图像的分析和处理。 图像的直方图均衡化可以实现将原图像的灰度值范围扩大&#xff0c;这样图像的对比度就得到了提高&#xff0c;从而方便对图像进行后续的分析和处理…...

星河智联Android开发

背景&#xff1a;朋友内推&#xff0c;过了一周约面。本人 2019年毕业 20230208一面 1.自我介绍 2.为啥换工作 3.项目经历&#xff08;中控面板、智能音箱、语音问的比较细&#xff09; 4.问题 Handler机制原理&#xff1f;了解同步和异步消息吗&#xff1f;View事件分发…...

【C++】关联式容器——map和set的使用

文章目录一、关联式容器二、键值对三、树形结构的关联式容器1.set2.multiset3.map4.multimap四、题目练习一、关联式容器 序列式容器&#x1f4d5;:已经接触过STL中的部分容器&#xff0c;比如&#xff1a;vector、list、deque、forward_list(C11)等&#xff0c;这些容器统称为…...

Promise的实现原理

作用&#xff1a;异步问题同步化解决方案&#xff0c;解决回调地狱、链式操作原理&#xff1a; 状态&#xff1a;pending、fufilled reject构造函数传入一个函数&#xff0c;resolve进入then&#xff0c;reject进入catch静态方法&#xff1a;resolve reject all any react ne…...

【MFC】数据库操作——ODBC(20)

ODBC:开放式数据库连接&#xff0c;是为解决异构数据库&#xff08;不同数据库采用的数据存储方法不同&#xff09;共享而产生的。ODBC API相对来说非常复杂&#xff0c;这里介绍MFC的ODBC类。 添加ODBC用户DSN 首先&#xff0c;在计算机中添加用户DSN&#xff1a;(WIN10下&a…...

旺店通与金蝶云星空对接集成采购入库单接口

旺店通旗舰奇门与金蝶云星空对接集成采购入库单查询连通销售退货新增V1(12-采购入库单集成方案-P)数据源系统:旺店通旗舰奇门旺店通是北京掌上先机网络科技有限公司旗下品牌&#xff0c;国内的零售云服务提供商&#xff0c;基于云计算SaaS服务模式&#xff0c;以体系化解决方案…...

Linux基础-学会使用命令帮助

概述使用 whatis使用 man查看命令程序路径 which总结参考资料概述Linux 命令及其参数繁多&#xff0c;大多数人都是无法记住全部功能和具体参数意思的。在 linux 终端&#xff0c;面对命令不知道怎么用&#xff0c;或不记得命令的拼写及参数时&#xff0c;我们需要求助于系统的…...

基于大模型的 UI 自动化系统

基于大模型的 UI 自动化系统 下面是一个完整的 Python 系统,利用大模型实现智能 UI 自动化,结合计算机视觉和自然语言处理技术,实现"看屏操作"的能力。 系统架构设计 #mermaid-svg-2gn2GRvh5WCP2ktF {font-family:"trebuchet ms",verdana,arial,sans-…...

RocketMQ延迟消息机制

两种延迟消息 RocketMQ中提供了两种延迟消息机制 指定固定的延迟级别 通过在Message中设定一个MessageDelayLevel参数&#xff0c;对应18个预设的延迟级别指定时间点的延迟级别 通过在Message中设定一个DeliverTimeMS指定一个Long类型表示的具体时间点。到了时间点后&#xf…...

镜像里切换为普通用户

如果你登录远程虚拟机默认就是 root 用户&#xff0c;但你不希望用 root 权限运行 ns-3&#xff08;这是对的&#xff0c;ns3 工具会拒绝 root&#xff09;&#xff0c;你可以按以下方法创建一个 非 root 用户账号 并切换到它运行 ns-3。 一次性解决方案&#xff1a;创建非 roo…...

Springcloud:Eureka 高可用集群搭建实战(服务注册与发现的底层原理与避坑指南)

引言&#xff1a;为什么 Eureka 依然是存量系统的核心&#xff1f; 尽管 Nacos 等新注册中心崛起&#xff0c;但金融、电力等保守行业仍有大量系统运行在 Eureka 上。理解其高可用设计与自我保护机制&#xff0c;是保障分布式系统稳定的必修课。本文将手把手带你搭建生产级 Eur…...

SpringCloudGateway 自定义局部过滤器

场景&#xff1a; 将所有请求转化为同一路径请求&#xff08;方便穿网配置&#xff09;在请求头内标识原来路径&#xff0c;然后在将请求分发给不同服务 AllToOneGatewayFilterFactory import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; impor…...

Python基于历史模拟方法实现投资组合风险管理的VaR与ES模型项目实战

说明&#xff1a;这是一个机器学习实战项目&#xff08;附带数据代码文档&#xff09;&#xff0c;如需数据代码文档可以直接到文章最后关注获取。 1.项目背景 在金融市场日益复杂和波动加剧的背景下&#xff0c;风险管理成为金融机构和个人投资者关注的核心议题之一。VaR&…...

使用LangGraph和LangSmith构建多智能体人工智能系统

现在&#xff0c;通过组合几个较小的子智能体来创建一个强大的人工智能智能体正成为一种趋势。但这也带来了一些挑战&#xff0c;比如减少幻觉、管理对话流程、在测试期间留意智能体的工作方式、允许人工介入以及评估其性能。你需要进行大量的反复试验。 在这篇博客〔原作者&a…...

【Nginx】使用 Nginx+Lua 实现基于 IP 的访问频率限制

使用 NginxLua 实现基于 IP 的访问频率限制 在高并发场景下&#xff0c;限制某个 IP 的访问频率是非常重要的&#xff0c;可以有效防止恶意攻击或错误配置导致的服务宕机。以下是一个详细的实现方案&#xff0c;使用 Nginx 和 Lua 脚本结合 Redis 来实现基于 IP 的访问频率限制…...

django blank 与 null的区别

1.blank blank控制表单验证时是否允许字段为空 2.null null控制数据库层面是否为空 但是&#xff0c;要注意以下几点&#xff1a; Django的表单验证与null无关&#xff1a;null参数控制的是数据库层面字段是否可以为NULL&#xff0c;而blank参数控制的是Django表单验证时字…...

数据库——redis

一、Redis 介绍 1. 概述 Redis&#xff08;Remote Dictionary Server&#xff09;是一个开源的、高性能的内存键值数据库系统&#xff0c;具有以下核心特点&#xff1a; 内存存储架构&#xff1a;数据主要存储在内存中&#xff0c;提供微秒级的读写响应 多数据结构支持&…...