[Deeplearning4j应用教程03]_快速完成在自己的Maven项目中使用DL4J

article/2025/5/20 7:35:36

快速使用DL4J

  • 一、新建Maven项目
  • 二、配置依赖
  • 三、测试

一、新建Maven项目

1、打开IDEA后,步骤为:“File -> New -> Project”
在这里插入图片描述
2、选择Maven,然后选择已安装好的的JDK。另外,关于Add Archetype在下面。
在这里插入图片描述
Archetype我们可以理解为项目模型或者项目的骨架,能够通过它生成某一种项目的通用文件布局,此处我们选择较为常用的maven-archetype-quickStart。当然,也可以选择其他的,或者不选都是可以的。
在这里插入图片描述
3、进行Maven项目的重命名。
在这里插入图片描述
4、选择Maven的坐标,这里,我们选择本地的maven,选择maven的配置文件路径及本地maven仓库路径,选择完成后,点击“Finish”完成创建。
在这里插入图片描述
至此,Maven项目基本创建完毕,接下来,是最简单也是最重要的一步。

二、配置依赖

修改“pom.xml”文件,添加DL4J依赖。直接用以下内容全部替换原Maven项目中的“pom.xml”文件中的内容,点击更新即可。也可从此处进行复制替换:link

<?xml version="1.0" encoding="UTF-8"?>
<!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Copyright (c) 2020 Konduit K.K.~ Copyright (c) 2015-2019 Skymind, Inc.~~ This program and the accompanying materials are made available under the~ terms of the Apache License, Version 2.0 which is available at~ https://www.apache.org/licenses/LICENSE-2.0.~~ Unless required by applicable law or agreed to in writing, software~ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT~ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the~ License for the specific language governing permissions and limitations~ under the License.~~ SPDX-License-Identifier: Apache-2.0~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--><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><!-- Group-ID, artifact ID and version of the project. You can modify these as you want --><groupId>org.deeplearning4j</groupId><artifactId>deeplearning4j-example-sample</artifactId><version>1.0.0-beta7</version><!-- Properties Section. Change ND4J versions here, if required --><properties><dl4j-master.version>1.0.0-beta7</dl4j-master.version><logback.version>1.2.3</logback.version><java.version>1.8</java.version><maven-shade-plugin.version>2.4.3</maven-shade-plugin.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><!-- deeplearning4j-core: contains main functionality and neural networks --><dependency><groupId>org.deeplearning4j</groupId><artifactId>deeplearning4j-core</artifactId><version>${dl4j-master.version}</version></dependency><!--ND4J backend: every project needs one of these. The backend defines the hardware on which network trainingwill occur. "nd4j-native-platform" is for CPUs only (for running on all operating systems).--><dependency><groupId>org.nd4j</groupId><artifactId>nd4j-native</artifactId><version>${dl4j-master.version}</version></dependency><!-- CUDA: to use GPU for training (CUDA) instead of CPU, uncomment this, and remove nd4j-native-platform --><!-- Requires CUDA to be installed to use. Change the version (8.0, 9.0, 9.1) to change the CUDA version --><!--<dependency><groupId>org.nd4j</groupId><artifactId>nd4j-cuda-9.2-platform</artifactId><version>${dl4j-master.version}</version></dependency>--><!-- Optional, but recommended: if you use CUDA, also use CuDNN. To use this, CuDNN must also be installed --><!-- See: https://deeplearning4j.konduit.ai/config/backends/config-cudnn#using-deeplearning-4-j-with-cudnn --><!--<dependency><groupId>org.deeplearning4j</groupId><artifactId>deeplearning4j-cuda-9.2</artifactId><version>${dl4j-master.version}</version></dependency>--><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-classic</artifactId><version>${logback.version}</version></dependency></dependencies><build><plugins><!-- Maven compiler plugin: compile for Java 8 --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.5.1</version><configuration><source>${java.version}</source><target>${java.version}</target></configuration></plugin><!--Maven shade plugin configuration: this is required so that if you build a single JAR file (an "uber-jar")it will contain all the required native libraries, and the backends will work correctly.Used for example when running the following commantsmvn packagecd targetjava -cp deeplearning4j-examples-1.0.0-beta-bin.jar org.deeplearning4j.LenetMnistExample--><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-shade-plugin</artifactId><version>${maven-shade-plugin.version}</version><configuration><shadedArtifactAttached>true</shadedArtifactAttached><shadedClassifierName>bin</shadedClassifierName><createDependencyReducedPom>true</createDependencyReducedPom><filters><filter><artifact>*:*</artifact><excludes><exclude>org/datanucleus/**</exclude><exclude>META-INF/*.SF</exclude><exclude>META-INF/*.DSA</exclude><exclude>META-INF/*.RSA</exclude></excludes></filter></filters></configuration><executions><execution><phase>package</phase><goals><goal>shade</goal></goals><configuration><transformers><transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer"><resource>reference.conf</resource></transformer><transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/><transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"></transformer></transformers></configuration></execution></executions></plugin></plugins></build></project>

替换后内容如下图所示,并且点击右上角的更新按钮,进行更新。最后,等待1分钟左右即可。
在这里插入图片描述

三、测试

这里我们使用官方提供的MINIST案例进行测试,注意修改包名与类名(如果不是按照本教程设置的名称的话,需要根据自己所写的实际名称进行修改),另外项目结构如下。还有,我们需要删除“test”文件夹下“AppTest.java”文件中的内容,否则运行时会出错,因为,依赖有变化。
在这里插入图片描述
代码如下:


```java
/* ****************************************************************************** Copyright (c) 2020 Konduit K.K.* Copyright (c) 2015-2019 Skymind, Inc.** This program and the accompanying materials are made available under the* terms of the Apache License, Version 2.0 which is available at* https://www.apache.org/licenses/LICENSE-2.0.** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the* License for the specific language governing permissions and limitations* under the License.** SPDX-License-Identifier: Apache-2.0******************************************************************************/
package org.example;import org.apache.commons.io.FilenameUtils;
import org.deeplearning4j.datasets.iterator.impl.MnistDataSetIterator;
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.inputs.InputType;
import org.deeplearning4j.nn.conf.layers.*;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.deeplearning4j.optimize.api.InvocationType;
import org.deeplearning4j.optimize.listeners.EvaluativeListener;
import org.deeplearning4j.optimize.listeners.ScoreIterationListener;
import org.nd4j.linalg.activations.Activation;
import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
import org.nd4j.linalg.learning.config.Adam;
import org.nd4j.linalg.lossfunctions.LossFunctions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.File;/*** Created by agibsonccc on 9/16/15.*/
public class App {private static final Logger log = LoggerFactory.getLogger(String.class);public static void main(String[] args) throws Exception {int nChannels = 1; // Number of input channelsint outputNum = 10; // The number of possible outcomesint batchSize = 64; // Test batch sizeint nEpochs = 1; // Number of training epochsint seed = 123; ///*Create an iterator using the batch size for one iteration*/log.info("Load data....");DataSetIterator mnistTrain = new MnistDataSetIterator(batchSize,true,12345);DataSetIterator mnistTest = new MnistDataSetIterator(batchSize,false,12345);/*Construct the neural network*/log.info("Build model....");MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder().seed(seed).l2(0.0005).weightInit(WeightInit.XAVIER).updater(new Adam(1e-3)).list().layer(new ConvolutionLayer.Builder(5, 5)//nIn and nOut specify depth. nIn here is the nChannels and nOut is the number of filters to be applied.nIn(nChannels).stride(1,1).nOut(20).activation(Activation.IDENTITY).build()).layer(new SubsamplingLayer.Builder(PoolingType.MAX).kernelSize(2,2).stride(2,2).build()).layer(new ConvolutionLayer.Builder(5, 5)//Note that nIn need not be specified in later layers.stride(1,1).nOut(50).activation(Activation.IDENTITY).build()).layer(new SubsamplingLayer.Builder(PoolingType.MAX).kernelSize(2,2).stride(2,2).build()).layer(new DenseLayer.Builder().activation(Activation.RELU).nOut(500).build()).layer(new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD).nOut(outputNum).activation(Activation.SOFTMAX).build()).setInputType(InputType.convolutionalFlat(28,28,1)) //See note below.build();/*Regarding the .setInputType(InputType.convolutionalFlat(28,28,1)) line: This does a few things.(a) It adds preprocessors, which handle things like the transition between the convolutional/subsampling layersand the dense layer(b) Does some additional configuration validation(c) Where necessary, sets the nIn (number of input neurons, or input depth in the case of CNNs) values for eachlayer based on the size of the previous layer (but it won't override values manually set by the user)InputTypes can be used with other layer types too (RNNs, MLPs etc) not just CNNs.For normal images (when using ImageRecordReader) use InputType.convolutional(height,width,depth).MNIST record reader is a special case, that outputs 28x28 pixel grayscale (nChannels=1) images, in a "flattened"row vector format (i.e., 1x784 vectors), hence the "convolutionalFlat" input type used here.*/MultiLayerNetwork model = new MultiLayerNetwork(conf);model.init();log.info("Train model...");model.setListeners(new ScoreIterationListener(10), new EvaluativeListener(mnistTest, 1, InvocationType.EPOCH_END)); //Print score every 10 iterations and evaluate on test set every epochmodel.fit(mnistTrain, nEpochs);String path = FilenameUtils.concat(System.getProperty("java.io.tmpdir"), "lenetmnist.zip");log.info("Saving model to tmp folder: "+path);model.save(new File(path), true);log.info("****************Example finished********************"); }
}

部分代码截图:
在这里插入图片描述
最终,运行程序,输出结果如下,则说明我们创建成功啦,恭喜,恭喜。
在这里插入图片描述


http://chatgpt.dhexx.cn/article/f5IOoTTS.shtml

相关文章

[Deeplearning4j应用教程00]_DL4J技术介绍

文章目录 Deeplearning 4j概览Deeplearning主要组件nd4jSameDiffDatavecDeeplearningDeeplearning技术栈与工作流 Konduit Deeplearning 4j概览 Deeplearning4j当前最大、最流行的基于JAVA的深度学习框架&#xff0c;截止目前&#xff0c;社区人数为4900&#xff0c;拥有11800…

[Deeplearning4j应用教程04]_基于DL4J的神经网络实现

DL4JScala的神经网络实现 一、内容简介二、准备工程与环境三、准备工作空间四、准备要加载的数据五、神经网络的搭建六、训练神经网络模型七、评估模型 一、内容简介 Deeplearning4j&#xff08;也称为“ DL4J”&#xff09;是一种高性能的特定领域语言&#xff0c;用于配置由…

从TensorFlow到DL4J——主流深度学习框架对比分析

从TensorFlow到DL4J——主流深度学习框架对比分析 2022年2月22日 极链AI云 官网地址 点击注册 更多AI小知识&#xff0c;关注《极链AI云》公众号 文章目录 从TensorFlow到DL4J——主流深度学习框架对比分析一、深度学习框架概述与深度学习技术的四大阵营二、主流开源深度学习框…

DL4J中文文档/ND4J/概述

本用户指南旨在解释&#xff08;并提供示例&#xff09;ND4J中的主要功能。 简介 NDArrays:它们在内存中是如何存储的&#xff1f;视图&#xff1a;当两个或更多NDArrays引用相同的数据创建NDArrays 0,1和标量值初始化数组随机数组从Java数组创建NDArrays从其它NDArrays创建ND…

DL4J实战之五:矩阵操作基本功

欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码)&#xff1a;https://github.com/zq2599/blog_demos 本篇概览 作为《DL4J实战》系列的第五篇&#xff0c;在前面对深度学习有一定的了解后&#xff0c;本篇会暂停深度学习相关的操作&#xff0c;转为基本功练习&…

DL4J实战之六:图形化展示训练过程

欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码)&#xff1a;https://github.com/zq2599/blog_demos 本篇概览 本篇是《DL4J实战》系列的第六篇&#xff0c;咱们继续夯实基本功&#xff0c;这次学习的是如何更加形象完整的展示训练过程&#xff1a;图形化页面&…

使用tensorflow搭建深层神经网络

6在吴恩达老师的《深度学习》第二课第三周的课程中&#xff0c;提及到了多种深度学习框架&#xff0c;包括caffe/caffe2&#xff0c;CNTK&#xff0c;DL4J&#xff0c;Keras&#xff0c;Lasagne&#xff0c;mxnet&#xff0c;paddlepadle&#xff0c;tensorflow&#xff0c;The…

[Deeplearning4j应用教程02]_DL4J环境搭建教程-Windows版

Windows下DL4J环境搭建教程 一、DL4J简介二、Windows下DL4J环境搭建三、安装JDK1.1、JDK简介1.2、JDK下载安装1.3、安装JDK1.3.1、环境变量配置 四、安装Intellij idea五、Maven Apache安装六、在IDEA中配置Maven七、安装Git八、获取DL4J示例代码九、在IDEA中导入项目并运行 一…

DL4J源码分析

目录 源码目录&#xff08;部分&#xff09; NDArray 工作间 DL4J的层工作间管理器 沿维张量&#xff08;TAD&#xff09; 反向减法 源码目录&#xff08;部分&#xff09; DeepLearning4J: 包含用于既在单个机器上&#xff0c;又在分布式上学习神经网络的所有代码。 N…

DL4J实战之四:经典卷积实例(GPU版本)

欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码)&#xff1a;https://github.com/zq2599/blog_demos 本篇概览 作为《DL4J实战》的第四篇&#xff0c;今天咱们不写代码&#xff0c;而是为今后的实战做些准备&#xff1a;在DL4J框架下用GPU加速深度学习的训练过…

DL4J实战之三:经典卷积实例(LeNet-5)

欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码)&#xff1a;https://github.com/zq2599/blog_demos 本篇概览 作为《DL4J》实战的第三篇&#xff0c;目标是在DL4J框架下创建经典的LeNet-5卷积神经网络模型&#xff0c;对MNIST数据集进行训练和测试&#xff0…

DL4J实战之二:鸢尾花分类

欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码)&#xff1a;https://github.com/zq2599/blog_demos 本篇概览 本文是《DL4J》实战的第二篇&#xff0c;前面做好了准备工作&#xff0c;接下来进入正式实战&#xff0c;本篇内容是经典的入门例子&#xff1a;鸢…

DL4J实战之一:准备

欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码)&#xff1a;https://github.com/zq2599/blog_demos 关于DL4J DL4J是Deeplearning4j的简称&#xff0c;是基于Java虚拟机的深度学习框架&#xff0c;是用java和scala开发的&#xff0c;已开源&#xff0c;官网&…

【DL4J】基本操作_学习笔记(二)

DL4J基本操作 文章目录 DL4J基本操作1. 创建矩阵2. 矩阵元素读取3. 矩阵行元素读取4. 矩阵运算 导入依赖 <nd4j.version>1.0.0-beta2</nd4j.version><dependency><groupId>org.nd4j</groupId><artifactId>nd4j-native-platform</artifa…

【DL4J速成】Deeplearning4j图像分类从模型自定义到测试

文章首发于微信公众号《有三AI》 【DL4J速成】Deeplearning4j图像分类从模型自定义到测试 欢迎来到专栏《2小时玩转开源框架系列》&#xff0c;这是我们第九篇&#xff0c;前面已经说过了caffe&#xff0c;tensorflow&#xff0c;pytorch&#xff0c;mxnet&#xff0c;keras&…

深度学习框架DeepLearning4J(DL4J)的安装及配置

一、DeepLearning4J的简介和系统要求 1、DeepLearning4J简介 Deeplearning4J&#xff08;以下简称DL4J&#xff09;不是第一个开源的深度学习项目&#xff0c;但与此前的其他项目相比&#xff0c;DL4J在编程语言和宗旨两方面都独具特色。DL4J是基于JVM、聚焦行业应用且提供商…

适合中学生看的英文电影

怎样利用好丰富的资源来学习英语口语呢&#xff1f;其实其实看什么样的剧、如何看剧都是很讲究的。一起来解锁吧。 一、选剧要学会拆解自己学习目标&#xff0c;选定合适的类型&#xff0c;各取所需。 并不是所有类型的国外影视剧都适合作为学习的素材&#xff0c;主要依据自身…

springboot+mybatis实现简单的增、删、查、改

这篇文章主要针对java初学者&#xff0c;详细介绍怎么创建一个基本的springboot项目来对数据库进行crud操作。 目录 第一步&#xff1a;准备数据库 第二步&#xff1a;创建springboot项目 方法1&#xff1a;通过spring官网的spring initilizer创建springboot项目 方法2&am…

tk-mybatis使用介绍,springboot整合tk-mybatis、PageHelper实现分页查询

Mybatis-Plus极大简化了我们的开发&#xff0c;作为mybatis的增强版&#xff0c;Mybatis-Plus确实帮我们减少了很多SQL语句的编写&#xff0c;通过其提高的API&#xff0c;可以方便快捷第完成增删查改操作。但是&#xff0c;其实除了Mybatis-Plus以外&#xff0c;还有一个技术t…

SXSW 2022线下展回归,今年有哪些有趣的AR/VR内容?

如今海外的线下活动开始逐渐恢复&#xff0c;今年的SXSW活动也回归线下。与往年相比&#xff0c;这场艺术、音乐、电影的年度盛会在今年进一步融合新兴科技&#xff0c;比如将AR/VR与线下活动结合&#xff0c;带来了更多样化的娱乐应用场景。 那么今年活动上都有哪些看点&#…