a long 1d nmr sequence are input as cnn-resnet, and the corresponding nmr sequence are used as cnn-resnet18 output for denoising in python in python

First, load the input NMR sequence and the corresponding NMR sequence used as the output for denoising. The NMR sequences can be in the form of text files or any other suitable format which can be easily parsed in Python.

main.py
input_sequence = load_sequence("input_sequence.txt")
output_sequence = load_sequence("output_sequence.txt")
108 chars
3 lines

Next, we create a CNN-ResNet18 model in Python using the PyTorch library.

main.py
import torch
import torch.nn as nn
import torchvision.models as models

class NMRResNet(nn.Module):
    def __init__(self):
        super(NMRResNet, self).__init__()
        
        # Load pre-trained ResNet18 as encoder
        self.resnet18 = models.resnet18(pretrained=True)
        
        # Replace the last fully connected layer with a convolutional layer
        self.resnet18.fc = nn.Conv2d(512, 1, kernel_size=1, stride=1, bias=True)
        
        # Define a batch normalization layer
        self.bn = nn.BatchNorm2d(1)
        
    def forward(self, x):
        # Pass the input through the ResNet encoder
        x = self.resnet18(x)
        
        # Apply batch normalization to the output
        x = self.bn(x)
        
        return x
759 chars
26 lines

We then initialize the model and define the optimizer and loss function.

main.py
model = NMRResNet()

optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
criterion = nn.MSELoss()
105 chars
5 lines

Now we define a training loop to train the network using the input and output NMR sequences.

main.py
# Number of training epochs
num_epochs = 10

# Loop over the dataset multiple times
for epoch in range(num_epochs):
    
    running_loss = 0.0
    
    # Loop over the training data in batches
    for i in range(len(input_sequence)):
        
        # Convert the input and output NMR sequences to torch tensors
        input_tensor = torch.Tensor(input_sequence[i])
        output_tensor = torch.Tensor(output_sequence[i])
        
        # Reshape the input and output tensors to be 4-dimensional
        input_tensor = input_tensor.view(1, 1, -1, 1)
        output_tensor = output_tensor.view(1, 1, -1, 1)
        
        # Zero the parameter gradients
        optimizer.zero_grad()
        
        # Forward pass
        output = model(input_tensor)
        
        # Compute the loss
        loss = criterion(output, output_tensor)
        
        # Backward pass and optimization
        loss.backward()
        optimizer.step()
        
        # Add the batch loss to the running loss
        running_loss += loss.item()
        
    # Print the average loss for the epoch
    print(f"Epoch {epoch+1} Loss: {running_loss/len(input_sequence)}")
1159 chars
38 lines

After training the model, we can use it to denoise the input NMR sequence using the following code.

main.py
# Convert the input NMR sequence to a torch tensor
input_tensor = torch.Tensor(input_sequence)

# Reshape the input tensor to be 4-dimensional
input_tensor = input_tensor.view(len(input_sequence), 1, -1, 1)

# Pass the input through the trained model
denoised_output = model(input_tensor)

# Convert the denoised output to a numpy array
denoised_output = denoised_output.detach().numpy()
388 chars
12 lines

The denoised_output variable will now contain the denoised NMR sequence as output by the trained model.

gistlibby LogSnag