<output id="qn6qe"></output>

    1. <output id="qn6qe"><tt id="qn6qe"></tt></output>
    2. <strike id="qn6qe"></strike>

      亚洲 日本 欧洲 欧美 视频,日韩中文字幕有码av,一本一道av中文字幕无码,国产线播放免费人成视频播放,人妻少妇偷人无码视频,日夜啪啪一区二区三区,国产尤物精品自在拍视频首页,久热这里只有精品12

      deeplearning4j訓練MNIST數據集以及驗證

      訓練模型官方示例

      MNIST數據下載地址: http://github.com/myleott/mnist_png/raw/master/mnist_png.tar.gz
      GitHub示例地址: https://github.com/deeplearning4j/deeplearning4j-examples/blob/master/dl4j-examples/src/main/java/org/deeplearning4j/examples/quickstart/modeling/convolution/LeNetMNISTReLu.java

      /*******************************************************************************
       *
       *
       *
       * 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.
       *  See the NOTICE file distributed with this work for additional
       *  information regarding copyright ownership.
       *
       * 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.deeplearning4j.examples.quickstart.modeling.convolution;
      
      import org.datavec.api.io.labels.ParentPathLabelGenerator;
      import org.datavec.api.split.FileSplit;
      import org.datavec.image.loader.NativeImageLoader;
      import org.datavec.image.recordreader.ImageRecordReader;
      import org.deeplearning4j.datasets.datavec.RecordReaderDataSetIterator;
      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.ConvolutionLayer;
      import org.deeplearning4j.nn.conf.layers.DenseLayer;
      import org.deeplearning4j.nn.conf.layers.OutputLayer;
      import org.deeplearning4j.nn.conf.layers.SubsamplingLayer;
      import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
      import org.deeplearning4j.nn.weights.WeightInit;
      import org.deeplearning4j.optimize.listeners.ScoreIterationListener;
      import org.deeplearning4j.examples.utils.DataUtilities;
      import org.deeplearning4j.util.ModelSerializer;
      import org.nd4j.evaluation.classification.Evaluation;
      import org.nd4j.linalg.activations.Activation;
      import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
      import org.nd4j.linalg.dataset.api.preprocessor.DataNormalization;
      import org.nd4j.linalg.dataset.api.preprocessor.ImagePreProcessingScaler;
      import org.nd4j.linalg.learning.config.Nesterovs;
      import org.nd4j.linalg.lossfunctions.LossFunctions;
      import org.nd4j.linalg.schedule.MapSchedule;
      import org.nd4j.linalg.schedule.ScheduleType;
      import org.slf4j.Logger;
      import org.slf4j.LoggerFactory;
      
      import java.io.File;
      import java.util.HashMap;
      import java.util.Map;
      import java.util.Random;
      
      /**
       * Implementation of LeNet-5 for handwritten digits image classification on MNIST dataset (99% accuracy)
       * <a >[LeCun et al., 1998. Gradient based learning applied to document recognition]</a>
       * Some minor changes are made to the architecture like using ReLU and identity activation instead of
       * sigmoid/tanh, max pooling instead of avg pooling and softmax output layer.
       * <p>
       * This example will download 15 Mb of data on the first run.
       *
       * @author hanlon
       * @author agibsonccc
       * @author fvaleri
       * @author dariuszzbyrad
       */
      public class LeNetMNISTReLu {
          private static final Logger LOGGER = LoggerFactory.getLogger(LeNetMNISTReLu.class);
          //    private static final String BASE_PATH = System.getProperty("java.io.tmpdir") + "/mnist";
          private static final String BASE_PATH = "D:\\Documents\\Downloads\\mnist_png";
          private static final String DATA_URL = "http://github.com/myleott/mnist_png/raw/master/mnist_png.tar.gz";
      
          public static void main(String[] args) throws Exception {
              // 圖片高度
              int height = 28;    // height of the picture in px
              // 圖片寬度
              int width = 28;     // width of the picture in px
              // 通道 1 表示 黑白
              int channels = 1;   // single channel for grayscale images
              // 可能出現的結果數量 0-9 10個數字
              int outputNum = 10; // 10 digits classification
              // 批處理數量
              int batchSize = 54; // number of samples that will be propagated through the network in each iteration
              // 迭代次數
              int nEpochs = 1;    // number of training epochs
              // 隨機數生成器
              int seed = 1234;    // number used to initialize a pseudorandom number generator.
              Random randNumGen = new Random(seed);
      
              LOGGER.info("Data load...");
              if (!new File(BASE_PATH + "/mnist_png").exists()) {
      
                  LOGGER.debug("Data downloaded from {}", DATA_URL);
                  String localFilePath = BASE_PATH + "/mnist_png.tar.gz";
                  if (DataUtilities.downloadFile(DATA_URL, localFilePath)) {
                      DataUtilities.extractTarGz(localFilePath, BASE_PATH);
                  }
              }
      
              LOGGER.info("Data vectorization...");
              // vectorization of train data
              File trainData = new File(BASE_PATH + "/mnist_png/training");
              FileSplit trainSplit = new FileSplit(trainData, NativeImageLoader.ALLOWED_FORMATS, randNumGen);
              ParentPathLabelGenerator labelMaker = new ParentPathLabelGenerator(); // use parent directory name as the image label
              ImageRecordReader trainRR = new ImageRecordReader(height, width, channels, labelMaker);
              trainRR.initialize(trainSplit);
              // MNIST中的數據
              DataSetIterator trainIter = new RecordReaderDataSetIterator(trainRR, batchSize, 1, outputNum);
      
              // pixel values from 0-255 to 0-1 (min-max scaling)
              DataNormalization imageScaler = new ImagePreProcessingScaler();
              imageScaler.fit(trainIter);
              trainIter.setPreProcessor(imageScaler);
      
              // vectorization of test data
              File testData = new File(BASE_PATH + "/mnist_png/testing");
              FileSplit testSplit = new FileSplit(testData, NativeImageLoader.ALLOWED_FORMATS, randNumGen);
              ImageRecordReader testRR = new ImageRecordReader(height, width, channels, labelMaker);
              testRR.initialize(testSplit);
              DataSetIterator testIter = new RecordReaderDataSetIterator(testRR, batchSize, 1, outputNum);
              testIter.setPreProcessor(imageScaler); // same normalization for better results
      
              LOGGER.info("Network configuration and training...");
              // reduce the learning rate as the number of training epochs increases
              // iteration #, learning rate
              Map<Integer, Double> learningRateSchedule = new HashMap<>();
              learningRateSchedule.put(0, 0.06);
              learningRateSchedule.put(200, 0.05);
              learningRateSchedule.put(600, 0.028);
              learningRateSchedule.put(800, 0.0060);
              learningRateSchedule.put(1000, 0.001);
      
              MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
                      .seed(seed)
                      .l2(0.0005) // ridge regression value
                      .updater(new Nesterovs(new MapSchedule(ScheduleType.ITERATION, learningRateSchedule)))
                      .weightInit(WeightInit.XAVIER)
                      .list()
                      .layer(new ConvolutionLayer.Builder(5, 5)
                              .nIn(channels)
                              .stride(1, 1)
                              .nOut(20)
                              .activation(Activation.IDENTITY)
                              .build())
                      .layer(new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX)
                              .kernelSize(2, 2)
                              .stride(2, 2)
                              .build())
                      .layer(new ConvolutionLayer.Builder(5, 5)
                              .stride(1, 1) // nIn need not specified in later layers
                              .nOut(50)
                              .activation(Activation.IDENTITY)
                              .build())
                      .layer(new SubsamplingLayer.Builder(SubsamplingLayer.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(height, width, channels)) // InputType.convolutional for normal image
                      .build();
      
              MultiLayerNetwork net = new MultiLayerNetwork(conf);
              net.init();
              net.setListeners(new ScoreIterationListener(10));
              LOGGER.info("Total num of params: {}", net.numParams());
      
              // evaluation while training (the score should go down)
              for (int i = 0; i < nEpochs; i++) {
                  net.fit(trainIter);
                  LOGGER.info("Completed epoch {}", i);
                  Evaluation eval = net.evaluate(testIter);
                  LOGGER.info(eval.stats());
      
                  trainIter.reset();
                  testIter.reset();
              }
      
              File ministModelPath = new File(BASE_PATH + "/minist-model.zip");
              ModelSerializer.writeModel(net, ministModelPath, true);
              LOGGER.info("The MINIST model has been saved in {}", ministModelPath.getPath());
          }
      }
      

      驗證模型

      package org.deeplearning4j.examples.quickstart.modeling.convolution;
      
      import org.datavec.image.loader.NativeImageLoader;
      import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
      import org.nd4j.linalg.api.ndarray.INDArray;
      import org.nd4j.linalg.dataset.api.preprocessor.DataNormalization;
      import org.nd4j.linalg.dataset.api.preprocessor.ImagePreProcessingScaler;
      
      import java.io.File;
      import java.io.IOException;
      
      /**
       * @description:
       * @author: Mr.Fang
       * @create: 2023-07-14 15:06
       **/
      
      public class VerifyMNSIT {
          public static void main(String[] args) throws IOException {
      
              // 加載訓練好的模型
              File modelFile = new File("D:\\Documents\\Downloads\\mnist_png\\minist-model.zip");
              MultiLayerNetwork model = MultiLayerNetwork.load(modelFile, true);
      
              // 加載待驗證的圖像
              File imageFile = new File("D:\\Documents\\Downloads\\mnist_png\\mnist_png\\testing\\8\\1717.png");
              NativeImageLoader loader = new NativeImageLoader(28, 28, 1);
              INDArray image = loader.asMatrix(imageFile);
              DataNormalization scaler = new ImagePreProcessingScaler(0, 1);
              scaler.transform(image);
      
              // 對圖像進行預測
              INDArray output = model.output(image);
              int predictedLabel = output.argMax().getInt();
              // 在這行代碼中,`output.argMax()`用于找到`output`中具有最大值的索引。`output`是一個包含模型的輸出概率的NDArray對象。對于MNIST模型,輸出是一個長度為10的向量,表示數字0到9的概率分布。
              //
              //`.argMax()`方法返回具有最大值的索引。例如,如果`output`的值為[0.1, 0.3, 0.2, 0.05, 0.25, 0.05, 0.05, 0.1, 0.05, 0.05],則`.argMax()`將返回索引1,因為在位置1處的值0.3是最大的。
              //
              //最后,`.getInt()`方法將獲取`.argMax()`的結果并將其轉換為一個整數,表示預測的標簽。在這個例子中,`predictedLabel`將包含模型預測的數字標簽。
              //
              //簡而言之,這行代碼的作用是找到輸出中概率最高的數字標簽,以進行預測。
              System.out.println("Predicted label: " + predictedLabel);
          }
      }
      
      

      輸出結果

      o.n.l.f.Nd4jBackend - Loaded [CpuBackend] backend
      o.n.n.NativeOpsHolder - Number of threads used for linear algebra: 6
      o.n.l.c.n.CpuNDArrayFactory - Binary level Generic x86 optimization level AVX/AVX2
      o.n.n.Nd4jBlas - Number of threads used for OpenMP BLAS: 6
      o.n.l.a.o.e.DefaultOpExecutioner - Backend used: [CPU]; OS: [Windows 10]
      o.n.l.a.o.e.DefaultOpExecutioner - Cores: [12]; Memory: [4.0GB];
      o.n.l.a.o.e.DefaultOpExecutioner - Blas vendor: [OPENBLAS]
      o.n.l.c.n.CpuBackend - Backend build information:
       GCC: "12.1.0"
      STD version: 201103L
      DEFAULT_ENGINE: samediff::ENGINE_CPU
      HAVE_FLATBUFFERS
      HAVE_OPENBLAS
      o.d.n.m.MultiLayerNetwork - Starting MultiLayerNetwork with WorkspaceModes set to [training: ENABLED; inference: ENABLED], cacheMode set to [NONE]
      Predicted label: 8
      
      
      posted @ 2023-07-14 17:30  天葬  閱讀(466)  評論(1)    收藏  舉報
      主站蜘蛛池模板: brazzers欧美巨大| 高清国产精品人妻一区二区| 亚洲av永久无码精品水牛影视| 国产精品免费第一区二区| 国产黑色丝袜在线播放| 亚洲av永久无码精品水牛影视| 99福利一区二区视频| 国产成人免费永久在线平台| 粉嫩av一区二区三区蜜臀| 国产普通话对白刺激| 动漫av网站免费观看| 精品无码国产一区二区三区AV| 亚洲成A人片在线观看的电影| 中文字幕色偷偷人妻久久| 蜜桃臀av在线一区二区| 熟女精品色一区二区三区| 在线天堂最新版资源| 免费现黄频在线观看国产| 免费无码又爽又刺激成人| 人人澡人摸人人添| 99久久国语露脸精品国产| 国产精品一区二区传媒蜜臀| 国产午夜三级一区二区三| 免费人妻无码不卡中文18禁| 亚洲日本韩国欧美云霸高清| 国产亚洲一区二区三不卡| √天堂中文在线最新版| 日韩激情一区二区三区| 日韩不卡一区二区在线观看| 亚洲精品在线二区三区| 国产精品无码v在线观看| 天堂中文8资源在线8| 男女爽爽无遮挡午夜视频| 久久香蕉国产线看观看精品yw| 99久久亚洲综合精品成人网| 美女无遮挡免费视频网站| 97人妻熟女成人免费视频色戒| 久久精品青青大伊人av| 亚洲精品成人片在线观看精品字幕| 中文字幕无码av波多野吉衣| 国产精品最新免费视频|