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

如何为MATLAB的ANN模型创建REST API并部署?不使用MATLAB Production Server

可行方案:为MATLAB ANN模型搭建REST API(替代MATLAB Production Server)

除了MATLAB Production Server,以下是几种实用方案,可用于为你的ANN模型搭建REST API,供React应用调用:

1. 利用MATLAB内置HTTP Server搭建API(无需额外授权)

从MATLAB R2020b开始,MATLAB提供原生HTTP服务器功能,可直接编写处理REST请求的逻辑。

实现步骤:

  • 编写请求处理函数annPredict.m,负责解析参数、调用模型并返回结果:
function response = annPredict(request)
    % 解析POST请求的JSON参数
    params = jsondecode(request.Body.Data);
    inputData = params.input;
    
    % 加载预训练的ANN模型(假设已保存为annModel.mat)
    load('annModel.mat');
    % 执行预测
    result = predict(annModel, inputData);
    
    % 构造JSON响应
    response = matlab.net.http.ResponseMessage;
    response.Body = matlab.net.http.MessageBody(jsonencode(struct('result', result)));
    response.StatusCode = matlab.net.http.StatusCode.OK;
    response.HeaderFields = [matlab.net.http.Field('Content-Type', 'application/json')];
end
  • 启动HTTP服务器并注册路由:
server = matlab.net.http.Server;
server.addRoute('/predict', @annPredict, 'POST');
server.start(8080); % 监听本地8080端口
  • React端调用示例(用fetch):
const callAnnModel = async (inputData) => {
  try {
    const response = await fetch('http://你的服务器IP:8080/predict', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ input: inputData })
    });
    const data = await response.json();
    console.log('预测结果:', data.result);
    return data.result;
  } catch (err) {
    console.error('调用失败:', err);
  }
};

2. 导出模型为ONNX格式,用Python搭建API

将MATLAB ANN模型导出为通用ONNX格式,借助Python成熟的Web框架(如FastAPI、Flask)搭建API,部署灵活性更高。

实现步骤:

  • 在MATLAB中导出ONNX模型:
% 假设你的ANN模型对象为annModel
exportONNXNetwork(annModel, 'ann_model.onnx');
  • 用Python加载模型并搭建FastAPI服务:
from fastapi import FastAPI
import onnxruntime as rt
import numpy as np

app = FastAPI()
# 加载ONNX模型
sess = rt.InferenceSession('ann_model.onnx')
input_name = sess.get_inputs()[0].name
output_name = sess.get_outputs()[0].name

@app.post("/predict")
async def predict(input_data: list):
    input_array = np.array(input_data, dtype=np.float32)
    result = sess.run([output_name], {input_name: input_array})[0]
    return {"result": result.tolist()}
  • 启动Python服务:
uvicorn main:app --host 0.0.0.0 --port 8000
  • React端直接请求http://你的服务器IP:8000/predict即可,调用逻辑同方案1。

3. 用MATLAB Compiler生成独立可执行文件,再封装API

将ANN模型的调用逻辑打包为无需MATLAB环境的独立程序,再用Node.js/Python等脚本封装成HTTP接口。

实现步骤:

  • 编写MATLAB命令行脚本ann_predict_script.m,接收命令行参数并输出结果:
% 读取命令行传入的JSON参数
inputArgs = argv;
params = jsondecode(inputArgs{1});
inputData = params.input;

load('annModel.mat');
result = predict(annModel, inputData);

% 输出JSON结果到标准输出
disp(jsonencode(struct('result', result)));
  • 用MATLAB Compiler生成独立可执行文件:
    打开MATLAB Compiler,选择「Standalone Application」,添加脚本和依赖的模型文件,生成对应平台的可执行程序(Windows为exe,Linux/macOS为二进制文件)。
  • 用Node.js封装HTTP接口示例:
const express = require('express');
const { execFileSync } = require('child_process');
const app = express();
app.use(express.json());

app.post('/predict', (req, res) => {
  try {
    const inputJson = JSON.stringify(req.body);
    // 调用生成的可执行文件
    const output = execFileSync('./ann_predict_script', [inputJson], { encoding: 'utf8' });
    const result = JSON.parse(output);
    res.json(result);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(3000, () => console.log('服务运行在3000端口'));
  • React端调用该Node.js服务即可。

4. 使用MATLAB Web App Server部署API(个人版免费)

MATLAB Web App Server个人版免费,可部署MATLAB Web App,并在App中暴露API接口处理请求。

实现步骤:

  • 在App Designer中创建Web App,添加HTTP服务启动和请求处理逻辑:
function startupFcn(app)
    % 启动内置HTTP服务器
    app.Server = matlab.net.http.Server;
    app.Server.addRoute('/predict', @app.handlePredict, 'POST');
    app.Server.start(9000);
end

function response = handlePredict(app, request)
    params = jsondecode(request.Body.Data);
    inputData = params.input;
    load('annModel.mat');
    result = predict(annModel, inputData);
    
    response = matlab.net.http.ResponseMessage;
    response.Body = matlab.net.http.MessageBody(jsonencode(struct('result', result)));
    response.StatusCode = matlab.net.http.StatusCode.OK;
    response.HeaderFields = [matlab.net.http.Field('Content-Type', 'application/json')];
end
  • 将Web App部署到MATLAB Web App Server,启动服务后,React可通过http://服务器IP:9000/predict调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 07:00:57