With sufficient training using the Adam optimizer, the model achieves 100% accuracy, correctly learning the XOR function. This contrasts with a standard single neuron, which typically stalls at 50% or 75% accuracy.
1import torch
2import torch.nn as nn
3# Make sure to install the nmn library: pip install nmn
4from nmn.torch.nmn import YatNMN
5
6# Define the model architecture
7class SingleNonLinearNeuron(nn.Module):
8 def __init__(self, input_size, output_size):
9 super(SingleNonLinearNeuron, self).__init__()
10 self.non_linear = YatNMN(input_size, output_size, bias=False)
11 def forward(self, x):
12 return self.non_linear(x)
13
14# Instantiate the model and load the weights from the hub
15# Note: You'll need to have huggingface_hub installed
16from huggingface_hub import hf_hub_download
17model = SingleNonLinearNeuron(input_size=2, output_size=1)
18model_path = hf_hub_download(repo_id="mlnomad/xor-single-nmn-neuron", filename="xor-single-nmn-neuron-model.pth")
19model.load_state_dict(torch.load(model_path))
20model.eval()
21
22# Example prediction
23input_data = torch.tensor([[1.0, 1.0]]) # Expected XOR output: 0
24with torch.no_grad():
25 logits = model(input_data)
26 prob = torch.sigmoid(logits)
27 prediction = (prob > 0.5).float().item()
28 print(f"Input: [1.0, 1.0], Prediction: {prediction}") # Should correctly predict 0.0