The differences between assert , TRACE, ASSERT, VERIFY

今天在路上遇见一个朋友,他急忙地问我关于断言assert的作用,原来他是要去参加面试。关于assert, TRACE, ASSERT, VERIFY这几个宏,以前在编程的时候总结过一些它们的用法,使用的时候比较简单,但是要详细完整地说出它们的作用还是查一下资料好。下面是查阅的一些资料将其整理如下:( 欢迎大家指正:) )



From:《高质量程序设计指南——C++/C语言(第3版)》P.116

如何使用断言(assert)?


断言(assert)的语义如下:如果表达式的值为0(假),则输出错误消息并终止程序的执行(一般还会出现提示对话框,说明在什么地方引发了

assert);如果表达式为非0(真),则不进行任何操作。因此断言失败表明程序存在一个bug。


C++/C的宏assert(expression)就是这样的断言,当表达式为假时,调用库函数abort()终止程序。

程序一般分为Debug版本和Release版本,Debug版本用于内部调试,Release版本发行给用户使用(感觉这种解释有点儿多余)。由于assert(expression)的宏体全部被条件编译伪指令#ifdef _DEBUG和#endif所包含,因此assert()只能在Debug版本里有效。


assert不是一个仓促拼凑起来的宏。为了不在程序的Debug版本和Release版本中造成差别,assert不应该带来任何副作用。所以assert不是函数,而是宏。(这句话不太理解,难道是函数就有差别吗?)


程序员可以把assert看成一个在任何系统状态下都可以安全使用的无害测试手段。所以不要把程序中的assert语句删除掉。


[note 1]:
如果程序在assert处终止了,并不是说含有该assert的函数有错误,而是调用函数出了差错,(这句话好像也不太准确,觉得表述为,如果出现了assert错误,说明assert(expression)中的expression为FALSE,这样理解容易些)。assert可以帮助我们(程序员)追踪到错误发生的原因。


[note 2]:
在函数的入口处,建议使用assert来检查参数的有效性(合法性)。
例如:
内存拷贝函数memcpy,如果assert的expression为假,那么程序就会中止。这样就可以检查程序对memcpy()的调用是否正确。


[note 3]:
请给assert语句加注释,告诉人们assert语句究竟要干什么。


[note 4]:
要注意assert语句仅仅在Debug版本中才有效,而在Release版本中无效。使用assert的目的是捕捉在运行时不应该发生的非法情况(而不是错误情况)。什么是错误情况?

例如:
用malloc返回NULL,动态内存申请失败不是非法情况,而是错误情况。所以我们要用if语句主动捕捉错误情况并给出错误处理代码,而不应该使用assert,否则在Release版本中失效。


[note 5]:
一般教科书都鼓励程序员们进行防错程序设计,但要知道这种编程风格可能会隐瞒错误。当进行防错设计时,如果“不可能发生”的事情的确发生了,则要使用assert进行报警。


[note 6]:
要区分assert和跟踪语句tracer的不同。tracer是指一些用于报告程序执行过程中当前状态的输出语句,相当于printf的作用,但输出的不一定是bug。


[note 7]:
程序通过了assert的检查,并不保证就万无一失了。

例如:

memcpy()中的assert,如果给它传入了两个未初始化的野指针(wild pointer,地址不为0但是没有指向合法的内存块),那么assert()就失去了作用。(所以,我们程序员在使用函数之前,应该避免一些非法操作)


[note 8]:
ASSERT宏中应该包含的元素:判断条件、输出当前断言失败的位置(文件、行数等)、返回错误、终止程序...


[note 9]:
几种典型的ASSERT的写法。


简要概括


<think> Let me analyze this code and provide a helpful response. This appears to be a Python script for training a convolutional neural network (CNN) on the MNIST handwritten digit dataset using PyTorch, and then exporting the trained model to ONNX format. The code consists of several parts: Importing necessary libraries and setting hyperparameters Preparing the MNIST dataset with transformations Visualizing some examples from the dataset Defining a CNN model architecture using PyTorch Setting up loss function and optimizer Defining training and testing functions Training the model for 10 epochs and saving it Exporting the trained model to ONNX format At the end, the user mentions they want to convert their ONNX model to RKNN format but are having version discrepancies. They're using rknn-toolkit2 version 2.3.0 in their code, but on their Ubuntu system they have rknn-toolkit2 version 1.6.0 with Python 3.10. I'll focus on providing a solution for converting their ONNX model to RKNN format, considering the version discrepancy they're experiencing. Let me first understand the model architecture better: Input: MNIST images (1 channel, 28x28 pixels) First convolutional layer: 1→10 channels, 5x5 kernel, followed by ReLU and 2x2 max pooling Second convolutional layer: 10→20 channels, 5x5 kernel, followed by ReLU and 2x2 max pooling Fully connected layers: 320→50→10 (output classes for digits 0-9) The exported ONNX model uses: Input shape: [1, 1, 28, 28] Output shape: [1, 10] (representing probabilities for digits 0-9) ONNX opset version: 19 Now, the issue is the version discrepancy between the rknn-toolkit2 they're using in their code (2.3.0) and what's installed on their Ubuntu system (1.6.0). I need to provide code that will work with their installed version (1.6.0) to convert the ONNX model to RKNN format. </think> I see you've shared a PyTorch script for training a CNN model on the MNIST dataset, followed by ONNX conversion. You mentioned that you need to convert this ONNX model to RKNN format, but there's a version mismatch between the rknn-toolkit2 in your code (2.3.0) and what's installed on your Ubuntu system (1.6.0). Let me create a compatible RKNN conversion script for your system: <artifact id="rknn_conversion_script" type="application/vnd.ant.code" language="python" title="MNIST ONNX to RKNN Conversion Script"> from rknn.api import RKNN Configuration ONNX_MODEL = './model_Mnist_fixed.onnx' RKNN_MODEL = './model_Mnist.rknn' Initialize RKNN object rknn = RKNN(verbose=True) Pre-process config for input print('--> Config model') rknn.config(mean_values=[127.5], std_values=[127.5], target_platform='rk3588') print('done') Load ONNX model print('--> Loading model') ret = rknn.load_onnx(model=ONNX_MODEL) if ret != 0: print('Load ONNX model failed!') exit(ret) print('done') Build model print('--> Building model') ret = rknn.build(do_quantization=True, dataset='./dataset.txt') if ret != 0: print('Build model failed!') exit(ret) print('done') Export RKNN model print('--> Export RKNN model') ret = rknn.export_rknn(RKNN_MODEL) if ret != 0: print('Export RKNN model failed!') exit(ret) print('done') Optional: Inference testing print('--> Testing model on sample data') Set inputs img = cv2.imread('sample_digit.png', cv2.IMREAD_GRAYSCALE) img = cv2.resize(img, (28, 28)) img = np.expand_dims(img, axis=0) # Add batch dimension img = np.expand_dims(img, axis=0) # Add channel dimension Init runtime environment ret = rknn.init_runtime() if ret != 0: print('Init runtime environment failed') exit(ret) Inference print('--> Running model') outputs = rknn.inference(inputs=[img]) predicted = np.argmax(outputs[0][0]) print(f'Predicted digit: {predicted}') Release RKNN context rknn.release() </artifact> Additional Setup for RKNN Conversion For the above script to work properly, you'll need: Create a calibration dataset file: RKNN quantization requires a dataset file listing paths to sample images: <artifact id="dataset_generator" type="application/vnd.ant.code" language="python" title="Calibration Dataset Generator"> import os import numpy as np from torchvision import datasets, transforms import torch Create dataset directory if it doesn't exist os.makedirs('./calibration_images', exist_ok=True) Load a subset of MNIST images for calibration transform = transforms.Compose([transforms.ToTensor()]) dataset = datasets.MNIST(root='./data/mnist', train=True, transform=transform, download=True) data_loader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=True) Save calibration images (using 100 images) with open('./dataset.txt', 'w') as f: for i, (img, ) in enumerate(data_loader): if i >= 100: # Use 100 images for calibration break # Convert tensor to numpy and save as raw format img_np = img.numpy().reshape(28, 28) * 255 img_np = img_np.astype(np.uint8) img_path = f'./calibration_images/img{i:03d}.bin' img_np.tofile(img_path) f.write(f'{img_path}\n') print(f"Created dataset.txt with {min(100, i+1)} image paths for calibration") </artifact> Version Compatibility Notes Since you're using rknn-toolkit2 version 1.6.0 on Ubuntu with Python 3.10, here are some important compatibility considerations: API differences: The script I provided uses the API structure compatible with older versions. The newer 2.3.0 version might have slightly different parameter names or methods. Target platform: I specified 'rk3588' as the target platform. Adjust this if you're targeting a different RK chip. Quantization parameters: The script uses basic quantization settings. You may need to adjust these (particularly mean_values and std_values) based on your model's preprocessing. Testing the model: The optional testing section requires you to have a sample image. You can generate one from your test dataset or skip this section if not needed. Troubleshooting Common Issues If you encounter errors: ONNX compatibility: Older RKNN versions may not support ONNX opset 19. Try re-exporting your ONNX model with a lower opset version (e.g., 11 or 13). Layer support: Some operations might not be supported. Check error messages for unsupported operations and consider simplifying your model if needed. Quantization issues: If quantization fails, try do_quantization=False first to verify the conversion works without quantization. Would you like me to explain any specific part of the conversion process in more detail? 先仔细阅读这部分内容,再来结合这上面的讲解,最终生成适合的转化rknn代码
05-30
提供了基于BP(Back Propagation)神经网络结合PID(比例-积分-微分)控制策略的Simulink仿真模型。该模型旨在实现对杨艺所著论文《基于S函数的BP神经网络PID控制器及Simulink仿真》中的理论进行实践验证。在Matlab 2016b环境下开发,经过测试,确保能够正常运行,适合学习和研究神经网络在控制系统中的应用。 特点 集成BP神经网络:模型中集成了BP神经网络用于提升PID控制器的性能,使之能更好地适应复杂控制环境。 PID控制优化:利用神经网络的自学习能力,对传统的PID控制算法进行了智能调整,提高控制精度和稳定性。 S函数应用:展示了如何在Simulink中通过S函数嵌入MATLAB代码,实现BP神经网络的定制化逻辑。 兼容性说明:虽然开发于Matlab 2016b,但理论上兼容后续版本,可能会需要调整少量配置以适配不同版本的Matlab。 使用指南 环境要求:确保你的电脑上安装有Matlab 2016b或更高版本。 模型加载: 下载本仓库到本地。 在Matlab中打开.slx文件。 运行仿真: 调整模型参数前,请先熟悉各模块功能和输入输出设置。 运行整个模型,观察控制效果。 参数调整: 用户可以自由调节神经网络的层数、节点数以及PID控制器的参数,探索不同的控制性能。 学习和修改: 通过阅读模型中的注释和查阅相关文献,加深对BP神经网络与PID控制结合的理解。 如需修改S函数内的MATLAB代码,建议有一定的MATLAB编程基础。
GPT (Generative Pre-trained Transformer) and BERT (Bidirectional Encoder Representations from Transformers) are both advanced natural language processing (NLP) models developed by OpenAI and Google respectively. Although they share some similarities, there are key differences between the two models. 1. Pre-training Objective: GPT is pre-trained using a language modeling objective, where the model is trained to predict the next word in a sequence of words. BERT, on the other hand, is trained using a masked language modeling objective. In this approach, some words in the input sequence are masked, and the model is trained to predict these masked words based on the surrounding context. 2. Transformer Architecture: Both GPT and BERT use the transformer architecture, which is a neural network architecture that is specifically designed for processing sequential data like text. However, GPT uses a unidirectional transformer, which means that it processes the input sequence in a forward direction only. BERT, on the other hand, uses a bidirectional transformer, which allows it to process the input sequence in both forward and backward directions. 3. Fine-tuning: Both models can be fine-tuned on specific NLP tasks, such as text classification, question answering, and text generation. However, GPT is better suited for text generation tasks, while BERT is better suited for tasks that require a deep understanding of the context, such as question answering. 4. Training Data: GPT is trained on a massive corpus of text data, such as web pages, books, and news articles. BERT is trained on a similar corpus of text data, but it also includes labeled data from specific NLP tasks, such as the Stanford Question Answering Dataset (SQuAD). In summary, GPT and BERT are both powerful NLP models, but they have different strengths and weaknesses depending on the task at hand. GPT is better suited for generating coherent and fluent text, while BERT is better suited for tasks that require a deep understanding of the context.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值