ImageImpaint_Python_II/Net.py

37 lines
1.4 KiB
Python
Raw Normal View History

2022-07-01 13:35:12 +00:00
import numpy as np
2022-06-01 10:27:58 +00:00
import torch
class ImageNN(torch.nn.Module):
2022-07-01 13:35:12 +00:00
def __init__(self, precision: np.float32 or np.float64, n_in_channels: int = 1, n_hidden_layers: int = 3, n_kernels: int = 32, kernel_size: int = 7):
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-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,
kernel_size=kernel_size,
padding=int(kernel_size / 2)
))
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