ImageImpaint_Python_II/Net.py

47 lines
1.5 KiB
Python
Raw Permalink Normal View History

import math
2022-07-01 13:35:12 +00:00
import numpy as np
2022-06-01 10:27:58 +00:00
import torch
from torch import nn
2022-06-01 10:27:58 +00:00
class ImageNN(torch.nn.Module):
def __init__(self, precision: np.float32 or np.float64, n_in_channels: int = 1, n_hidden_layers: int = 3,
2022-07-11 21:36:07 +00:00
n_kernels: int = 32, kernel_size: int = 9):
2022-06-28 16:28:36 +00:00
"""Simple CNN with `n_hidden_layers`, `n_kernels`, and `kernel_size` as hyperparameters"""
2022-06-01 10:27:58 +00:00
super().__init__()
2022-07-11 21:36:07 +00:00
ksize = kernel_size
2022-06-28 16:28:36 +00:00
cnn = []
for i in range(n_hidden_layers):
cnn.append(torch.nn.Conv2d(
in_channels=n_in_channels,
out_channels=n_kernels,
2022-07-11 21:36:07 +00:00
kernel_size=ksize,
padding=int(ksize / 2),
padding_mode="replicate"
2022-06-28 16:28:36 +00:00
))
2022-07-11 21:36:07 +00:00
kernel_size -= 2
2022-06-28 16:28:36 +00:00
cnn.append(torch.nn.ReLU())
n_in_channels = n_kernels
self.hidden_layers = torch.nn.Sequential(*cnn)
self.output_layer = torch.nn.Conv2d(
in_channels=n_in_channels,
out_channels=3,
kernel_size=kernel_size,
padding=int(kernel_size / 2)
)
2022-07-01 13:35:12 +00:00
if precision == np.float64:
self.double()
2022-06-28 16:28:36 +00:00
def forward(self, x):
"""Apply CNN to input `x` of shape (N, n_channels, X, Y), where N=n_samples and X, Y are spatial dimensions"""
cnn_out = self.hidden_layers(x) # apply hidden layers (N, n_in_channels, X, Y) -> (N, n_kernels, X, Y)
pred = self.output_layer(cnn_out) # apply output layer (N, n_kernels, X, Y) -> (N, 1, X, Y)
return pred