added README.md
Browse files
README.md
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
library_name: pytorch
|
| 4 |
+
---
|
| 5 |
+
|
| 6 |
+
# xor
|
| 7 |
+
|
| 8 |
+
A multi-layer perceptron (MLP) that performs the XOR logical computation. It generates the following truth table:
|
| 9 |
+
|
| 10 |
+
| A | B | C |
|
| 11 |
+
| - | - | - |
|
| 12 |
+
| 0 | 0 | 0 |
|
| 13 |
+
| 0 | 1 | 1 |
|
| 14 |
+
| 1 | 0 | 1 |
|
| 15 |
+
| 1 | 1 | 0 |
|
| 16 |
+
|
| 17 |
+
It takes as input two column vectors of zeros and ones. It outputs a single column vector of zeros and ones.
|
| 18 |
+
|
| 19 |
+
Code: https://github.com/sambitmukherjee/handson-ml3-pytorch/blob/main/chapter10/xor.ipynb
|
| 20 |
+
|
| 21 |
+
## Usage
|
| 22 |
+
|
| 23 |
+
```
|
| 24 |
+
import torch
|
| 25 |
+
import torch.nn as nn
|
| 26 |
+
from huggingface_hub import PyTorchModelHubMixin
|
| 27 |
+
|
| 28 |
+
# Let's create two column vectors containing `0`s and `1`s.
|
| 29 |
+
batch = {'a': torch.tensor([[0.], [0.], [1.], [1.]]), 'b': torch.tensor([[0.], [1.], [0.], [1.]])}
|
| 30 |
+
|
| 31 |
+
class XOR(nn.Module, PyTorchModelHubMixin):
|
| 32 |
+
def __init__(self):
|
| 33 |
+
super().__init__()
|
| 34 |
+
self.layer0_weight = torch.tensor([[1., 1.], [1., 1.]])
|
| 35 |
+
self.layer0_bias = torch.tensor([-1.5, -0.5])
|
| 36 |
+
self.layer1_weight = torch.tensor([[-1.], [1.]])
|
| 37 |
+
self.layer1_bias = torch.tensor([-0.5])
|
| 38 |
+
|
| 39 |
+
def heaviside(self, x):
|
| 40 |
+
return (x >= 0).float()
|
| 41 |
+
|
| 42 |
+
def forward(self, x):
|
| 43 |
+
inputs = torch.cat([x['a'], x['b']], dim=1)
|
| 44 |
+
out = self.heaviside(inputs @ self.layer0_weight + self.layer0_bias)
|
| 45 |
+
out = self.heaviside(out @ self.layer1_weight + self.layer1_bias)
|
| 46 |
+
return out
|
| 47 |
+
|
| 48 |
+
# Instantiate:
|
| 49 |
+
logical_xor = XOR.from_pretrained("sadhaklal/xor")
|
| 50 |
+
|
| 51 |
+
# Forward pass:
|
| 52 |
+
output = logical_xor(batch)
|
| 53 |
+
print(output)
|
| 54 |
+
```
|