You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GEKKO多变量深度学习函数逼近、模型保存与动态仿真集成技术咨询

Let's break down your three questions and provide practical, working code examples to solve each one. Also, note that you had a variable name conflict in your original code (you named both the Brain object and your b input variable b), which we've fixed by renaming the Brain object to br.


1. Training a Multivariable GEKKO Deep Learning Model

The core issue in your original code is that you only defined 1 input layer neuron, but your function has 4 input variables (x, a, b, d). You also need to generate a training dataset that includes all combinations of these inputs, not just a single variable.

Here's the corrected approach:

  • Set the input layer size to 4 (one neuron per input variable)
  • Generate a grid of all input combinations to create a comprehensive training dataset
  • Pass the combined input matrix and corresponding output vector to br.learn()
from gekko import brain
import numpy as np
import matplotlib.pyplot as plt

# Initialize brain with correct input size (4 variables: x,a,b,d)
br = brain.Brain(remote=False)
br.input_layer(4)  # Updated from 1 to 4
br.layer(linear=2)
br.layer(tanh=5)
br.layer(linear=2)
br.output_layer(1)

# Generate training data: all combinations of x,a,b,d
x = np.linspace(-2, 2, 20)  # Reduced to 20 points for faster training
a = np.linspace(0, 1, 5)
b = np.linspace(0, 0.5, 5)
d = np.linspace(-1, 0, 5)

# Create grid of all input combinations
X, A, B, D = np.meshgrid(x, a, b, d)
# Reshape into a 2D array where each row is [x_i, a_i, b_i, d_i]
train_inputs = np.vstack([X.ravel(), A.ravel(), B.ravel(), D.ravel()]).T
# Calculate corresponding output values
def function(x_val, a_val, b_val, d_val):
    return 0.0001 * x_val + a_val * b_val * x_val + d_val

train_outputs = function(X, A, B, D).ravel()

# Train the model
br.learn(train_inputs, train_outputs)
print("Model training complete!")

2. Saving the Model and Integrating into GEKKO Dynamic Simulation

Yes, you can save your trained GEKKO Brain model and load it directly into a dynamic simulation (IMODE 4 or 7) without retraining. Here's how:

Step 1: Save the Trained Model

After training, save the model to a file (we'll use trained_model.apm):

# Save the trained model to a file
br.save('trained_model.apm')

Step 2: Load and Integrate into Dynamic Simulation

Load the saved model into a new GEKKO simulation, connect your input parameters/variables, and run the simulation:

from gekko import GEKKO

# Initialize dynamic simulation model
m = GEKKO(remote=False)
m.options.IMODE = 4  # Steady-state dynamic simulation mode

# Load the pre-trained model
m.load('trained_model.apm')

# Define input parameters/variables (can be fixed or time-varying)
x = m.Param(value=0)  # Example fixed input
a = m.Param(value=0.5)
b = m.Param(value=0.25)
d = m.Param(value=-0.5)

# Connect your inputs to the model's input ports
m.Equation(m.inpt[0] == x)
m.Equation(m.inpt[1] == a)
m.Equation(m.inpt[2] == b)
m.Equation(m.inpt[3] == d)

# Access the model's output
y = m.outpt[0]

# Run the simulation
m.solve(disp=False)
print(f"Dynamic Simulation Output: y = {y.value[0]:.4f}")

For time-varying inputs, set x.value = np.linspace(-2,2,100) and switch to IMODE=7 for sequential simulation.


3. Getting Output for Single or Multivariable Inputs

You don't need to construct large arrays for single-point predictions. Just pass a 2D array with one row (your single input set) to br.think(). For convenience, wrap this in a helper function:

# Helper function for single-point prediction
def predict(x_val, a_val, b_val, d_val):
    # Create a 2D array (required by br.think())
    single_input = np.array([[x_val, a_val, b_val, d_val]])
    # Extract the scalar output value
    return br.think(single_input)[0][0]

# Example: Single point prediction
y_pred = predict(x_val=0, a_val=0.5, b_val=0.25, d_val=-0.5)
print(f"Single Point Prediction: y = {y_pred:.4f}")

# Example: Multiple points at once
multi_inputs = np.array([
    [0, 0.5, 0.25, -0.5],
    [1, 1, 0.5, 0],
    [-2, 0, 0, -1]
])
multi_outputs = br.think(multi_inputs)
print("\nMultiple Point Predictions:")
for i, out in enumerate(multi_outputs[0]):
    print(f"Input {i+1}: y = {out:.4f}")

内容的提问来源于stack exchange,提问作者whisper123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 21:44:12