0

我一直在使用 pytorch 构建连体神经网络。但我只是通过插入 2 张图片并计算相似度分数来测试它,其中 0 表示图片不同,1 表示图片相同。

import numpy as np
import os, sys
from PIL import Image
dir_name = "/Users/tania/Desktop/Aksara/Compare" #this should contain 26 images only
X = []
for i in os.listdir(dir_name):
    if ".PNG" in i:
        X.append(torch.from_numpy(np.array(Image.open("./Compare/" + i))))

x1 = np.array(Image.open("/Users/tania/Desktop/Aksara/TEST/Ba/B/B.PNG"))
x1 = transforms(x1)
x1 = torch.from_numpy(x1)

#x1 = torch.stack([x1])

closest = 0.0  #highest similarity
closest_letter_idx = 0  #index of closest letter 0=A, 1=B, ...
cnt = 0

for i in X:
    output = model(x1,i) #assuming x1 is your input image
    output = torch.sigmoid(output)
    if output > closest:
        closest_letter_idx = cnt
        closest = output
    cnt += 1

两张图片不同,所以输出

  File "test.py", line 83, in <module>
    X.append(torch.from_numpy(Image.open("./Compare/" + i)))
TypeError: expected np.ndarray (got PngImageFile)

这是目录 在此处输入图像描述

4

1 回答 1

2

是的,有一种方法,您可以使用 softmax 函数:

output = torch.softmax(output)

这将返回 26 个值的张量,每个值对应于图像对应于 26 个类别中的每一个的概率。因此,张量总和为 1 (100%)。

然而,这种方法适用于分类任务,而不是 Siamese Networks。连体网络在输入之间进行比较,而不是将输入分类。从您的问题来看,您似乎正在尝试将 1 张图片与其他 26 张图片进行比较。您可以遍历所有 26 个样本进行比较,计算并保存每个样本的相似度得分,并输出最大值(即如果您不想修改模型):

dir_name = '/Aksara/Compare' #this should contain 26 images only
X = []
for i in os.listdir(dir_name):
    if ".PNG" in i:
        X.append(torch.from_numpy(np.array(Image.open("./Compare/" + i))))

x1 = np.array(Image.open("test.PNG"))
#do your transformations on x1
x1 = torch.from_numpy(x1)
closest = 0.0  #highest similarity
closest_letter_idx = 0  #index of closest letter 0=A, 1=B, ...
cnt = 0

for i in X:
    output = model(x1,i) #assuming x1 is your input image
    output = torch.sigmoid(output)
    if output > closest:
        closest_letter_idx = cnt
        closest = output
    cnt += 1
print(closest_letter_idx)
于 2020-03-14T06:11:56.957 回答