赞
踩
DeepLearning4J (DL4J) 是一个基于 Java 的神经网络工具包,用于构建、训练和部署神经网络。DL4J 与 Hadoop 和Spark集成,支持分布式 CPU 和 GPU,专为商业环境而设计,而非研究工具用途。Skymind是 DL4J 的商业支持组织。Deeplearning4j 拥有先进的技术,旨在实现即插即用,有更多预设可供使用,避免冗余配置,即使非企业也可以快速进行原型设计。DL4J 还可以进行大规模定制。DL4J 在 Apache 2.0 许可下获得许可,所有基于它的衍生作品均为衍生作品。
Deeplearning4j 包括分布式、多线程深度学习框架,以及常见的单线程深度学习框架。训练过程在集群中进行,这意味着 Deeplearning4j 可以快速处理大量数据。神经网络可以通过 [迭代简化] 并行训练,并且可以与 Java、Scala和Clojure并行使用,全部兼容。Deeplearning4j 能够作为开放堆栈中的模块组件,使其成为同类中第一个面向微服务架构的深度学习框架。
示例:使用 Spring Boot、Java 和 DL4J 的贷款审批推荐系统
您想要在“贷款审批”应用程序中构建一个微服务,根据历史数据建议是否批准或拒绝贷款申请。该建议基于使用 DL4J 训练的机器学习模型。
创建一个 CSV 文件 (loan_data.csv),其中包含 credit_score、income、loan_amount、employment_status 和 label 等列(其中 label 为 1 表示贷款已获批准,为 0 表示贷款已拒绝)。
- csv file
-
- credit_score,income,loan_amount,employment_status,label
- 700,50000,20000,1,1
- 650,45000,15000,1,1
- 600,30000,25000,0,0
- 720,60000,22000,1,1
- 580,29000,18000,0,0
pom.xml
Maven 或build.gradle
Gradle 中):- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <groupId>com.example</groupId>
- <artifactId>loan-approval</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>jar</packaging>
-
- <name>loan-approval</name>
- <description>Loan Approval Recommendation System using DL4J</description>
-
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.7.1</version>
- <relativePath/> <!-- lookup parent from repository -->
- </parent>
-
- <properties>
- <java.version>11</java.version>
- <dl4j.version>1.0.0-M1.1</dl4j.version>
- </properties>
-
- <dependencies>
-
- <!-- Spring Boot Starter Web -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
-
- <!-- Deeplearning4j Dependencies -->
- <dependency>
- <groupId>org.deeplearning4j</groupId>
- <artifactId>deeplearning4j-core</artifactId>
- <version>${dl4j.version}</version>
- </dependency>
- <dependency>
- <groupId>org.deeplearning4j</groupId>
- <artifactId>deeplearning4j-nn</artifactId>
- <version>${dl4j.version}</version>
- </dependency>
- <dependency>
- <groupId>org.nd4j</groupId>
- <artifactId>nd4j-native-platform</artifactId>
- <version>${dl4j.version}</version>
- </dependency>
-
- <!-- DataVec (for CSV reading) -->
- <dependency>
- <groupId>org.datavec</groupId>
- <artifactId>datavec-api</artifactId>
- <version>${dl4j.version}</version>
- </dependency>
- <dependency>
- <groupId>org.datavec</groupId>
- <artifactId>datavec-local</artifactId>
- <version>${dl4j.version}</version>
- </dependency>
-
- <!-- Lombok (Optional, for reducing boilerplate code) -->
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <!-- Spring Boot DevTools (Optional, for development convenience) -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-devtools</artifactId>
- <scope>runtime</scope>
- <optional>true</optional>
- </dependency>
-
- <!-- Spring Boot Test (Optional, for unit tests) -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
-
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
-
- </project>
使用 Java 中的 DL4J 创建一个简单的神经网络模型。
- import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
- import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
- import org.deeplearning4j.nn.conf.layers.DenseLayer;
- import org.deeplearning4j.nn.conf.layers.OutputLayer;
- import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
- import org.deeplearning4j.nn.weights.WeightInit;
- import org.deeplearning4j.optimize.api.IterationListener;
- import org.deeplearning4j.optimize.listeners.ScoreIterationListener;
- import org.nd4j.linalg.activations.Activation;
- import org.nd4j.linalg.dataset.DataSet;
- import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
- import org.nd4j.linalg.dataset.api.preprocessor.DataNormalization;
- import org.nd4j.linalg.dataset.api.preprocessor.NormalizerStandardize;
- import org.nd4j.linalg.factory.Nd4j;
- import org.nd4j.linalg.lossfunctions.LossFunctions.LossFunction;
- import org.nd4j.linalg.dataset.api.iterator.RecordReaderDataSetIterator;
- import org.datavec.api.records.reader.impl.csv.CSVRecordReader;
- import org.datavec.api.split.FileSplit;
- import org.datavec.api.util.ClassPathResource;
-
- public class LoanApprovalModel {
-
- public static void main(String[] args) throws Exception {
- // Load dataset
- int numLinesToSkip = 0;
- char delimiter = ',';
- CSVRecordReader recordReader = new CSVRecordReader(numLinesToSkip, delimiter);
- recordReader.initialize(new FileSplit(new ClassPathResource("loan_data.csv").getFile()));
-
- int labelIndex = 4; // Index of the label (approve/reject)
- int numClasses = 2; // Approve or Reject
- int batchSize = 5;
- DataSetIterator iterator = new RecordReaderDataSetIterator(recordReader, batchSize, labelIndex, numClasses);
-
- // Normalize the data
- DataNormalization normalizer = new NormalizerStandardize();
- normalizer.fit(iterator);
- iterator.setPreProcessor(normalizer);
-
- // Define the network configuration
- MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
- .iterations(1000)
- .activation(Activation.RELU)
- .weightInit(WeightInit.XAVIER)
- .learningRate(0.01)
- .list()
- .layer(0, new DenseLayer.Builder().nIn(4).nOut(3).build())
- .layer(1, new OutputLayer.Builder(LossFunction.NEGATIVELOGLIKELIHOOD)
- .activation(Activation.SOFTMAX)
- .nIn(3).nOut(2).build())
- .backprop(true).pretrain(false).build();
-
- MultiLayerNetwork model = new MultiLayerNetwork(conf);
- model.init();
- model.setListeners(new ScoreIterationListener(100));
-
- // 训练模型
- for (int i = 0; i < 1000; i++) {
- iterator.reset();
- model.fit(iterator);
- }
-
- // 保存模型
- model.save(new File("loan_approval_model.zip"), true);
- }
- }
创建一个 Spring Boot REST API,加载经过训练的模型并使用它来对新的贷款申请进行预测。
- import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
- import org.nd4j.linalg.factory.Nd4j;
- import org.nd4j.linalg.api.ndarray.INDArray;
- import org.springframework.web.bind.annotation.*;
-
- import java.io.File;
- import java.io.IOException;
-
- @RestController
- @RequestMapping("/loan")
- public class LoanApprovalController {
-
- private MultiLayerNetwork model;
-
- public LoanApprovalController() throws IOException {
- // Load the trained model
- model = MultiLayerNetwork.load(new File("loan_approval_model.zip"), true);
- }
-
- @PostMapping("/approve")
- public String approveLoan(@RequestBody LoanApplication loanApplication) {
- // Prepare input data
- INDArray input = Nd4j.create(new double[]{
- loanApplication.getCreditScore(),
- loanApplication.getIncome(),
- loanApplication.getLoanAmount(),
- loanApplication.getEmploymentStatus()
- }, 1, 4);
-
- // Make prediction
- INDArray output = model.output(input);
- int prediction = Nd4j.argMax(output, 1).getInt(0);
-
- return prediction == 1 ? "Approved" : "Rejected";
- }
- }
-
- class LoanApplication {
- private double creditScore;
- private double income;
- private double loanAmount;
- private int employmentStatus;
-
- // Getters and setters
- }
构建并运行您的 Spring Boot 应用程序。
向上面的web服务地址 /loan/approve 发送一个 POST 请求,其中包含代表贷款申请的 JSON 主体:
- {
- "creditScore": 710,
- "income": 55000,
- "loanAmount": 20000,
- "employmentStatus": 1
- }
API 将根据模型的预测返回“已批准”或“已拒绝”。
“使用 Spring Boot 和 DL4J 为‘贷款审批’应用程序开发了贷款审批推荐系统。实施了一个神经网络模型,根据申请人数据预测贷款审批,大大增强了决策过程并降低了违约风险。”
此示例演示了您使用现代 springboot框架将机器学习集成到生产环境的能力。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。