DeepLearningTool-深度学习分类-和HALCON的详细过程

因二维码划伤在码内部,可以识别二维码,用二维码的固定损坏等级,来判断,要么过检测,要么,漏检测。所以考虑用深度学习。测试后,深度学习可用,但是耗时较长。深度学习弃用。

1

具体描述halcon深度学习分类的实现过程:
首先需要用自带的MVTEC DEEPLEARNING TOOL来标注训练得到模型。具体做法如下:
需要提前准备的工作:
有图像,有dlt工具
1

点击图标:
目前自用版本是24.12

1
点击新建项目
1
1
添加图片:这里已经将OK和NG分好分别放在两个文件夹
在这里插入图片描述

文件图路径
1

1

1
1
1

可以更改OK/NG类型
1
1

1

1
1

1
1
1
1

1
1

1

1
1
1
设好所有参数
点击开始训练

1
1
1
1

评估

1
1
1
1

AI2性能更强大一些。
导出:

1

1

1
如何使用:
在halcon
以下是使用说明:
1
1

1
1

*关闭程序计数器
dev_update_pc ('off')
*开启或关闭程序运行过程中变量窗口的更新
dev_update_var ('off')
dev_update_window ('off')
dev_close_window ()
dev_open_window (0, 0, 202, 202, 'black', WindowHandle)
*在此处输入/调整名称和路径

* 
*读取阀值和图像预处理参数。
read_dict ('E:/2025yearproject/2Project_BarCode20250217/DL-CODE/model_训练-250304-212226_opt_dl_preprocess_params.hdict',\
           [], [], DLPreprocessParam)
*读入学习的网络模版及权重
read_dl_model ('E:/2025yearproject/2Project_BarCode20250217/DL-CODE/model_训练-250304-212226_opt.hdl',\
DLModelHandle)
*请选择CPU设备。
query_available_dl_devices (['runtime', 'runtime'], ['gpu', 'cpu'], DLDeviceHandles)
if (|DLDeviceHandles| == 0)
    throw ('No supported device found to continue this example.')
endif
*由于query_available_dl_devices中使用的筛选器,第一个设备是GPU(如果可用)。
DLDevice := DLDeviceHandles[0]
* 
*使用的批处理大小
set_dl_model_param (DLModelHandle, 'device', DLDevice)

    query_font (WindowHandle, Font)
    * Specify font name and size
    FontWithSize := Font[0]+'-20'
    set_font (WindowHandle, FontWithSize)
*将DLT中的训练模型随机应用于一些
*选择的示例图像。

create_dict (DLSample)
* Image Acquisition 01: Code generated by Image Acquisition 01
list_files ('E:/DATACODE', ['files','follow_links','recursive'], ImageFiles)
tuple_regexp_select (ImageFiles, ['\\.(tif|tiff|gif|bmp|jpg|jpeg|jp2|png|pcx|pgm|ppm|pbm|xwd|ima|hobj)$','ignore_case'], ImageFiles)
for Index := 0 to |ImageFiles| - 1 by 1
    read_image (Image, ImageFiles[Index])
    *把图像装入字典
    set_dict_object (Image, DLSample, 'image')
    *格式化图片使其和训练的一样,异常判断还是种类选择,图像大小,通道数,色彩范围,归一化,查找范围
    preprocess_dl_samples (DLSample, DLPreprocessParam)
    *对预处理后的图像进行判断
    apply_dl_model (DLModelHandle, DLSample, [], DLResult)
    *用学习过的阈值推断结果。
    *写出结果
    dev_display (Image)
    result:=DLResult.classification_class_names[0]
    if(result=='OK')
        set_color (WindowHandle, 'green')
    else
        set_color (WindowHandle, 'red')
    endif
    set_tposition (WindowHandle, 24, 12)
    write_string (WindowHandle, 'Result: ' + DLResult.classification_class_names[0])
    wait_seconds (0.5)
*     stop()
endfor

损失函数(Loss Function)

定义:损失函数用于衡量模型预测值与真实值之间的差异,是模型优化的目标。

作用

  • 模型训练:通过最小化损失函数来优化模型参数。
  • 性能评估:评估模型在训练集和测试集上的表现。

常见类型

  • 均方误差(MSE):用于回归问题,计算预测值与真实值的平方差均值。
  • 交叉熵损失(Cross-Entropy Loss):用于分类问题,衡量预测概率分布与真实分布的差异。
  • 对数损失(Log Loss):二分类问题的交叉熵损失。
  • Hinge Loss:用于支持向量机(SVM),适用于分类问题。

公式

  • MSE:( \text{MSE} = \frac{1}{n} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2 )
  • 交叉熵损失:( \text{Cross-Entropy} = -\sum_{i=1}^{n} y_i \log(\hat{y}_i) )

混淆矩阵(Confusion Matrix)

定义:混淆矩阵用于分类问题,展示模型预测结果与真实标签的对比。

结构

  • 真正例(True Positive, TP):正确预测为正类。
  • 假正例(False Positive, FP):错误预测为正类。
  • 真反例(True Negative, TN):正确预测为负类。
  • 假反例(False Negative, FN):错误预测为负类。

作用

  • 性能评估:计算准确率、召回率、F1分数等指标。
  • 错误分析:识别模型在哪些类别上表现不佳。

常见指标

  • 准确率(Accuracy):( \frac{TP + TN}{TP + FP + TN + FN} )
  • 精确率(Precision):( \frac{TP}{TP + FP} )
  • 召回率(Recall):( \frac{TP}{TP + FN} )
  • F1分数(F1 Score):( 2 \times \frac{\text{Precision} \times \text{Recall}}{\text{Precision} + \text{Recall}} )

总结

  • 损失函数:衡量预测误差,用于模型优化。
  • 混淆矩阵:评估分类模型性能,提供详细预测结果分析。

两者结合使用,可以全面评估和优化模型。

过拟合(Overfitting)

定义:模型在训练集上表现很好,但在测试集或新数据上表现较差,通常是因为模型过于复杂,捕捉了训练数据中的噪声。

表现

  • 训练集误差低,测试集误差高。
  • 模型对训练数据过于敏感。

原因

  • 模型复杂度过高。
  • 训练数据不足。
  • 训练时间过长。

调整方法

  1. 简化模型
    • 减少参数数量。
    • 使用正则化(如L1、L2正则化)。
  2. 增加数据
    • 数据增强。
    • 收集更多数据。
  3. 早停(Early Stopping)
    • 在验证集误差最小时停止训练。
  4. 交叉验证
    • 使用交叉验证评估模型性能。
  5. Dropout
    • 在神经网络中随机丢弃部分神经元。

欠拟合(Underfitting)

定义:模型在训练集和测试集上表现都不佳,通常是因为模型过于简单,无法捕捉数据中的复杂模式。

表现

  • 训练集和测试集误差都高。
  • 模型对数据拟合不足。

原因

  • 模型复杂度过低。
  • 特征选择不当。
  • 训练时间不足。

调整方法

  1. 增加模型复杂度
    • 增加参数数量。
    • 使用更复杂的模型(如深层神经网络)。
  2. 特征工程
    • 添加更多特征。
    • 使用特征选择方法。
  3. 增加训练时间
    • 增加训练轮数(epochs)。
  4. 调整学习率
    • 使用更小的学习率,使模型更细致地学习数据。
  5. 集成方法
    • 使用集成学习(如随机森林、梯度提升)。

总结

  • 过拟合:模型过于复杂,捕捉了噪声,表现为训练集误差低,测试集误差高。
  • 欠拟合:模型过于简单,无法捕捉数据模式,表现为训练集和测试集误差都高。

调整参数

  • 过拟合:简化模型、增加数据、使用正则化、早停、Dropout。
  • 欠拟合:增加模型复杂度、特征工程、增加训练时间、调整学习率、使用集成方法。

通过合理调整参数和方法,可以有效避免过拟合和欠拟合,提升模型性能。

深度学习工具包 Deprecation notice. ----- This toolbox is outdated and no longer maintained. There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/) I would suggest you use one of the tools mentioned above rather than use this toolbox. Best, Rasmus. DeepLearnToolbox ================ A Matlab toolbox for Deep Learning. Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data. It is inspired by the human brain's apparent deep (layered, hierarchical) architecture. A good overview of the theory of Deep Learning theory is [Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf) For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng. * [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007) * [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010) * [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011) If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284) ``` @MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012", } ``` Contact: rasmusbergpalm at gmail dot com Directories included in the toolbox ----------------------------------- `NN/` - A library for Feedforward Backpropagation Neural Networks `CNN/` - A library for Convolutional Neural Networks `DBN/` - A library for Deep Belief Networks `SAE/` - A library for Stacked Auto-Encoders `CAE/` - A library for Convolutional Auto-Encoders `util/` - Utility functions used by the libraries `data/` - Data used by the examples `tests/` - unit tests to verify toolbox is working For references on each library check REFS.md Setup ----- 1. Download. 2. addpath(genpath('DeepLearnToolbox')); Example: Deep Belief Network --------------------- ```matlab function test_example_DBN load mnist_uint8; train_x = double(train_x) / 255; test_x = double(test_x) / 255; train_y = double(train_y); test_y = double(test_y); %% ex1 train a 100 hidden unit RBM and visualize its weights rand('state',0) dbn.sizes = [100]; opts.numepochs = 1; opts.batchsize = 100; opts.momentum = 0; opts.alpha = 1; dbn = dbnsetup(dbn, train_x, opts); dbn = dbntrain(dbn, train_x, opts); figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights %% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NN rand('state',0) %train dbn dbn.sizes = [100 100]; opts.numepochs = 1; opts.batchsize = 100; opts.momentum = 0; opts.alpha = 1; dbn = dbnsetup(dbn, train_x, opts); dbn = dbntrain(dbn, train_x, opts); %unfold dbn to nn nn = dbnunfoldtonn(dbn, 10); nn.activation_function = 'sigm'; %train nn opts.numepochs = 1; opts.batchsize = 100; nn = nntrain(nn, train_x, train_y, opts); [er, bad] = nntest(nn, test_x, test_y); assert(er < 0.10, 'Too big error'); ``` Example: Stacked Auto-Encoders --------------------- ```matlab function test_example_SAE load mnist_uint8; train_x = double(train_x)/255; test_x = double(test_x)/255; train_y = double(train_y); test_y = double(test_y); %% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN % Setup and train a stacked denoising autoencoder (SDAE) rand('state',0) sae = saesetup([784 100]); sae.ae{1}.activation_function = 'sigm'; sae.ae{1}.learningRate = 1; sae.ae{1}.inputZeroMaskedFraction = 0.5; opts.numepochs = 1; opts.batchsize = 100; sae = saetrain(sae, train_x, opts); visualize(sae.ae{1}.W{1}(:,2:end)') % Use the SDAE to initialize a FFNN nn = nnsetup([784 100 10]); nn.activation_function = 'sigm'; nn.learningRate = 1; nn.W{1} = sae.ae{1}.W{1}; % Train the FFNN opts.numepochs = 1; opts.batchsize = 100; nn = nntrain(nn, train_x, train_y, opts); [er, bad] = nntest(nn, test_x, test_y); assert(er < 0.16, 'Too big error'); ``` Example: Convolutional Neural Nets --------------------- ```matlab function test_example_CNN load mnist_uint8; train_x = double(reshape(train_x',28,28,60000))/255; test_x = double(reshape(test_x',28,28,10000))/255; train_y = double(train_y'); test_y = double(test_y'); %% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% error rand('state',0) cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer }; cnn = cnnsetup(cnn, train_x, train_y); opts.alpha = 1; opts.batchsize = 50; opts.numepochs = 1; cnn = cnntrain(cnn, train_x, train_y, opts); [er, bad] = cnntest(cnn, test_x, test_y); %plot mean squared error figure; plot(cnn.rL); assert(er<0.12, 'Too big error'); ``` Example: Neural Networks --------------------- ```matlab function test_example_NN load mnist_uint8; train_x = double(train_x) / 255; test_x = double(test_x) / 255; train_y = double(train_y); test_y = double(test_y); % normalize [train_x, mu, sigma] = zscore(train_x); test_x = normalize(test_x, mu, sigma); %% ex1 vanilla neural net rand('state',0) nn = nnsetup([784 100 10]); opts.numepochs = 1; % Number of full sweeps through data opts.batchsize = 100; % Take a mean gradient step over this many samples [nn, L] = nntrain(nn, train_x, train_y, opts); [er, bad] = nntest(nn, test_x, test_y); assert(er < 0.08, 'Too big error'); %% ex2 neural net with L2 weight decay rand('state',0) nn = nnsetup([784 100 10]); nn.weightPenaltyL2 = 1e-4; % L2 weight decay opts.numepochs = 1; % Number of full sweeps through data opts.batchsize = 100; % Take a mean gradient step over this many samples nn = nntrain(nn, train_x, train_y, opts); [er, bad] = nntest(nn, test_x, test_y); assert(er < 0.1, 'Too big error'); %% ex3 neural net with dropout rand('state',0) nn = nnsetup([784 100 10]); nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through data opts.batchsize = 100; % Take a mean gradient step over this many samples nn = nntrain(nn, train_x, train_y, opts); [er, bad] = nntest(nn, test_x, test_y); assert(er < 0.1, 'Too big error'); %% ex4 neural net with sigmoid activation function rand('state',0) nn = nnsetup([784 100 10]); nn.activation_function = 'sigm'; % Sigmoid activation function nn.learningRate = 1; % Sigm require a lower learning rate opts.numepochs = 1; % Number of full sweeps through data opts.batchsize = 100; % Take a mean gradient step over this many samples nn = nntrain(nn, train_x, train_y, opts); [er, bad] = nntest(nn, test_x, test_y); assert(er < 0.1, 'Too big error'); %% ex5 plotting functionality rand('state',0) nn = nnsetup([784 20 10]); opts.numepochs = 5; % Number of full sweeps through data nn.output = 'softmax'; % use softmax output opts.batchsize = 1000; % Take a mean gradient step over this many samples opts.plot = 1; % enable plotting nn = nntrain(nn, train_x, train_y, opts); [er, bad] = nntest(nn, test_x, test_y); assert(er < 0.1, 'Too big error'); %% ex6 neural net with sigmoid activation and plotting of validation and training error % split training data into training and validation data vx = train_x(1:10000,:); tx = train_x(10001:end,:); vy = train_y(1:10000,:); ty = train_y(10001:end,:); rand('state',0) nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax output opts.numepochs = 5; % Number of full sweeps through data opts.batchsize = 1000; % Take a mean gradient step over this many samples opts.plot = 1; % enable plotting nn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally) [er, bad] = nntest(nn, test_x, test_y); assert(er < 0.1, 'Too big error'); ``` [![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
Deep Learning Toolbox™提供了一个框架,用于设计实现具有算法,预训练模型应用程序的深度神经网络。您可以使用卷积神经网络(ConvNets,CNN)长期短期记忆(LSTM)网络对图像,时间序列文本数据进行分类回归。应用程序图表可帮助您可视化激活,编辑网络体系结构以及监控培训进度。 对于小型训练集,您可以使用预训练的深层网络模型(包括SqueezeNet,Inception-v3,ResNet-101,GoogLeNetVGG-19)以及从TensorFlow™-KerasCaffe导入的模型执行传输学习。 了解深度学习工具箱的基础知识 深度学习图像 从头开始训练卷积神经网络或使用预训练网络快速学习新任务 使用时间序列,序列文本进行深度学习 为时间序列分类,回归预测任务创建训练网络 深度学习调整可视化 绘制培训进度,评估准确性,进行预测,调整培训选项以及可视化网络学习的功能 并行云中的深度学习 通过本地或云中的多个GPU扩展深度学习,并以交互方式或批量作业培训多个网络 深度学习应用 通过计算机视觉,图像处理,自动驾驶,信号音频扩展深度学习工作流程 深度学习导入,导出自定义 导入导出网络,定义自定义深度学习图层以及自定义数据存储 深度学习代码生成 生成MATLAB代码或CUDA ®C ++代码部署深学习网络 函数逼近聚类 使用浅层神经网络执行回归,分类聚类 时间序列控制系统 基于浅网络的模型非线性动态系统; 使用顺序数据进行预测。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值