-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMNIST_metastable.py
202 lines (144 loc) · 5.77 KB
/
MNIST_metastable.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# %%
import sys
sys.path.append("..")
from utils import HopfieldNet, Flatten # , normmax_bisect
import torch
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
from utils import entmax # , SparseMAP_exactly_k
from collections import Counter
import numpy as np
from prettytable import PrettyTable
from feature_map import FeatureMap, train_separation
import argparse
torch.set_num_threads(5)
parser = argparse.ArgumentParser(description="Synthetic Metastable State")
parser.add_argument("--D", type=int, default=784, help="dimension of memory pattern")
parser.add_argument("--N", type=int, default=5, help="number of memories")
parser.add_argument("--D_phi", type=int, default=200, help="dimension of feature space")
parser.add_argument("--iteration", type=int, default=1, help="iteration of separation training")
parser.add_argument("--lr", type=float, default=0.1, help="lr of separation training")
parser.add_argument("--tau", type=float, default=0.1, help="separation loss temperature")
parser.add_argument("--batch_size", type=int, default=16, help="separation training batch size")
args = parser.parse_args()
# %%
torch.random.manual_seed(42)
# Define the transformations
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(0.5,0.5),
Flatten() # Normalize to [-1, 1]
])
# Load the MNIST dataset
mnist_dataset = datasets.MNIST(root='../datasets', train=True, download=True, transform=transform)
mnist_dataset_test = datasets.MNIST(root='../datasets', train=False, download=True, transform=transform)
# # Create a DataLoader to iterate over the dataset
# data_loader = torch.utils.data.DataLoader(mnist_dataset, batch_size=len(mnist_dataset), shuffle=True)
# # Create a DataLoader to iterate over the dataset
# data_loader_test = torch.utils.data.DataLoader(mnist_dataset_test, batch_size=len(mnist_dataset_test), shuffle=True)
# Create a DataLoader to iterate over the dataset
data_loader = torch.utils.data.DataLoader(mnist_dataset, batch_size=args.batch_size, shuffle=True)
# Create a DataLoader to iterate over the dataset
data_loader_test = torch.utils.data.DataLoader(mnist_dataset_test, batch_size=args.batch_size, shuffle=True)
X_train = []
X_test = []
for data in data_loader:
img, labels_train = data
X_train.append(img)
for data in data_loader_test:
img, labels_test = data
X_test.append(img)
X_train = torch.cat(X_train, dim=0)
X_test = torch.cat(X_test, dim=0)
# for data in data_loader:
# X_train, labels_train = data
# for data in data_loader_test:
# X_test, labels_test = data
def cccp(X, Q, alpha, beta, num_iters, k = None, normmax = False):
results = []
for i in range(Q.size(-1)):
Xi = Q[:, i].unsqueeze(-1) # query
for _ in range(num_iters):
P = entmax(X @ Xi *beta, alpha=alpha, dim=0)
Xi = X.T @ P
results.append(P)
results = torch.cat( results, dim=-1)
return results
def kernelized_cccp(X, raw_memory, Q, alpha, beta, num_iters, w):
# # calculate Phi(memory)
# memories_feat = []
# for i in range(X.size(0)):
# memories_feat.append(X[i])
# memories_feat = torch.cat(memories_feat, dim=0)
results = []
for i in range(Q.size(-1)):
Xi = Q[:, i].unsqueeze(-1) # query
for _ in range(num_iters):
P = entmax(X @ w(Xi.T).T * beta, alpha=alpha, dim=0)
Xi = raw_memory.T @ P
results.append(P)
results = torch.cat( results, dim=-1)
return results
num_iters = 5
eps = 1e-2
# device = torch.device("cuda:" + "0")
# Specify the Column Names while initializing the Table
device = torch.device("cuda")
X_train = X_train.to(device)
X_test = X_test.to(device)
n_samples = X_test.shape[0]
N = X_train.shape[0]
ctrs_total = []
print("running")
def run_cccp(X_train, X_test, num_iters):
tab = PrettyTable(["K", "beta", "alpha", "metastable size"])
ctrs_total = []
n_samples = X_test.shape[0]
N = X_train.shape[0]
for beta in [0.1]:
ctrs = []
for alpha in [1]:
with torch.no_grad():
P = cccp(X_train, X_test.T, alpha, beta, num_iters)
eps_ = eps if alpha == 1 else 0
sizes = (P > eps_).sum(dim=0)
ctr = Counter(sizes.tolist())
ctrs.append(ctr)
ctrs_total.append(ctrs)
for k in range(1, 11):
for i, beta in enumerate([0.1]):
for j, alpha in enumerate([1]):
score = round(ctrs_total[i][j][k]/n_samples * 100, 2)
tab.add_row([k, beta, alpha, score])
print("CCCP")
print(tab)
def run_kernel_cccp(X_train, X_test, num_iters, w):
tab = PrettyTable(["K", "beta", "alpha", "metastable size"])
ctrs_total = []
n_samples = X_test.shape[0]
N = X_train.shape[0]
memories_feat = []
for i in range(X_train.size(0)):
memories_feat.append(w(X_train[i].unsqueeze(0)))
memories_feat = torch.cat(memories_feat, dim=0)
for beta in [0.1]:
ctrs = []
for alpha in [1]:
with torch.no_grad():
P = kernelized_cccp(memories_feat, X_train, X_test.T, alpha, beta, num_iters, w)
eps_ = eps if alpha == 1 else 0
sizes = (P > eps_).sum(dim=0)
ctr = Counter(sizes.tolist())
ctrs.append(ctr)
ctrs_total.append(ctrs)
for k in range(1, 11):
for i, beta in enumerate([0.1]):
for j, alpha in enumerate([1]):
score = round(ctrs_total[i][j][k]/n_samples * 100, 2)
tab.add_row([k, beta, alpha, score])
print("kernelized CCCP")
print(tab)
run_cccp(X_train, X_test, num_iters)
print("training")
w = train_separation(data_loader, args.D, args.D_phi, args.iteration, args.lr, args.tau)
run_kernel_cccp(X_train, X_test, num_iters, w)