endswith(),issubset() ,deepcopy,round,eval(),numel(),extend(),argmax,torch.cat(),view()方法

本文介绍了Python中几个关键的内置函数如endswith(),issubset(),deepcopy(),以及与TensorFlow/PyTorch相关的操作如round(),eval(),torch.argmax(),torch.cat(),view(),展示了它们在字符串处理、集合操作和深度学习中的应用。
摘要由CSDN通过智能技术生成

endswith()

方法用于判断字符串是否以指定后缀结尾,如果是则返回 True,否则返回 False

str.endswith(".txt") #能判断str字符串是否以.txt结尾

x.issubset(y)

方法用于判断集合 x 的所有元素是否都包含在集合 y ,如果是则返回 True,否则返回 False

x = {"a", "b", "c"}

y = {"f", "e", "d", "c", "b", "a"}

z = x.issubset(y)

print(z)#输出True

copy.deepcopy()

的用法是将某一个变量的值赋值给另一个变量(此时两个变量地址不同)

a = [1, 2, 3]

d = copy.deepcopy(a) # a和d的地址不相同

python copy.deepcopy()深入解读-CSDN博客

round() 

方法返回浮点数x的四舍五入值

x=round(80.23456, 2)                 #80.23

eval()

用字符串来新建对象,新建列表、元组、字典什么的。

字符串转换为字典

 a = "{1: 'a', 2: 'b'}"

print(type(a))

b = eval(a)

print(type(b))

print(b)

字符串新建对象

class Life():
	animal = 'cat'
	food = 'banana'
	sport = 'run'
	language = 'python'
	def __init__(self):
		pass
 

life1 = Life()
life2 = eval("Life()")

#两种方法都可以新建 Life 类的对象

实际上就是去掉字符串的引号"",直接把那一段字符串输入进代码的对应部分。比如下面两段代码是等价的

class Life():
	animal = 'cat'
	food = 'banana'
	sport = 'run'
	language = 'python'
	def __init__(self):
		pass

a=eval("Life()")
class Life():
	animal = 'cat'
	food = 'banana'
	sport = 'run'
	language = 'python'
	def __init__(self):
		pass

a=Life()

numel()函数

获取tensor中一共包含多少个元素

import torch
x = torch.randn(3,3)
print("number elements of x is ",x.numel())
y = torch.randn(3,10,5)
print("number elements of y is ",y.numel())

输出:

number elements of x is 9
number elements of y is 150

extend()函数

用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)

A = [1, 2, 3]
B = [['a', 'b']]
A.extend([4])
A.extend([5, 6])
B.extend(['c', 'd'])
B.extend([['e', 'f']])
print(A)
print(B)

结果:

[1, 2, 3, 4, 5, 6]
[['a', 'b'], 'c', 'd', ['e', 'f']]

torch.argmax()函数

函数功能:求最大值序号
x = torch.randn(3, 5)
print(x)
print(torch.argmax(x))
print(torch.argmax(x, dim=0))
print(torch.argmax(x, dim=-2))
print(torch.argmax(x, dim=1))
print(torch.argmax(x, dim=-1))

输出:

tensor([[-1.0214,  0.7577, -0.0481, -1.0252,  0.9443],
        [ 0.5071, -1.6073, -0.6960, -0.6066,  1.6297],
        [-0.2776, -1.3551,  0.0036, -0.9210, -0.6517]])
tensor(9)
tensor([1, 0, 2, 1, 1])
tensor([1, 0, 2, 1, 1])
tensor([4, 4, 2])
tensor([4, 4, 2])

torch.cat()函数

在指定维度上对tensor拼接,在深度学习的concat层中常用,一般是

z=[x,y]
z=torch.cat(z,1)#因为第0维是batch_size,第1维一般是channel,[batch_size, ch, w, h]

import torch
x=torch.arange(1,25).reshape([2,3,4])
y=torch.arange(101,125).reshape([2,3,4])

z=[x,y]
print(z)
z=torch.cat(z,1)
print(z)
print(z.shape)

输出

[tensor([[[ 1,  2,  3,  4],
         [ 5,  6,  7,  8],
         [ 9, 10, 11, 12]],

        [[13, 14, 15, 16],
         [17, 18, 19, 20],
         [21, 22, 23, 24]]]), tensor([[[101, 102, 103, 104],
         [105, 106, 107, 108],
         [109, 110, 111, 112]],

        [[113, 114, 115, 116],
         [117, 118, 119, 120],
         [121, 122, 123, 124]]])]
tensor([[[  1,   2,   3,   4],
         [  5,   6,   7,   8],
         [  9,  10,  11,  12],
         [101, 102, 103, 104],
         [105, 106, 107, 108],
         [109, 110, 111, 112]],

        [[ 13,  14,  15,  16],
         [ 17,  18,  19,  20],
         [ 21,  22,  23,  24],
         [113, 114, 115, 116],
         [117, 118, 119, 120],
         [121, 122, 123, 124]]])
torch.Size([2, 6, 4])

view()

相当于reshape()

x = torch.randn(4, 4)
print(x.size())
y = x.view(16)
print(y.size())
z = x.view(-1, 8)  # -1表示该维度取决于其它维度大小,即(4*4)/ 8
print(z.size())
m = x.view(2, 2, 4) # 也可以变为更多维度
print(m.size())

结果:

torch.Size([4, 4])
torch.Size([16])
torch.Size([2, 8])
torch.Size([2, 2, 4])

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这是对单个文件进行预测“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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值