豆包 Python 和 Java 的 AI 集成及模型转换
Python 和 Java 的 AI 集成及模型转换
一、Python 基础 AI 源码(TensorFlow 实现简单分类模型)
python import tensorflow as tffrom tensorflow.keras
import layers, modelsfrom tensorflow.keras.datasets
import mnistimport numpy as np#
-
数据加载与预处理(x_train, y_train), (x_test, y_test) = mnist.load_data()x_train = x_train.reshape((60000, 28, 28, 1)).astype(‘float32’) / 255x_test = x_test.reshape((10000, 28, 28, 1)).astype(‘float32’) / 255y_train = tf.keras.utils.to_categorical(y_train, 10)y_test = tf.keras.utils.to_categorical(y_test, 10)#
-
构建 CNN 模型model = models.Sequential([ layers.Conv2D(32, (3, 3), activation=‘relu’, input_shape=(28, 28, 1)), layers.MaxPooling2D((2, 2)), layers.Conv2D(64, (3, 3), activation=‘relu’), layers.MaxPooling2D((2, 2)), layers.Conv2D(64, (3, 3), activation=‘relu’), layers.Flatten(), layers.Dense(64, activation=‘relu’), layers.Dense(10, activation=‘softmax’)])#
-
编译与训练model.compile(optimizer=‘adam’, loss=‘categorical_crossentropy’, metrics=[‘accuracy’])history = model.fit(x_train, y_train, epochs=5, batch_size=64, validation_split=0.1)#
-
模型评估test_loss, test_acc = model.evaluate(x_test, y_test)print(f"测试准确率: {test_acc:.4f}")#
-
保存模型model.save(‘mnist_cnn_model.h5’)
二、Java 后端 AI 集成源码(Spring Boot + TensorFlow Java API)
- 依赖配置(pom.xml)xml
< org.springframework.boot spring-boot-starter-web org.tensorflow tensorflow 2.15.0 javax.imageio imageio-core 3.1.4 </
- AI 模型调用服务(MnistService.java)java
import org.springframework.stereotype.Service;
import org.tensorflow.Graph;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
import org.tensorflow.TensorFlow;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.FloatBuffer;
@Service
public class MnistService { private final Graph graph; private final Session session; // 初始化模型(加载预训练的 .h5 或 .pb 模型) public MnistService() throws IOException { // 加载模型文件(需先将 Python 训练的 .h5 转为 .pb 格式) graph = new Graph(); graph.importGraphDef(TensorFlow.loadGraphDef(new File(“mnist_cnn_model.pb”).toPath())); session = new Session(graph); } // 图像预测方法 public int predictImage(File imageFile) throws IOException { // 1. 图像预处理(转为 28x28 灰度图) BufferedImage image = ImageIO.read(imageFile); BufferedImage grayImage = new BufferedImage(28, 28, BufferedImage.TYPE_BYTE_GRAY); grayImage.getGraphics().drawImage(image, 0, 0, 28, 28, null); // 2. 转为 float 数组并归一化 float[] inputData = new float[28 * 28]; for (int i = 0; i < 28; i++) { for (int j = 0; j < 28; j++) { int pixel = grayImage.getRGB(j, i); inputData[i * 28 + j] = (255 - (pixel & 0xFF)) / 255.0f; // 反色(MNIST 背景为黑色) } } // 3. 构建输入 Tensor Tensor<?> inputTensor = Tensor.create( new long[]{1, 28, 28, 1}, FloatBuffer.wrap(inputData) ); // 4. 执行预测(需匹配模型输入输出节点名) Tensor<?> outputTensor = session.runner() .feed(“conv2d_input”, inputTensor) .fetch(“dense_1/Softmax”) .run() .get(0); // 5. 解析输出结果 float[] output = new float[10]; outputTensor.writeTo(FloatBuffer.wrap(output)); outputTensor.close(); inputTensor.close(); // 6. 返回概率最大的类别 int result = 0; float maxProb = 0; for (int i = 0; i < 10; i++) { if (output[i] > maxProb) { maxProb = output[i]; result = i; } } return result; }}
- 接口控制器(MnistController.java)java
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.multipart.MultipartFile;import java.io.File;import java.io.IOException;
@RestController
public class MnistController { @Autowired private MnistService mnistService; @PostMapping("/predict-digit") public String predictDigit(@RequestParam(“file”) MultipartFile file) throws IOException { // 临时保存上传文件 File tempFile = File.createTempFile(“mnist-”, “.png”); file.transferTo(tempFile); // 调用 AI 服务预测 int result = mnistService.predictImage(tempFile); tempFile.delete(); // 删除临时文件 return "预测数字: " + result; }}
三、关键说明模型格式转换:Python 训练的 .h5 模型需用 tensorflow.python.saved_model.save 转为 .pb 格式,才能被 Java API 加载。依赖注意:TensorFlow Java API 仅支持特定系统(Windows/Linux/macOS),需确保环境匹配。
扩展方向:可集成到微信小程序 / 服务号,通过接口接收前端上传的手写数字图片,返回预测结果。需要我帮你生成 模型格式转换的 Python 脚本,或补充 微信小程序调用该 AI 接口的前端代码 吗?
