输出列表中张量形状:
import torch
features = [
torch.randn(8, 64, 64, 64),
torch.randn(8, 64, 32, 32),
torch.randn(8, 64, 16, 16),
torch.randn(8, 64, 8, 8)
]
for idx, feature in enumerate(features):
print(f'feature {idx} shape: {feature.shape}')
取列表的最后一个元素predictions_class [-1] :
predictions_class = [
torch.Size([8, 64, 64, 64]),
torch.Size([8, 32, 32, 32]),
torch.Size([8, 16, 16, 16])
]
last_prediction = predictions_class[-1]
print(last_prediction) # 输出: torch.Size([8, 16, 16, 16])
输出张量形状:
print(tensor.shape)
字典由键(key)和值(values)成对表示:
input_shape = {
'res2': ShapeInfo(channels=64, stride=1),
'res3': ShapeInfo(channels=64, stride=2),
'res4': ShapeInfo(channels=64, stride=3),
'res5': ShapeInfo(channels=64, stride=4)
}
按stride对上述四组排序,输出字典内容:
sorted_input_shape = sorted(input_shape.items(), key=lambda x: x[1].stride)
self.in_features = [k for k, v in sorted_input_shape]
feature_channels = [v.channels for k, v in sorted_input_shape]
print("In features:", self.in_features)
print("Feature channels:", feature_channels)
已知输入的张量tensor,获取对应的高度和宽度:
tensor = torch.randn(8, 64, 64, 64)
_, _, height, width = tensor.shape
print(f"Height: {height}")
print(f"Width: {width}")
将张量沿着dim=1的维度进行划分:
x.narrow(1, start, length)