Skip to content
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

Fixes for CHOP #14

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions datasets/covtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

with safe_import_context() as import_ctx:
from sklearn.datasets import fetch_covtype
from sklearn.preprocessing import StandardScaler


class Dataset(BaseDataset):
Expand All @@ -11,9 +12,18 @@ class Dataset(BaseDataset):
install_cmd = 'conda'
requirements = ['pip:scikit-learn']

parameters = {
'standardized': [False, True]
}

def get_data(self):
X, y = fetch_covtype(return_X_y=True)
y[y != 2] = -1
y[y == 2] = 1 # try to separate class 2 from the other 6 classes.

if self.standardized:
scaler = StandardScaler()
X = scaler.fit_transform(X)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would simplify and always standardize.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok -- only for Covtype? It would make sense to do it for all non-sparse datasets, right?

data = dict(X=X, y=y)

return X.shape[1], data
71 changes: 39 additions & 32 deletions solvers/chop.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,17 @@ class Solver(BaseSolver):
name = 'chop'

install_cmd = 'conda'
requirements = ['pip:https://github.com/openopt/chop/archive/master.zip']
requirements = ['pip:https://github.com/openopt/chop/archive/master.zip',
'pip:scikit-learn']
Comment on lines +16 to +17
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
requirements = ['pip:https://github.com/openopt/chop/archive/master.zip',
'pip:scikit-learn']
requirements = ['pip:https://github.com/openopt/chop/archive/master.zip']


parameters = {
'solver': ['pgd'],
'line_search': [False, True],
'line_search': [True, False],
'stochastic': [False, True],
'batch_size': ['full', 1],
'momentum': [0., 0.7],
'momentum': [0., 0.9],
'device': ['cpu', 'cuda']
}
}

def skip(self, X, y, lmbd):
if self.device == 'cuda' and not torch.cuda.is_available():
Expand Down Expand Up @@ -59,23 +60,32 @@ def set_objective(self, X, y, lmbd):

device = torch.device(self.device)

self.X = torch.tensor(X).to(device)
self.y = torch.tensor(y > 0, dtype=torch.float64).to(device)
self.X = torch.tensor(X, dtype=torch.float32, device=device)
self.y = torch.tensor(y, dtype=torch.float32, device=device)

_, n_features = X.shape

self.x0 = torch.zeros(n_features,
dtype=self.X.dtype,
device=self.X.device)
self.criterion = torch.nn.BCEWithLogitsLoss()

# prepare loader for stochastic methods
if self.stochastic:
dataset = TensorDataset(self.X, self.y)
self.loader = DataLoader(dataset, batch_size=self.batch_size)

def logloss(x, data=self.X, target=self.y):
y_X_x = target * (data @ x.flatten())
l2 = 0.5 * x.pow(2).sum()
loss = torch.log1p(torch.exp(-y_X_x)).sum() + self.lmbd * l2
return loss

self.objective = logloss

def run_stochastic(self, n_iter):
# prepare dataset
dataset = TensorDataset(self.X, self.y)
loader = DataLoader(dataset, batch_size=self.batch_size)

# prepare opt variable
x = self.x0.clone().detach().flatten()
x = self.x0.clone().detach()
x.requires_grad_(True)

if self.solver == 'pgd':
Expand All @@ -86,7 +96,6 @@ def run_stochastic(self, n_iter):
raise NotImplementedError

# Optimization loop
counter = 0

alpha = self.lmbd / self.X.size(0)

Expand All @@ -98,45 +107,44 @@ def loglossderiv(p, y):
return -y
return -y / (1. + np.exp(z))

def optimal_step_size(t):
"""From sklearn, from an idea by Leon Bottou"""
def initial_step_size():
p = np.sqrt(1. / np.sqrt(alpha))
eta0 = p / max(1, loglossderiv(-p, 1))
t0 = 1. / (alpha * eta0)
return t0

return 1. / (alpha * (t0 + t - 1.))
t0 = initial_step_size()

while counter < n_iter:
def optimal_step_size(t):
"""From sklearn, from an idea by Leon Bottou"""
return 1. / (alpha * (t0 + t - 1.))

for data, target in loader:
counter = 0
stop = False
while not stop:
for data, target in self.loader:
counter += 1
if counter == n_iter:
stop = True
break
optimizer.lr = optimal_step_size(counter)

optimizer.zero_grad()
pred = data @ x
loss = self.criterion(pred, target)
loss += .5 * alpha * (x ** 2).sum()
loss = self.objective(x, data=data, target=target)
loss.backward()
optimizer.step()

self.beta = x.detach().clone()

def run_full_batch(self, n_iter):
# Set up the problem
@chop.utils.closure
def objective(x):
return self.objective(x, data=self.X, target=self.y)

# chop's full batch optimizers require
# (batch_size, *shape) shape
x0 = self.x0.reshape(1, -1)

@chop.utils.closure
def logloss(x):

alpha = self.lmbd / self.X.size(0)
out = chop.utils.bmv(self.X, x)
loss = self.criterion(out, self.y)
reg = .5 * alpha * (x ** 2).sum()
return loss + reg

# Solve the problem
if self.solver == 'pgd':
if self.line_search:
Expand All @@ -145,8 +153,7 @@ def logloss(x):
# estimate the step using backtracking line search once
step = None

result = chop.optim.minimize_pgd(logloss, x0,
prox=lambda x, s=None: x,
result = chop.optim.minimize_pgd(objective, x0,
step=step,
max_iter=n_iter)

Expand Down