모델에 대한 입력으로 이미지와 벡터를 입력하려고합니다. 이미지는 4d의 올바른 모양을 가지고 있지만 입력 한 벡터에는 그런 모양이 없습니다. 이미지 크기는 424x512이고 벡터는 모양 (18,)입니다. 데이터 로더를 사용한 후에는 (50x1x424x512) 및 (50x18) 모양의 배치를 얻습니다. 모델은 벡터 모양도 4d가되어야하므로 오류가 발생합니다. 어떻게하나요? 내 코드는 다음과 같습니다.
def loadTrainingData_B(args):
fdm = []
tdm = []
parameters = []
for i in image_files[:4]:
try:
false_dm = np.fromfile(join(ref, i), dtype=np.int32)
false_dm = Image.fromarray(false_dm.reshape((424, 512, 9)).astype(np.uint8)[:,:,1])
fdm.append(false_dm)
true_dm = np.fromfile(join(ref, i), dtype=np.int32)
true_dm = Image.fromarray(true_dm.reshape((424, 512, 9)).astype(np.uint8)[:,:,1])
tdm.append(true_dm)
pos = param_filenames.index(i)
param = np.array(params[pos, 1:])
param = np.where(param == '-point-light-source', 1, param).astype(np.float64)
parameters.append(param)
except:
print('[!] File {} not found'.format(i))
return (fdm, parameters, tdm)
class Flat_ModelB(Dataset):
def __init__(self, args, train=True, transform=None):
self.args = args
if train == True:
self.fdm, self.parameters, self.tdm = loadTrainingData_B(self.args)
else:
self.fdm, self.parameters, self.tdm = loadTestData_B(self.args)
self.data_size = len(self.parameters)
self.transform = transforms.Compose([transforms.ToTensor()])
def __getitem__(self, index):
return (self.transform(self.fdm[index]).double(), torch.from_numpy(self.parameters[index]).double(), self.transform(self.tdm[index]).double())
def __len__(self):
return self.data_size
내가 얻는 오류는 다음과 같습니다.
RuntimeError: Expected 4-dimensional input for 4-dimensional weight 32 1 5 5, but got 2-dimensional input of size [50, 18] instead
모델은 다음과 같습니다.
class Model_B(nn.Module):
def __init__(self, config):
super(Model_B, self).__init__()
self.config = config
# CNN layers for fdm
self.layer1 = nn.Sequential(
nn.Conv2d(in_channels=1, out_channels=16, kernel_size=5, stride=2, padding=2),
nn.ReLU(),
nn.BatchNorm2d(16))
self.layer2 = nn.Sequential(
nn.Conv2d(in_channels=16, out_channels=32, kernel_size=5, stride=2, padding=2),
nn.ReLU(),
nn.BatchNorm2d(32))
self.layer3 = nn.Sequential(
nn.Conv2d(in_channels=32, out_channels=32, kernel_size=5, stride=2, padding=2),
nn.ReLU(),
nn.BatchNorm2d(32))
self.layer4 = nn.Sequential(
nn.ConvTranspose2d(in_channels=32, out_channels=32, kernel_size=5, stride=2, padding=2, output_padding=1),
nn.ReLU(),
nn.BatchNorm2d(32))
self.layer5 = nn.Sequential(
nn.ConvTranspose2d(in_channels=32, out_channels=16, kernel_size=5, stride=2, padding=2,output_padding=1),
nn.ReLU(),
nn.BatchNorm2d(16))
self.layer6 = nn.Sequential(
nn.ConvTranspose2d(in_channels=16, out_channels=1, kernel_size=5, stride=2, padding=2, output_padding=1),
nn.ReLU(),
nn.BatchNorm2d(1))
# CNN layer for parameters
self.param_layer1 = nn.Sequential(
nn.Conv2d(in_channels=1, out_channels=32, kernel_size=5, stride=2, padding=2),
nn.ReLU(),
nn.BatchNorm2d(32))
def forward(self, x, y):
out = self.layer1(x)
out_param = self.param_layer1(y)
print("LayerParam 1 Output Shape : {}".format(out_param.shape))
print("Layer 1 Output Shape : {}".format(out.shape))
out = self.layer2(out)
print("Layer 2 Output Shape : {}".format(out.shape))
out = self.layer3(out)
# out = torch.cat((out, out_param), dim=2)
print("Layer 3 Output Shape : {}".format(out.shape))
out = self.layer4(out)
print("Layer 4 Output Shape : {}".format(out.shape))
out = self.layer5(out)
print("Layer 5 Output Shape : {}".format(out.shape))
out = self.layer6(out)
print("Layer 6 Output Shape : {}".format(out.shape))
return out
데이터에 액세스하는 방법 :
for batch_idx, (fdm, parameters) in enumerate(self.data):
if self.config.gpu:
fdm = fdm.to(device)
parameters = parameters.to(device)
print('shape of parameters for model a : {}'.format(parameters.shape))
output = self.model(fdm)
loss = self.criterion(output, parameters)
편집 : (18) 벡터에 컨볼 루션을 적용하려고 할 때 내 코드가 잘못되었다고 생각합니다. 벡터를 복사하여 (18x64)로 만든 다음 입력했습니다. 여전히 작동하지 않으며 다음 출력을 제공합니다.
RuntimeError: Expected 4-dimensional input for 4-dimensional weight 32 1 5 5, but got 3-dimensional input of size [4, 18, 64] instead
이러한 일을 할 수 없다면 18 길이 벡터를 레이어 3의 출력에 연결하는 방법을 모르겠습니다.
오토 인코더 모델을 훈련하고 병목 계층에 추가 벡터 입력을 사용하여 매개 변수화하려는 것 같습니다. 일부 변환을 수행하려면 공간 종속성이 필요한지 여부를 결정해야합니다. 일정한 입력 크기 (N, 1, 424, 512)가 주어지면의 출력은 layer3
모양 (N, 32, 53, 64)을 갖습니다. 원하는 모델 성능에 따라 많은 옵션이 있습니다.
nn.Linear
매개 변수 벡터를 변환하려면 활성화와 함께를 사용하십시오 . 그런 다음 추가 공간 차원을 추가하고 모든 공간 위치에서이 벡터를 반복 할 수 있습니다.img = torch.rand((1, 1, 424, 512))
vec = torch.rand(1, 19)
layer3_out = model(img)
N, C, H, W = layer3_out.shape
param_encoder = nn.Sequential(nn.Linear(19, 30), nn.ReLU(), nn.Linear(30, 10))
param = param_encoder(vec)
param = param.unsqueeze(-1).unsqueeze(-1).expand(N, -1, H, W)
encoding = torch.cat([param, layer3_out], dim=1)
layer3
출력 크기로 업 샘플링합니다 . 그러나 (N, 32, 53, 64)에 맞는 정확한 출력 모양을 계산해야하므로 구현하기가 더 어려울 것입니다.nn.Linear
채널의 2 배 크기로 layer3
변환합니다. 그런 다음 소위 기능별 변환 을 사용하여 layer3
.첫 번째 옵션으로 시작하는 것이 가장 간단한 방법이므로 다른 옵션을 시도해 보는 것이 좋습니다.
Este artículo se recopila de Internet, indique la fuente cuando se vuelva a imprimir.
En caso de infracción, por favor [email protected] Eliminar
Déjame decir algunas palabras