模型训练完准确率为0的解决方法,以及模型验证方法(resize和reshape区别)

目录

 模型训练完准确率一直为0

完整的模型验证套路:test

reshape和reszie的区别 

debug方法 


 模型训练完准确率一直为0

  • 计算准确率或者输出看loss、准确率时,需要把原来的tensor数据类型,转成普通的数字

即.item()进行转换

total_accuracy = (total_accuracy +accuracy).item()
# 最好转item数据类型,不然这个accuracy会是一个tensor的数据类型,tensor数据类型和一个普通的数据相除,结果一定是0

如果不转,就会输出:

如果Tensor数据类型没有转换,直接用 total_accuracy直接除以测试集10000这一数值,出来的结果会是0

转换后,结果正确:

完整的模型验证套路:test

import torchvision
from PIL import Image
from model import *

image_path ='dog.jpg'
# 用PIL读取图片
PIL_image = Image.open(image_path)
# 定义transform
transform = torchvision.transforms.Compose([torchvision.transforms.Resize((32,32)),torchvision.transforms.ToTensor()])
# PIL图片变成32*32,同时转tensor
tensor_image = transform(PIL_image)
# reshape,加一个batchsize
tensor_image = torch.reshape(tensor_image,(1,3,32,32))
tensor_image = tensor_image.cuda()
print(tensor_image.shape)
# 读取模型
modle = torch.load('module_10.pth')
module1 = Module()

module1.load_state_dict(modle)
module1 = module1.cuda()
# print(module1)

with torch.no_grad():
    output = module1(tensor_image)
    print(output)
    output = (output.argmax(1)).item()
    print(output)

reshape和reszie的区别 

 要注意reshape和resize的区别:

torchvision.transforms.Resize((32,32))

 tensor_image= torch.reshape(tensor_image,(B,C,W,H))

一个是切割裁剪图片,一个是对图片的像素进行重新排列组合,添加BatchSize

debug方法 

  • 此时我们不记得5对应的是哪个类别,可以去代码中debug一下,看看数据集
  • debug是运行到红点的上一行

 

 完成训练!

附一个修狗图片

这玩意都能预测出来是青蛙,厉害了~

### 使用Python训练人脸识别模型 在使用Python进行人脸识别模型训练过程中,可以采用多种方法技术栈。一种常见的做法是利用`face_recognition`库来简化开发过程[^2]。 对于更深入的学习定制化需求,则可能涉及到了解并应用诸如TensorFlow或PyTorch这样的深度学习框架来进行模型构建与优化工作[^1]。下面提供了一个基于OpenCV自定义数据集的人脸识别模型训练流程概述: #### 准备环境 安装必要的依赖项,包括但不限于OpenCV、NumPy以及PIL等图像处理工具包[^3]。 ```bash pip install opencv-python-headless numpy pillow scikit-learn ``` #### 数据收集与预处理 准备用于训练的数据集,确保每张照片都经过标准化处理(如调整大小),以便于后续特征提取操作更加高效稳定[^4]。 ```python import cv2 as cv import os from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder import numpy as np from PIL import Image def load_images_from_folder(folder): images = [] labels = [] for label in os.listdir(folder): path = os.path.join(folder, label) if not os.path.isdir(path): continue for filename in os.listdir(path): img_path = os.path.join(path,filename) try: image = Image.open(img_path).convert("L") # 转灰度图 image = image.resize((100, 100), Image.ANTIALIAS) # 统一尺寸 image_np = np.array(image.getdata()).reshape( (image.size[1], image.size[0])) images.append(image_np) labels.append(label) except Exception as e: print(f"Error loading {img_path}: ", str(e)) return np.asarray(images), np.asarray(labels) X, y = load_images_from_folder('path_to_your_dataset') le = LabelEncoder() y_encoded = le.fit_transform(y) ``` #### 训练分类器 这里选择了LBPH(Local Binary Patterns Histograms)作为人脸描述符,并通过交叉验证的方式评估不同参数组合下的性能表现;当然也可以尝试其他类型的机器学习算法或者神经网络结构以获得更好的效果。 ```python recognizer = cv.face.LBPHFaceRecognizer_create() # 划分测试集训练集 X_train, X_test, y_train, y_test = train_test_split(X, y_encoded, test_size=0.2, random_state=42) # 开始训练 recognizer.train(X_train.tolist(), y_train) # 测试准确性 accuracy = recognizer.predict(np.array([X_test[0]]))[1] print(f'Accuracy on first sample of testing set is: {accuracy}') ``` 上述代码片段展示了如何创建一个人脸识别系统的基础架构,具体到实际应用场景还需要进一步调优超参设置及改进错误率等问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值