Java分布式神经网络库Deeplearning4j之上手实践手写数字图像识别与模型训练

本文介绍如何使用Java分布式神经网络库Deeplearning4j进行手写数字识别,包括环境搭建、模型训练及保存、加载模型进行预测等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

环境的搭建可以参考另一篇文章。

                   

  • 第一步运行MnistImagePipelineExampleSave代码下载数据集,并进行训练和保存

需要下载一个文件(windows默认保存在C:\Users\Administrator\AppData\Local\Temp\dl4j_Mnist)。文件存在git。如果网络不好。建议手动下载并解压。然后注释掉代码中的下载方法即可。如图所示:

               

训练需要一段时间等待即可。时间长短取决于自己电脑配置。

  • 第二步运行MnistImagePipelineLoadChooser代码。并选中一个手写数字图像。进行识别测试
package org.deeplearning4j.examples.dataexamples;

import org.datavec.image.loader.NativeImageLoader;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.util.ModelSerializer;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.dataset.api.preprocessor.DataNormalization;
import org.nd4j.linalg.dataset.api.preprocessor.ImagePreProcessingScaler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * 
 * 给定用户一个文件选择框来选中要测试的手写数字图像
 * 0-9数字 白色或者黑色背景进行识别
 */
public class MnistImagePipelineLoadChooser {
    private static Logger log = LoggerFactory.getLogger(MnistImagePipelineLoadChooser.class);


    /*
    Create a popup window to allow you to chose an image file to test against the
    trained Neural Network
    Chosen images will be automatically
    scaled to 28*28 grayscale
     */
    public static String fileChose(){
        JFileChooser fc = new JFileChooser();
        int ret = fc.showOpenDialog(null);
        if (ret == JFileChooser.APPROVE_OPTION)
        {
            File file = fc.getSelectedFile();
            String filename = file.getAbsolutePath();
            return filename;
        }
        else {
            return null;
        }
    }

    public static void main(String[] args) throws Exception{
        int height = 28;
        int width = 28;
        int channels = 1;

        List<Integer> labelList = Arrays.asList(0,1,2,3,4,5,6,7,8,9);

        // pop up file chooser
        String filechose = fileChose().toString();

        //LOAD NEURAL NETWORK

        // MnistImagePipelineExampleSave训练并保存模型
        File locationToSave = new File("trained_mnist_model.zip");
        // 检查保存的模型是否存在
        if(locationToSave.exists()){
            System.out.println("\n######存在保存的训练模型######\n");
        }else{
            System.out.println("\n\n#######File not found!#######");
            System.out.println("This example depends on running ");
            System.out.println("MnistImagePipelineExampleSave");
            System.out.println("Run that Example First");
            System.out.println("#############################\n\n");


            System.exit(0);
        }

        MultiLayerNetwork model = ModelSerializer.restoreMultiLayerNetwork(locationToSave);

        log.info("*********TEST YOUR IMAGE AGAINST SAVED NETWORK********");

        // 选择一个文件

        File file = new File(filechose);

        // 使用NativeImageLoader转换为数值矩阵

        NativeImageLoader loader = new NativeImageLoader(height, width, channels);

        // 得到图像并赋值INDArray

        INDArray image = loader.asMatrix(file);

        // 0-255
        // 0-1
        DataNormalization scaler = new ImagePreProcessingScaler(0,1);
        scaler.transform(image);
        // 传递到神经网络 并得到概率值
        INDArray output = model.output(image);

        log.info("## The FILE CHOSEN WAS " + filechose);
        log.info("## The Neural Nets Pediction ##");
        log.info("## list of probabilities per label ##");
        //log.info("## List of Labels in Order## ");
        //有序状态
        log.info(output.toString());
        log.info(labelList.toString());

    }



}
  • 选择图片运行后的结果
######Saved Model Found######

o.n.l.f.Nd4jBackend - Loaded [CpuBackend] backend
o.n.n.NativeOpsHolder - Number of threads used for NativeOps: 2
o.n.n.Nd4jBlas - Number of threads used for BLAS: 2
o.n.l.a.o.e.DefaultOpExecutioner - Backend used: [CPU]; OS: [Windows 7]
o.n.l.a.o.e.DefaultOpExecutioner - Cores: [4]; Memory: [1.8GB];
o.n.l.a.o.e.DefaultOpExecutioner - Blas vendor: [OPENBLAS]
o.d.n.m.MultiLayerNetwork - Starting MultiLayerNetwork with WorkspaceModes set to [training: NONE; inference: SEPARATE]
o.d.e.d.MnistImagePipelineLoadChooser - *********TEST YOUR IMAGE AGAINST SAVED NETWORK********
o.d.e.d.MnistImagePipelineLoadChooser - ## The FILE CHOSEN WAS C:\Users\Administrator\Desktop\93.png
o.d.e.d.MnistImagePipelineLoadChooser - ## The Neural Nets Pediction ##
o.d.e.d.MnistImagePipelineLoadChooser - ## list of probabilities per label ##
o.d.e.d.MnistImagePipelineLoadChooser - [0.00,  0.00,  0.00,  1.00,  0.00,  0.00,  0.00,  0.00,  0.00,  0.00]
o.d.e.d.MnistImagePipelineLoadChooser - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
图中的数字为: 3
数字的置信度为:100.0%

Process finished with exit code 0

选择的图片为:

可见模型对黑白的手写数字识别度还算是可以的。

相关资料。建议还是去官网查阅。本博客只是进行上手实践

https://deeplearning4j.org/cn/

想了解菜品识别,车型识别,OCR识别,可以扫码下面微信小程序二维码进行体验

 

转载于:https://my.oschina.net/xshuai/blog/1537757

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值