Below, I'll provide Python code using PyTorch, a popular library for constructing and training neural networks. The first part shows how to create the datasets, while the second part covers building and training the neural networks.
Part 1: Construct the Datasets
a. XOR Dataset
import numpy as np
import torch
# XOR dataset
X_xor = torch.tensor([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=torch.float32)
Y_xor = torch.tensor([[0], [1], [1], [0]], dtype=torch.float32)
b. Sine with Additive White Gaussian Noise
# Sine dataset with noise
np.random.seed(42) # For reproducibility
x_values = np.linspace(0, 2 * np.pi, 100) # 100 data points
sin_values = np.sin(x_values)
noise = np.random.normal(0, 0.1, sin_values.shape) # Small std deviation
y_values = sin_values + noise
X_sine = torch.tensor(x_values, dtype=torch.float32).view(-1, 1)
Y_sine = torch.tensor(y_values, dtype=torch.float32).view(-1, 1)
Part 2: Building and Training Neural Networks
import torch.nn as nn
import torch.optim as optim
# Set up the device for training (CPU or GPU)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Neural network with a single hidden layer
class SingleLayerNetwork(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(SingleLayerNetwork, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.activation = nn.Sigmoid() # Change if required
self.fc2 = nn.Linear(hidden_size, output_size)
def forward(self, x):
x = self.activation(self.fc1(x))
x = torch.sigmoid(self.fc2(x)) # For binary classification output
return x
# Neural network with two hidden layers
class TwoLayerNetwork(nn.Module):
def __init__(self, input_size, hidden_size1, hidden_size2, output_size):
super(TwoLayerNetwork, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size1)
self.activation = nn.Sigmoid() # Change if required
self.fc2 = nn.Linear(hidden_size1, hidden_size2)
self.fc3 = nn.Linear(hidden_size2, output_size)
def forward(self, x):
x = self.activation(self.fc1(x))
x = self.activation(self.fc2(x))
x = torch.sigmoid(self.fc3(x)) # For binary classification output
return x
# Training the XOR network
input_size_xor = 2
hidden_size_xor = 10 # Can be adjusted between 2 and 50
output_size_xor = 1
xor_model = SingleLayerNetwork(input_size_xor, hidden_size_xor, output_size_xor).to(device)
# Loss and optimizer
criterion_xor = nn.BCELoss()
optimizer_xor = optim.SGD(xor_model.parameters(), lr=0.1) # Adjust learning rate as needed
# Training loop for XOR
for epoch in range(1000): # You can adjust the number of epochs
optimizer_xor.zero_grad()
outputs_xor = xor_model(X_xor.to(device))
loss_xor = criterion_xor(outputs_xor, Y_xor.to(device))
loss_xor.backward()
optimizer_xor.step()
if (epoch+1) % 100 == 0: # Print the loss every 100 epochs
print(f'Epoch [{epoch+1}/1000], Loss: {loss_xor.item():.4f}')
# Training the sine network using a TwoLayerNetwork
input_size_sine = 1
hidden_size1_sine = 20 # Can be adjusted between 2 and 50
hidden_size2_sine = 20 # Can be adjusted between 2 and 50
output_size_sine = 1
sine_model = TwoLayerNetwork(input_size_sine, hidden_size1_sine, hidden_size2_sine, output_size_sine).to(device)
# Loss and optimizer for sine
criterion_sine = nn.MSELoss()
optimizer_sine = optim.SGD(sine_model.parameters(), lr=0.01) # Adjust learning rate as needed
# Training loop for sine
for epoch in range(10000): # More epochs might be needed due to noise
optimizer_sine.zero_grad()
outputs_sine = sine_model(X_sine.to(device))
loss_sine = criterion_sine(outputs_sine, Y_sine.to(device))
loss_sine.backward()
optimizer_sine.step()
if (epoch+1) % 1000 == 0: # Print the loss every 1000 epochs
print(f'Epoch [{epoch+1}/10000], Loss: {loss_sine.item():.4f}')
Discussion of Results
For this task, you might find that a single hidden layer network is enough to learn the XOR function since it's a relatively simple problem that just requires the network to capture a non-linear boundary. However, for more complex problems or datasets with more noise, additional layers and neurons might be needed.
As for the sine wave with added noise, the network might require more or fewer epochs to be appropriately trained depending on the level of noise and the chosen architecture. More complex models may overfit to the noise, while too simple models may not capture the underlying sine pattern well. The number of hidden layers and neurons, learning rate, and the number of epochs are all hyperparameters that could require adjustment.
The above code assumes standard values for learning rates and initializes models with a moderate number of neurons. You may need to adjust the hyperparameters and the network architecture as you see fit to achieve better results. Hyperparameters include the learning rate, number of epochs, and the number of neurons in the hidden layers. Regular evaluation on a validation set would be needed to avoid overfitting and to ensure the generalization of the network.