Вот что у меня получилось:
Код: Выделить всё
import torch
import torch.nn as nn
class DynamicCNN(nn.Module):
def __init__(self, input_shape):
super(DynamicCNN, self).__init__()
# Extract input dimensions
input_height, input_width = input_shape
# Dynamically calculate kernel size based on input dimensions
kernel_size = (input_height // 10, input_width // 10)
# Define the CNN layers
self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=kernel_size)
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=(3, 3))
self.fc1 = nn.Linear(64 * (input_height // 4) * (input_width // 4), 128) # Adjust based on pooling
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.pool(torch.relu(self.conv1(x)))
x = self.pool(torch.relu(self.conv2(x)))
x = x.view(-1, self.num_flat_features(x)) # Flatten
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return x
def num_flat_features(self, x):
size = x.size()[1:] # All dimensions except batch size
num_features = 1
for s in size:
num_features *= s
return num_features
# Example: Create the model with an input size of 64x64
input_shape = (64, 64)
model = DynamicCNN(input_shape)
print(model)
- Правильный ли это способ динамического расчета размера ядра в PyTorch или есть лучший способ ( или более дружественный к PyTorch) способ сделать это?
- Будет ли этот подход хорошо масштабироваться для больших изображений или мне следует действовать по-другому?
Будем очень признательны за любые советы или улучшения. !
Подробнее здесь: https://stackoverflow.com/questions/790 ... image-size