-
Notifications
You must be signed in to change notification settings - Fork 0
/
code_sample.py
61 lines (51 loc) · 1.63 KB
/
code_sample.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/usr/bin/env python
# coding: utf-8
import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader
import pyepo
from src.model import tspDFJModel
from src.dataset import optDatasetConstrs, collate_fn
from src.cave import innerConeAlignedCosine
# generate data
num_node = 20 # node size
num_data = 100 # number of training data
num_feat = 10 # size of feature
poly_deg = 4 # polynomial degree
noise = 0.5 # noise width
feats, costs = pyepo.data.tsp.genData(num_data, num_feat, num_node, poly_deg, noise, seed=42)
# build predictor
class linearRegression(nn.Module):
def __init__(self):
super(linearRegression, self).__init__()
self.linear = nn.Linear(num_feat, num_node*(num_node-1)//2)
def forward(self, x):
out = self.linear(x)
return out
reg = linearRegression()
# set solver
optmodel = tspDFJModel(num_node)
# get dataset
dataset = optDatasetConstrs(optmodel, feats, costs)
# get data loader
dataloader = DataLoader(dataset, batch_size=32, collate_fn=collate_fn, shuffle=True)
# init loss
cave = innerConeAlignedCosine(optmodel, solver="clarabel", processes=1)
# set optimizer
optimizer = torch.optim.Adam(reg.parameters(), lr=1e-2)
# training
num_epochs = 10
for epoch in range(num_epochs):
for data in dataloader:
# unzip data: only need features and binding constraints
x, _, _, _, bctr = data
# predict cost
cp = reg(x)
# cave loss
loss = cave(cp, bctr)
# backward pass
optimizer.zero_grad()
loss.backward()
optimizer.step()
print("Epoch {:4.0f}, Loss: {:8.4f}".format(epoch, loss.item()))