Python 实现深度学习模型预测控制--预测模型构建

链接:深度学习模型预测控制  (如果认为有用,动动小手为我点亮github小星星哦),持续更新中……

链接:WangXiaoMingo/TensorDL-MPC: DL-MPC(deep learning model predictive control) is a software toolkit developed based on the Python and TensorFlow frameworks, designed to enhance the performance of traditional Model Predictive Control (MPC) through deep learning technology. This toolkit provides core functionalities such as model training, simulation, parameter optimization. (github.com)icon-default.png?t=O83Ahttps://github.com/WangXiaoMingo/TensorDL-MPC此文档为如何使用深度学习模型预测控制系列文档。

使用 TensorDL-MPC 进行 MPC 控制,包括初始化系统、训练模型、执行 MPC 控制、模拟系统动力学等。

1. 构建模型

方法1:可以直接加载模型进行网络训练。

方法2:同样允许我们自己构建特定模型。使用方法与使用TensorFlow的Keras API构建方式类似,包括Sequential模型、函数式API(Functional API)、以及子类化(Subclassing)方法。这些方法都可以完成从模型构建到训练的整个过程。下面将分别展示这些方式的具体实现。

1.1  使用Sequential模型

import tensorflow as tf
from tensorflow.keras import layers, models

# 使用Sequential API 构建模型
model = models.Sequential([
    layers.Dense(128, activation='relu', input_shape=(784,)),  # 输入层
    layers.Dense(64, activation='relu'),  # 隐藏层
    layers.Dense(10, activation='softmax')  # 输出层
])

# 编译模型
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
model.summary()

1.2  函数式API(Functional API)

函数式API允许创建更复杂的模型结构,例如多输入、多输出或共享层的模型。

from tensorflow.keras import Input, Model

# 使用Functional API 构建模型
inputs = Input(shape=(784,))
x = layers.Dense(128, activation='relu')(inputs)
x = layers.Dense(64, activation='relu')(x)
outputs = layers.Dense(10, activation='softmax')(x)

model = Model(inputs=inputs, outputs=outputs)

# 编译模型
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
model.summary()

也可以自定义类实现模型封装,如:

# dlmpc/models/BPMM.py

import tensorflow as tf
from tensorflow import keras
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from layers.normlization import MinMaxNormalization
import numpy as np
import random
import os


# 固定随机数种子
random_seed = 42
random.seed(random_seed)  # set random seed for python
np.random.seed(random_seed)  # set random seed for numpy
tf.random.set_seed(random_seed)  # set random seed for tensorflow-cpu
os.environ['TF_DETERMINISTIC_OPS'] = '1' # set random seed for tensorflow-gpu
# warnings.filterwarnings("ignore")



class MultiBPNet():
    def __init__(self, hidden_blocks=3, dim_u=1, dim_x=3, dim_y=1, feature_range=(0, 1), min_val=None, max_val=None,
                     use_mask=False):
        """
        初始化函数

        参数:
        hidden_blocks (int): 隐藏层的数量,默认为3。必须为整数。
        dim_u (int): 输入的维度,默认为1。必须为整数。
        dim_x (int): 输出的维度,默认为3。必须为整数。
        dim_y (int): 输出的维度,默认为1。必须为整数。
        feature_range (tuple): 特征的范围,默认为(0, 1)。必须为长度为2的元组。
        min_val (list or tuple): 输入和输出的最小值,默认为None。如果提供,必须为长度为2的列表或元组。
        max_val (list or tuple): 输入和输出的最大值,默认为None。如果提供,必须为长度为2的列表或元组。
        use_mask (bool): 是否启用掩码,默认为False。
        """

        if not isinstance(hidden_blocks, int):
            raise ValueError("hidden_blocks must be an integer")
        if not isinstance(dim_u, int):
            raise ValueError("dim_u must be an integer")
        if not isinstance(dim_x, int):
            raise ValueError("dim_x must be an integer")

        super().__init__()
        self.nblocks = hidden_blocks
        self.dim_u = dim_u
        self.dim_x = dim_x
        self.dim_y = dim_y
        self.feature_range = feature_range
        self.use_mask = use_mask

        self.min_val_x, self.min_val_u = self._validate_values(min_val)
        self.max_val_x, self.max_val_u = self._validate_values(max_val)

        self.normalization_layer_x = MinMaxNormalization(feature_range=self.feature_range, min_val=self.min_val_x, max_val=self.max_val_x)
        self.normalization_layer_u = MinMaxNormalization(feature_range=self.feature_range, min_val=self.min_val_u, max_val=self.max_val_u)

    def _validate_values(self, values):
        if values is not None:
            if not (isinstance(values, (list, tuple)) and len(values) == 2):
                raise ValueError("values must be a list or tuple of length 2")
            return values[0], values[1]
        return None, None
    def _apply_normalization(self, input_tensor, normalization_layer, min_val, max_val):
        if min_val is not None and max_val is not None:
            return normalization_layer(input_tensor)
        return input_tensor

    def build(self, units=32, time_step = 3 ,u_steps = 1, data_type='1D'):
        # 构建模型,2个输入,分别x和u
        input_x = keras.Input(shape=(time_step,self.dim_x))
        input_u = keras.Input(shape=(u_steps,self.dim_u))

        if self.use_mask:
            input_x = keras.layers.Masking(mask_value=0.0)(input_x)
            input_u = keras.layers.Masking(mask_value=0.0)(input_u)

        norm_x = self._apply_normalization(input_x, self.normalization_layer_x, self.min_val_x, self.max_val_x)
        norm_u = self._apply_normalization(input_u, self.normalization_layer_u, self.min_val_u, self.max_val_u)

        inputs = self._concatenate_inputs(units,norm_x, norm_u, data_type)

        for j in range(self.nblocks):
            x = keras.layers.Dense(units, activation='linear')(inputs)
            inputs = x
        out = keras.layers.Dense(self.dim_y, activation='linear')(x)
        out = out[:, -1]
        model = keras.models.Model(inputs
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值