REST APIへの組み込み(Spring Boot等との連携)

Deeplearning4j(DL4J)のモデルをREST APIとして提供し、JavaベースのWebフレームワークであるSpring Bootと連携させることで、モデルをWebサービスとしてデプロイ・実運用することが可能です。以下に、DL4JのモデルをSpring Bootを用いてREST API化する手順を詳しく説明します。


1. 前提条件

  • 学習済みモデル(.zipなど)をModelSerializerで保存済み

  • Java 8以上

  • Spring Bootプロジェクト(MavenまたはGradle)構築済み


2. 依存関係の追加

pom.xmlに以下の依存関係を追加します:

xml
<dependencies> <!-- Spring Boot Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Deeplearning4j Core --> <dependency> <groupId>org.deeplearning4j</groupId> <artifactId>deeplearning4j-core</artifactId> <version>1.0.0</version> </dependency> <!-- ND4J(数値処理ライブラリ) --> <dependency> <groupId>org.nd4j</groupId> <artifactId>nd4j-native-platform</artifactId> <version>1.0.0</version> </dependency> </dependencies>

3. モデルの読み込みクラス

java
@Component public class ModelProvider { private MultiLayerNetwork model; @PostConstruct public void init() throws IOException { File modelFile = new File("model.zip"); this.model = ModelSerializer.restoreMultiLayerNetwork(modelFile); } public MultiLayerNetwork getModel() { return model; } }

4. コントローラクラスの作成(REST APIエンドポイント)

java
@RestController @RequestMapping("/api/predict") public class PredictionController { @Autowired private ModelProvider modelProvider; @PostMapping public ResponseEntity<?> predict(@RequestBody double[] inputArray) { INDArray input = Nd4j.create(inputArray); // 1次元入力(例) input = input.reshape(1, input.length()); // バッチ次元の追加 INDArray output = modelProvider.getModel().output(input); double[] result = output.toDoubleVector(); return ResponseEntity.ok(result); } }

5. 実行方法

通常のSpring Bootアプリケーションとしてmain()を起動します。

java
@SpringBootApplication public class Dl4jApiApplication { public static void main(String[] args) { SpringApplication.run(Dl4jApiApplication.class, args); } }

APIを起動後、例えば次のようなcurlコマンドで推論が可能です:

bash
curl -X POST -H "Content-Type: application/json" \ -d '[0.1, 0.2, 0.3, 0.4]' \ http://localhost:8080/api/predict

6. 本番運用上の注意点

  • 入力検証(バリデーション):異常データを防ぐため、入力長や値域のチェックを行う。

  • 非同期処理:推論処理が重い場合は非同期化やスレッドプール制御の検討。

  • セキュリティ:API認証、CORS制限、通信のHTTPS化など。

  • スケーラビリティ:Spring BootアプリをDocker化し、Kubernetes等でスケール可能にする。


まとめ

Deeplearning4jのモデルは、Spring Bootを用いて容易にREST APIとして提供できます。これにより、Webアプリケーションや外部サービスからの推論要求を受け付け、リアルタイムに応答する機械学習APIを構築できます。本番運用を視野に入れる場合、セキュリティやパフォーマンスの最適化も重要な観点となります。

生成日:2025/05/23