小白友好教程:Xinference部署LSTM,实战股票数据分析与预测

张开发
2026/4/15 3:21:50 15 分钟阅读

分享文章

小白友好教程:Xinference部署LSTM,实战股票数据分析与预测
小白友好教程Xinference部署LSTM实战股票数据分析与预测1. 为什么选择Xinference部署LSTM模型LSTM长短期记忆网络是处理时间序列数据的利器在股票价格预测、销量预测等领域应用广泛。但传统部署方式需要搭建复杂的环境、编写大量服务代码对初学者很不友好。Xinference作为一个开源模型服务平台让LSTM模型的部署变得异常简单。它提供了一键式部署无需配置Python环境或管理依赖统一API接口与LLM相同的调用方式降低学习成本生产级服务内置负载均衡、监控等企业级功能硬件优化自动利用GPU加速计算更重要的是Xinference支持灵活模型Flexible Model可以轻松部署PyTorch、TensorFlow等框架训练的模型。下面我们就从零开始完成一个股票预测LSTM模型的完整部署流程。2. 环境准备与Xinference安装2.1 快速安装Xinference推荐使用Docker方式安装避免环境冲突# 拉取官方镜像CPU版本 docker pull xprobe/xinference:v1.17.1 # 启动服务映射9997端口 docker run -d \ --name xinference-lstm \ -p 9997:9997 \ -v $(pwd)/models:/root/.xinference/models \ xprobe/xinference:v1.17.1 \ xinference-local -H 0.0.0.0验证安装是否成功docker exec xinference-lstm xinference --version # 应输出类似xinference, version 1.17.12.2 准备股票数据我们使用A股市场历史数据作为示例。创建一个data目录存放CSV文件格式如下date,open,high,low,close,volume 2023-01-03,182.30,183.50,181.80,183.10,125432 2023-01-04,183.20,184.60,182.90,184.50,118765 ...3. 构建LSTM预测模型3.1 数据预处理创建preprocess.py处理原始数据import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler def prepare_data(file_path, window_size30, pred_days5): df pd.read_csv(file_path) prices df[close].values.astype(np.float32) # 归一化到0-1范围 scaler MinMaxScaler() scaled scaler.fit_transform(prices.reshape(-1, 1)).flatten() # 创建滑动窗口样本 X, y [], [] for i in range(len(scaled)-window_size-pred_days1): X.append(scaled[i:iwindow_size]) y.append(scaled[iwindow_size:iwindow_sizepred_days]) return np.array(X), np.array(y), scaler # 示例使用 X, y, scaler prepare_data(data/stock.csv) print(f共生成{X.shape[0]}个样本每个样本{X.shape[1]}天数据)3.2 定义LSTM模型创建lstm_model.pyimport torch import torch.nn as nn class StockPredictor(nn.Module): def __init__(self, input_size1, hidden_size64, output_size5): super().__init__() self.lstm nn.LSTM(input_size, hidden_size, batch_firstTrue) self.fc nn.Linear(hidden_size, output_size) def forward(self, x): x x.unsqueeze(-1) # 添加特征维度 out, _ self.lstm(x) out self.fc(out[:, -1, :]) # 取最后一个时间步 return out # 训练代码示例 model StockPredictor() criterion nn.MSELoss() optimizer torch.optim.Adam(model.parameters(), lr0.001) for epoch in range(100): inputs torch.from_numpy(X).float() targets torch.from_numpy(y).float() outputs model(inputs) loss criterion(outputs, targets) optimizer.zero_grad() loss.backward() optimizer.step() if epoch % 10 0: print(fEpoch {epoch}, Loss: {loss.item():.4f}) # 保存模型 torch.save({ model: model.state_dict(), scaler_min: scaler.data_min_[0], scaler_scale: scaler.scale_[0] }, models/stock_lstm.pt)4. 部署模型到Xinference4.1 创建模型描述文件在models目录下创建stock_lstm.json{ model_name: stock-lstm, model_type: flexible, model_description: LSTM股票价格预测模型, model_specs: { model_format: pytorch, model_uri: file:///root/.xinference/models/stock_lstm.py } }4.2 编写推理封装创建models/stock_lstm.pyimport torch import numpy as np class LSTMInference: def __init__(self, model_path): # 加载模型 checkpoint torch.load(model_path, map_locationcpu) self.model StockPredictor() self.model.load_state_dict(checkpoint[model]) self.model.eval() # 加载归一化参数 self.scaler_min checkpoint[scaler_min] self.scaler_scale checkpoint[scaler_scale] def predict(self, input_data): # 输入应为30天的收盘价列表 if len(input_data) ! 30: raise ValueError(需要30天的价格数据) # 归一化 scaled (np.array(input_data) - self.scaler_min) / self.scaler_scale input_tensor torch.tensor(scaled, dtypetorch.float32).unsqueeze(0) # 预测 with torch.no_grad(): pred self.model(input_tensor).numpy()[0] # 反归一化 pred_price pred * self.scaler_scale self.scaler_min return { predictions: pred_price.tolist(), next_day: float(pred_price[0]) } # Xinference要求的接口 model_instance None def get_model(): global model_instance if model_instance is None: model_instance LSTMInference(/root/.xinference/models/stock_lstm.pt) return model_instance def predict(**kwargs): return get_model().predict(kwargs[input_data])4.3 注册并启动模型# 进入容器 docker exec -it xinference-lstm bash # 注册模型 xinference register -n stock-lstm -f /root/.xinference/models/stock_lstm.json # 启动模型 xinference launch --model-name stock-lstm --model-type flexible --model-uid stock-predictor5. 使用模型进行预测5.1 Python客户端调用from xinference.client import Client client Client(http://localhost:9997) model client.get_model(stock-predictor) # 准备最近30天数据 history [182.3, 183.1, 181.9, 184.5, 185.2, 186.7, 185.8, 187.3, 188.1, 187.6, 189.2, 190.5, 189.8, 191.3, 192.7, 191.9, 193.4, 194.2, 193.6, 195.1, 196.3, 195.7, 197.2, 198.5, 197.8, 199.3, 200.1, 199.5, 201.2, 202.4] result model.predict(input_datahistory) print(f明日预测价格: {result[next_day]:.2f}) print(f未来5天预测: {result[predictions]})5.2 HTTP API调用Xinference提供REST API接口curl -X POST \ http://localhost:9997/v1/models/stock-predictor/predict \ -H Content-Type: application/json \ -d {input_data: [182.3,183.1,181.9,184.5,185.2,186.7,185.8,187.3,188.1,187.6,189.2,190.5,189.8,191.3,192.7,191.9,193.4,194.2,193.6,195.1,196.3,195.7,197.2,198.5,197.8,199.3,200.1,199.5,201.2,202.4]}响应示例{ predictions: [203.67,204.89,205.21,206.45,207.12], next_day: 203.67 }6. 总结与进阶建议通过本教程我们完成了使用PyTorch构建LSTM股票预测模型将模型封装为Xinference兼容格式一键部署模型服务通过Python和HTTP两种方式调用进阶建议数据更新定期用新数据重新训练模型特征工程尝试加入交易量、技术指标等更多特征模型集成部署多个模型进行投票预测监控使用Xinference内置的Prometheus指标监控服务健康状态Xinference让传统机器学习模型的部署变得前所未有的简单希望本教程能帮助你快速上手。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。

更多文章