-
Notifications
You must be signed in to change notification settings - Fork 29
RegHD single model regression example #23
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
57d9dda
RegHD single model regression example
dheyay 39a28ca
Format Python code
mikeheddes a7eb310
Updates
dheyay 0b2b858
Updates
dheyay 468fc9d
Format Python code
mikeheddes 95b2506
Update
dheyay 0d05f87
Update on PR
dheyay 5016428
Format Python code
mikeheddes File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,113 @@ | ||
# The following two lines are only needed because of this repository organization | ||
import sys, os | ||
|
||
sys.path.insert(1, os.path.realpath(os.path.pardir)) | ||
|
||
import math | ||
|
||
import torch | ||
import torch.nn as nn | ||
import torch.nn.functional as F | ||
import torch.utils.data as data | ||
|
||
# Note: this example requires the torchmetrics library: https://torchmetrics.readthedocs.io | ||
import torchmetrics | ||
from tqdm import tqdm | ||
|
||
from torchhd import functional | ||
from torchhd import embeddings | ||
from torchhd.datasets import AirfoilSelfNoise | ||
|
||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | ||
print("Using {} device".format(device)) | ||
|
||
DIMENSIONS = 10000 # number of hypervector dimensions | ||
NUM_FEATURES = 5 # number of features in dataset | ||
|
||
ds = AirfoilSelfNoise("../data", download=False) | ||
|
||
# Get necessary statistics for data and target transform | ||
STD_DEVS = ds.data.std(0) | ||
MEANS = ds.data.mean(0) | ||
TARGET_STD = ds.targets.std(0) | ||
TARGET_MEAN = ds.targets.mean(0) | ||
|
||
|
||
def transform(x): | ||
x = x - MEANS | ||
x = x / STD_DEVS | ||
return x | ||
|
||
|
||
def target_transform(x): | ||
x = x - TARGET_MEAN | ||
x = x / TARGET_STD | ||
return x | ||
|
||
|
||
ds.transform = transform | ||
ds.target_transform = target_transform | ||
|
||
# Split the dataset into 70% training and 30% testing | ||
train_size = int(len(ds) * 0.7) | ||
test_size = len(ds) - train_size | ||
train_ds, test_ds = data.random_split(ds, [train_size, test_size]) | ||
|
||
train_dl = data.DataLoader(train_ds, batch_size=1, shuffle=True) | ||
test_dl = data.DataLoader(test_ds, batch_size=1) | ||
|
||
# Model based on RegHD application for Single model regression | ||
class SingleModel(nn.Module): | ||
def __init__(self, num_classes, size): | ||
super(SingleModel, self).__init__() | ||
|
||
self.lr = 0.00001 | ||
self.M = torch.zeros(1, DIMENSIONS) | ||
self.project = embeddings.Projection(size, DIMENSIONS) | ||
self.project.weight.data.normal_(0, 1) | ||
self.bias = nn.parameter.Parameter(torch.empty(DIMENSIONS), requires_grad=False) | ||
self.bias.data.uniform_(0, 2 * math.pi) | ||
|
||
def encode(self, x): | ||
enc = self.project(x) | ||
sample_hv = torch.cos(enc + self.bias) * torch.sin(enc) | ||
return functional.hard_quantize(sample_hv) | ||
|
||
def model_update(self, x, y): | ||
update = self.M + self.lr * (y - (F.linear(x, self.M))) * x | ||
update = update.mean(0) | ||
|
||
self.M = update | ||
|
||
def forward(self, x): | ||
enc = self.encode(x) | ||
res = F.linear(enc, self.M) | ||
return res | ||
|
||
|
||
model = SingleModel(1, NUM_FEATURES) | ||
model = model.to(device) | ||
|
||
# Model training | ||
with torch.no_grad(): | ||
for _ in range(10): | ||
for samples, labels in tqdm(train_dl, desc="Iteration {}".format(_ + 1)): | ||
samples = samples.to(device) | ||
labels = labels.to(device) | ||
|
||
samples_hv = model.encode(samples) | ||
model.model_update(samples_hv, labels) | ||
|
||
# Model accuracy | ||
mse = torchmetrics.MeanSquaredError() | ||
|
||
with torch.no_grad(): | ||
for samples, labels in tqdm(test_dl, desc="Testing"): | ||
samples = samples.to(device) | ||
|
||
predictions = model(samples) | ||
dheyay marked this conversation as resolved.
Show resolved
Hide resolved
|
||
predictions = predictions * TARGET_STD + TARGET_MEAN | ||
labels = labels * TARGET_STD + TARGET_MEAN | ||
mse.update(predictions.cpu(), labels) | ||
|
||
print(f"Testing mean squared error of {(mse.compute().item()):.3f}") |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.