pytorch-第⼀章基本操作-强⼤的hub模块使⽤torch的hub模块载⼊模型,输⼊数据进⾏模型的结果输出,对输出的结果做可视化处理
## GITHUB github/pytorch/hub
import torch
model = torch.hub.load('pytorch/vision:v0.4.2', 'deeplabv3_resnet101', pretrained=True)
model.eval()
print(torch.hub.list('pytorch/vision:v0.4.2'))
#数据载⼊,获得图⽚
import urllib
url, filename = ("github/pytorch/hub/raw/master/dog.jpg", "dog.jpg")
try:
urllib.URLopener().retrieve(url, filename)
except:
一块操
from PIL import Image
from torchvision import transforms
input_image = Image.open(filename)
#构建处理图⽚的函数
preprocess = transforms.Compose(
[
transforms.ToTensor(),
transforms.Normalize(mean = [0.485, 0.456, 0.406], std = [0.229, 0.224, 0.225]),
]
)
input_tensor = preprocess(input_image)
input_batch = input_tensor.unsqueeze(0) # 产⽣⼀个样本
if torch.cuda.is_available():
input_batch = ("cuda")
<("cuda")
_grad():
output = model(input_batch)['out'][0]
output_predictions = output.argmax(0)
palette = sor([2 ** 25 - 1, 2 ** 15 - 1, 2 ** 21 - 1])
colors = torch.as_tensor([i for i in range(21)])[:, None] * colors
colors = (colors % 255).numpy().astype("uint8")
r = Image.fromarray(output_predictions.bytes().cpu().numpy()).resize(input_image.size)
r.putpalette(colors)
import matplotlib.pyplot as plt
plt.show(r)