numpy.squeeze | torch.unsqueeze | torch.expand

一、numpy.squeeze函数

  • 作用:从指定数组中删除长度为1的维度
  • 用法:
numpy.squeeze(a, axis=None) # 或者torch.squeeze(a, axis=None)
 - a为指定数组
 - axis不为None时,指定的维度必须是长度为1的单维度;为None时,删除所有长度为1的单维度
  • 举例
import numpy as np
a = np.arange(2).reshape(2, 1, 1)
# array([[[0]],
#       [[1]]])

np.squeeze(a).shape
# (2,)
np.squeeze(a, axis=1).shape
# (2, 1)
np.squeeze(a, axis=2).shape
# (2, 1)

二、torch.unsqueeze函数

squeeze作用相反:在指定数组中加入长度为1的维度。用法类似。

三、torch.expand函数

如下图:
在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
这是对单个文件进行预测“import os import json import torch from PIL import Image from torchvision import transforms import matplotlib.pyplot as plt from model import convnext_tiny as create_model def main(): device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print(f"using {device} device.") num_classes = 5 img_size = 224 data_transform = transforms.Compose( [transforms.Resize(int(img_size * 1.14)), transforms.CenterCrop(img_size), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) # load image img_path = "../tulip.jpg" assert os.path.exists(img_path), "file: '{}' dose not exist.".format(img_path) img = Image.open(img_path) plt.imshow(img) # [N, C, H, W] img = data_transform(img) # expand batch dimension img = torch.unsqueeze(img, dim=0) # read class_indict json_path = './class_indices.json' assert os.path.exists(json_path), "file: '{}' dose not exist.".format(json_path) with open(json_path, "r") as f: class_indict = json.load(f) # create model model = create_model(num_classes=num_classes).to(device) # load model weights model_weight_path = "./weights/best_model.pth" model.load_state_dict(torch.load(model_weight_path, map_location=device)) model.eval() with torch.no_grad(): # predict class output = torch.squeeze(model(img.to(device))).cpu() predict = torch.softmax(output, dim=0) predict_cla = torch.argmax(predict).numpy() print_res = "class: {} prob: {:.3}".format(class_indict[str(predict_cla)], predict[predict_cla].numpy()) plt.title(print_res) for i in range(len(predict)): print("class: {:10} prob: {:.3}".format(class_indict[str(i)], predict[i].numpy())) plt.show() if name == 'main': main()”,改为对指定文件夹下的左右文件进行预测,并绘制混淆矩阵,
06-11
好的,为了实现您的需求,您需要进行以下几个步骤: 1. 加载模型和类别标签: 您需要在代码中加载您的模型和类别标签。您可以使用之前的代码中的方式来加载它们,只需要做一些小的改动即可。例如,您需要将模型和类别标签的路径作为参数传递给您的函数。 2. 加载测试集: 您需要加载您的测试集。您可以使用 `torchvision.datasets.ImageFolder` 来加载测试集。这个函数会将每个文件夹中的所有图像文件都加载到一个 tensor 中,并自动为每个文件夹分配一个标签。 3. 进行预测: 您需要对测试集中的每个图像进行预测,并将预测结果与真实标签进行比较。您可以使用之前的代码中的方式来预测每个图像,只需要做一些小的改动即可。例如,您需要将预测结果保存到一个列表中,并将真实标签保存到另一个列表中。 4. 绘制混淆矩阵: 最后,您需要使用预测结果和真实标签来绘制混淆矩阵。您可以使用 `sklearn.metrics.confusion_matrix` 来计算混淆矩阵,并使用 `matplotlib` 来绘制它。 下面是修改后的代码示例: ``` import os import json import torch from PIL import Image from torchvision import transforms import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix import numpy as np from model import convnext_tiny as create_model def predict_folder(model_path, json_path, folder_path): device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print(f"using {device} device.") num_classes = 5 img_size = 224 data_transform = transforms.Compose([ transforms.Resize(int(img_size * 1.14)), transforms.CenterCrop(img_size), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) # load class_indict json with open(json_path, "r") as f: class_indict = json.load(f) # create model model = create_model(num_classes=num_classes).to(device) # load model weights model.load_state_dict(torch.load(model_path, map_location=device)) model.eval() y_true = [] y_pred = [] for root, dirs, files in os.walk(folder_path): for file in files: if file.endswith(".jpg") or file.endswith(".jpeg"): img_path = os.path.join(root, file) assert os.path.exists(img_path), "file: '{}' dose not exist.".format(img_path) img = Image.open(img_path) # [N, C, H, W] img = data_transform(img) # expand batch dimension img = torch.unsqueeze(img, dim=0) # predict class with torch.no_grad(): output = torch.squeeze(model(img.to(device))).cpu() predict = torch.softmax(output, dim=0) predict_cla = torch.argmax(predict).numpy() y_true.append(class_indict[os.path.basename(root)]) y_pred.append(predict_cla) # plot confusion matrix cm = confusion_matrix(y_true, y_pred) fig, ax = plt.subplots(figsize=(5, 5)) ax.imshow(cm, cmap=plt.cm.Blues, aspect='equal') ax.set_xlabel('Predicted label') ax.set_ylabel('True label') ax.set_xticks(np.arange(len(class_indict))) ax.set_yticks(np.arange(len(class_indict))) ax.set_xticklabels(class_indict.values(), rotation=90) ax.set_yticklabels(class_indict.values()) ax.tick_params(axis=u'both', which=u'both',length=0) for i in range(len(class_indict)): for j in range(len(class_indict)): text = ax.text(j, i, cm[i, j], ha="center", va="center", color="white" if cm[i, j] > cm.max() / 2. else "black") fig.tight_layout() plt.show() if __name__ == '__main__': # set the paths for the model, class_indict json, and test data folder model_path = './weights/best_model.pth' json_path = './class_indices.json' folder_path = './test_data' predict_folder(model_path, json_path, folder_path) ``` 请注意,这个函数的参数需要您自己根据您的实际情况进行设置,以匹配模型、类别标签和测试集的路径。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值