repo
stringlengths 2
99
| file
stringlengths 13
225
| code
stringlengths 0
18.3M
| file_length
int64 0
18.3M
| avg_line_length
float64 0
1.36M
| max_line_length
int64 0
4.26M
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
VLC-BERT | VLC-BERT-master/data/conceptual-captions/utils/gen_val4download.py | import os
captions = []
urls = []
with open('Validation_GCC-1.1.0-Validation.tsv') as fp:
for cnt, line in enumerate(fp):
s = line.split('\t')
captions.append(s[0].split(' '))
urls.append(s[1][:-1])
with open('val4download.txt', 'w') as fp:
for cnt, url in enumerate(urls):
fp.write("../val_image/{:08d}.jpg\t\"{}\"\n".format(cnt, url))
if not os.path.exists('../val_image'):
os.makedirs('../val_image') | 459 | 26.058824 | 70 | py |
VLC-BERT | VLC-BERT-master/data/conceptual-captions/utils/check_valid.py | import sys
from PIL import Image
import warnings
warnings.filterwarnings("ignore", "(Possibly )?corrupt EXIF data", UserWarning)
try:
im = Image.open(sys.argv[1]).convert('RGB')
# remove images with too small or too large size
if (im.size[0] < 10 or im.size[1] < 10 or im.size[0] > 10000 or im.size[1] > 10000):
raise Exception('')
except:
print(sys.argv[1])
| 386 | 24.8 | 88 | py |
HVAE | HVAE-master/setup.py | from distutils.core import setup
from setuptools import dist
dist.Distribution().fetch_build_eggs(['Cython', 'numpy<=1.19'])
import numpy
from Cython.Build import cythonize
required = [
"cython",
"numpy",
"torch",
"editdistance",
"scikit-learn",
"tqdm",
"pymoo"
]
setup(name='HVAE',
version='0.1',
description='Hierarchical Variational Autoencoder',
author='smeznar',
packages=['src'],
setup_requires=["numpy", "Cython"],
ext_modules=cythonize("src/cyfunc.pyx"),
include_dirs=[numpy.get_include()],
install_requires=required)
| 606 | 20.678571 | 63 | py |
HVAE | HVAE-master/src/symbolic_regression.py | import argparse
import json
import random
import time
import numpy as np
import torch
from pymoo.algorithms.soo.nonconvex.ga import GA
from pymoo.optimize import minimize
from pymoo.core.problem import ElementwiseProblem
from pymoo.core.sampling import Sampling
from pymoo.core.crossover import Crossover
from pymoo.core.mutation import Mutation
from pymoo.core.termination import Termination
from pymoo.termination.max_gen import MaximumGenerationTermination
from symbol_library import generate_symbol_library
from model import HVAE
from evaluation import RustEval
def read_eq_data(filename):
train = []
with open(filename, "r") as file:
for line in file:
train.append([float(v) for v in line.strip().split(",")])
return np.array(train)
def eval_vector(l, model, eval_obj):
try:
tree = model.decode(l)
error = eval_obj.get_error(tree.to_list(notation="postfix"))
if error is None:
error = 1e10
# else:
# error = np.sqrt(np.square(np.subtract(eval_obj.data[:, -1], y_hat)).mean())
except:
print("Recursion limit")
return 1e10, "", []
return error, str(tree), []
# return error, str(tree), constants
class SRProblem(ElementwiseProblem):
def __init__(self, model, eval_object, dim):
self.model = model
self.eval_object = eval_object
self.input_mean = torch.zeros(next(model.decoder.parameters()).size(0))
self.best_f = 9e+50
self.best_expr = None
self.models = dict()
super().__init__(n_var=dim, n_obj=1)
def _evaluate(self, x, out, *args, **kwargs):
error, expr, constants = eval_vector(torch.tensor(x[None, None, :]), self.model, self.eval_object)
if expr in self.models:
self.models[expr]["trees"] += 1
else:
constants = [float(c) for c in constants]
self.models[expr] = {"expr": expr, "error": error, "trees": 1, "const": constants}
if error < self.best_f:
self.best_f = error
self.best_expr = self.models[expr]
print(f"New best expression: {expr}, with constants [{','.join([str(c) for c in constants])}]")
out["F"] = error
class TorchNormalSampling(Sampling):
def _do(self, problem, n_samples, **kwargs):
return [torch.normal(problem.input_mean).numpy() for _ in range(n_samples)]
class BestTermination(Termination):
def __init__(self, min_f=1e-10, n_max_gen=500) -> None:
super().__init__()
self.min_f = min_f
self.max_gen = MaximumGenerationTermination(n_max_gen)
def _update(self, algorithm):
if algorithm.problem.best_f < self.min_f:
self.terminate()
return self.max_gen.update(algorithm)
class LICrossover(Crossover):
def __init__(self):
super().__init__(2, 1)
def _do(self, problem, X, **kwargs):
weights = np.random.random(X.shape[1])
return (X[0, :]*weights[:, None] + X[1, :]*(1-weights[:, None]))[None, :, :]
class RandomMutation(Mutation):
def __init__(self):
super().__init__()
def _do(self, problem, X, **kwargs):
new = []
for i in range(X.shape[0]):
eq = problem.model.decode(torch.tensor(X[i, :])[None, None, :])
var = problem.model.encode(eq)[1][0, 0].detach().numpy()
mutation_scale = np.random.random()
std = mutation_scale * (np.exp(var / 2.0) - 1) + 1
new.append(torch.normal(torch.tensor(mutation_scale*X[i]), std=torch.tensor(std)).numpy())
return np.array(new, dtype=np.float32)
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog='Nguyen benchmark', description='Run a ED benchmark')
parser.add_argument("-dataset", required=True)
parser.add_argument("-baseline", choices=['HVAE_evo'], required=True)
parser.add_argument("-symbols", nargs="+", required=True)
parser.add_argument("-num_vars", default=2, type=int)
parser.add_argument("-has_const", action="store_true")
parser.add_argument("-latent", default=32, type=int)
parser.add_argument("-params", required=True)
parser.add_argument("-success_threshold", default=1e-8)
parser.add_argument("-seed", type=int)
args = parser.parse_args()
# -----------------------------------------------------------------------------------------------------------------
#
# WORK IN PROGRESS, USE SR SCRIPTS FROM ProGED
# (https://github.com/smeznar/ProGED/blob/main/ProGED/examples/ng_bench.py)
# TO EVALUATE THE RESULTS
#
# -----------------------------------------------------------------------------------------------------------------
if args.seed is not None:
np.random.seed(args.seed)
torch.manual_seed(args.seed)
random.seed(args.seed)
# Read data
train = read_eq_data(args.dataset)
symbols = generate_symbol_library(args.num_vars, args.symbols, args.has_const)
input_dim = len(symbols)
HVAE.add_symbols(symbols)
model = torch.load(args.params)
# fe = FastEval(train, args.num_vars, symbols, has_const=args.has_const)
fe = RustEval(train)
if args.baseline == "HVAE_evo":
ga = GA(pop_size=200, sampling=TorchNormalSampling(), crossover=LICrossover(), mutation=RandomMutation(),
eliminate_duplicates=False)
problem = SRProblem(model, fe, args.latent)
res = minimize(problem, ga, BestTermination(min_f=args.success_threshold), verbose=True)
with open(f"../results/nguyen/{args.dataset.strip().split('/')[-1]}_{time.time()}.json", "w") as file:
json.dump({"best": problem.best_expr, "all": list(problem.models.values())}, file)
# if args.baseline == "HVAE_random":
# fe = FastEval(train, args.num_vars, symbols, has_const=args.has_const)
# generator = GeneratorHVAE(args.params, ["X"], universal_symbols)
# ed = EqDisco(data=train, variable_names=["X", 'Y'], generator=generator, sample_size=100000, verbosity=0)
# ed.generate_models()
# ed.fit_models()
# print(len(ed.models))
# print(ed.get_results())
# ed.write_results(f"results/hvae_random_{args.dimension}/nguyen_{args.eq_num}_{np.random.randint(0, 1000000)}.json")
| 6,382 | 37.920732 | 125 | py |
HVAE | HVAE-master/src/batch_model.py | import torch
from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn as nn
from tree import Node, BatchedNode
from symbol_library import SymType
class HVAE(nn.Module):
_symbols = None
def __init__(self, input_size, output_size, hidden_size=None):
super(HVAE, self).__init__()
if hidden_size is None:
hidden_size = output_size
self.encoder = Encoder(input_size, hidden_size, output_size)
self.decoder = Decoder(output_size, hidden_size, input_size)
def forward(self, tree):
mu, logvar = self.encoder(tree)
z = self.sample(mu, logvar)
out = self.decoder(z, tree)
return mu, logvar, out
def sample(self, mu, logvar):
eps = Variable(torch.randn(mu.size()))
std = torch.exp(logvar / 2.0)
return mu + eps * std
def encode(self, tree):
mu, logvar = self.encoder(tree)
return mu, logvar
def decode(self, z):
if HVAE._symbols is None:
raise Exception("To generate expression trees, a symbol library is needed. Please add it using the"
" HVAE.add_symbols method.")
return self.decoder.decode(z, HVAE._symbols)
@staticmethod
def add_symbols(symbols):
HVAE._symbols = symbols
Node.add_symbols(symbols)
BatchedNode.add_symbols(symbols)
class Encoder(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(Encoder, self).__init__()
self.hidden_size = hidden_size
self.gru = GRU221(input_size=input_size, hidden_size=hidden_size)
self.mu = nn.Linear(in_features=hidden_size, out_features=output_size)
self.logvar = nn.Linear(in_features=hidden_size, out_features=output_size)
torch.nn.init.xavier_uniform_(self.mu.weight)
torch.nn.init.xavier_uniform_(self.logvar.weight)
def forward(self, tree):
# Check if the tree has target vectors
if tree.target is None:
tree.add_target_vectors()
tree_encoding = self.recursive_forward(tree)
mu = self.mu(tree_encoding)
logvar = self.logvar(tree_encoding)
return mu, logvar
def recursive_forward(self, tree):
left = self.recursive_forward(tree.left) if tree.left is not None \
else torch.zeros(tree.target.size(0), 1, self.hidden_size)
right = self.recursive_forward(tree.right) if tree.right is not None \
else torch.zeros(tree.target.size(0), 1, self.hidden_size)
# left = left.mul(tree.mask[:, None, None])
# right = right.mul(tree.mask[:, None, None])
hidden = self.gru(tree.target, left, right)
hidden = hidden.mul(tree.mask[:, None, None])
return hidden
class Decoder(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(Decoder, self).__init__()
self.hidden_size = hidden_size
self.z2h = nn.Linear(input_size, hidden_size)
self.h2o = nn.Linear(hidden_size, output_size)
self.gru = GRU122(input_size=output_size, hidden_size=hidden_size)
torch.nn.init.xavier_uniform_(self.z2h.weight)
torch.nn.init.xavier_uniform_(self.h2o.weight)
# Used during training to guide the learning process
def forward(self, z, tree):
hidden = self.z2h(z)
self.recursive_forward(hidden, tree)
return tree
def recursive_forward(self, hidden, tree):
prediction = self.h2o(hidden)
symbol_probs = F.softmax(prediction, dim=2)
tree.prediction = prediction
if tree.left is not None or tree.right is not None:
left, right = self.gru(symbol_probs, hidden)
if tree.left is not None:
self.recursive_forward(left, tree.left)
if tree.right is not None:
self.recursive_forward(right, tree.right)
# Used for inference to generate expression trees from latent vectorS
def decode(self, z, symbol_dict):
with torch.no_grad():
mask = torch.ones(z.size(0)).bool()
hidden = self.z2h(z)
batch = self.recursive_decode(hidden, symbol_dict, mask)
return batch.to_expr_list()
def recursive_decode(self, hidden, symbol_dict, mask):
prediction = F.softmax(self.h2o(hidden), dim=2)
# Sample symbol in a given node
symbols, left_mask, right_mask = self.sample_symbol(prediction, symbol_dict, mask)
left, right = self.gru(prediction, hidden)
if torch.any(left_mask):
l_tree = self.recursive_decode(left, symbol_dict, left_mask)
else:
l_tree = None
if torch.any(right_mask):
r_tree = self.recursive_decode(right, symbol_dict, right_mask)
else:
r_tree = None
node = BatchedNode()
node.symbols = symbols
node.left = l_tree
node.right = r_tree
return node
def sample_symbol(self, prediction, symbol_dict, mask):
sampled = F.softmax(prediction, dim=2)
# Select the symbol with the highest value ("probability")
symbols = []
left_mask = torch.clone(mask)
right_mask = torch.clone(mask)
for i in range(sampled.size(0)):
if mask[i]:
symbol = symbol_dict[torch.argmax(sampled[i, 0, :])]
symbols.append(symbol["symbol"])
if symbol["type"].value is SymType.Fun.value:
right_mask[i] = False
if symbol["type"].value is SymType.Var.value or symbol["type"].value is SymType.Const.value:
left_mask[i] = False
right_mask[i] = False
else:
symbols.append("")
return symbols, left_mask, right_mask
class GRU221(nn.Module):
def __init__(self, input_size, hidden_size):
super(GRU221, self).__init__()
self.wir = nn.Linear(in_features=input_size, out_features=hidden_size)
self.whr = nn.Linear(in_features=2*hidden_size, out_features=hidden_size)
self.wiz = nn.Linear(in_features=input_size, out_features=hidden_size)
self.whz = nn.Linear(in_features=2 * hidden_size, out_features=hidden_size)
self.win = nn.Linear(in_features=input_size, out_features=hidden_size)
self.whn = nn.Linear(in_features=2 * hidden_size, out_features=hidden_size)
torch.nn.init.xavier_uniform_(self.wir.weight)
torch.nn.init.xavier_uniform_(self.whr.weight)
torch.nn.init.xavier_uniform_(self.wiz.weight)
torch.nn.init.xavier_uniform_(self.whz.weight)
torch.nn.init.xavier_uniform_(self.win.weight)
torch.nn.init.xavier_uniform_(self.whn.weight)
def forward(self, x, h1, h2):
h = torch.cat([h1, h2], dim=2)
r = torch.sigmoid(self.wir(x) + self.whr(h))
z = torch.sigmoid(self.wiz(x) + self.whz(h))
n = torch.tanh(self.win(x) + r * self.whn(h))
return (1 - z) * n + (z / 2) * h1 + (z / 2) * h2
class GRU122(nn.Module):
def __init__(self, input_size, hidden_size):
super(GRU122, self).__init__()
self.hidden_size = hidden_size
self.wir = nn.Linear(in_features=input_size, out_features=2*hidden_size)
self.whr = nn.Linear(in_features=hidden_size, out_features=2*hidden_size)
self.wiz = nn.Linear(in_features=input_size, out_features=2*hidden_size)
self.whz = nn.Linear(in_features=hidden_size, out_features=2*hidden_size)
self.win = nn.Linear(in_features=input_size, out_features=2*hidden_size)
self.whn = nn.Linear(in_features=hidden_size, out_features=2*hidden_size)
torch.nn.init.xavier_uniform_(self.wir.weight)
torch.nn.init.xavier_uniform_(self.whr.weight)
torch.nn.init.xavier_uniform_(self.wiz.weight)
torch.nn.init.xavier_uniform_(self.whz.weight)
torch.nn.init.xavier_uniform_(self.win.weight)
torch.nn.init.xavier_uniform_(self.whn.weight)
def forward(self, x, h):
r = torch.sigmoid(self.wir(x) + self.whr(h))
z = torch.sigmoid(self.wiz(x) + self.whz(h))
n = torch.tanh(self.win(x) + r * self.whn(h))
dh = h.repeat(1, 1, 2)
out = (1 - z) * n + z * dh
return torch.split(out, self.hidden_size, dim=2)
| 8,343 | 38.545024 | 111 | py |
HVAE | HVAE-master/src/batch_train.py | from argparse import ArgumentParser
import numpy as np
import torch
from torch.utils.data import Sampler, Dataset, DataLoader
from tqdm import tqdm
# from utils import tokens_to_tree, read_expressions
from utils import read_expressions_json
from batch_model import HVAE
from symbol_library import generate_symbol_library
from tree import BatchedNode
def collate_fn(batch):
return batch
class TreeSampler(Sampler):
def __init__(self, batch_size, num_eq):
self.batch_size = batch_size
self.num_eq = num_eq
def __iter__(self):
for i in range(len(self)):
batch = np.random.randint(low=0, high=self.num_eq, size=self.batch_size)
yield batch
def __len__(self):
return self.num_eq // self.batch_size
class TreeBatchSampler(Sampler):
def __init__(self, batch_size, num_eq):
self.batch_size = batch_size
self.num_eq = num_eq
self.permute = np.random.permutation(self.num_eq)
def __iter__(self):
for i in range(len(self)):
batch = self.permute[(i*32):((i+1)*32)]
yield batch
def __len__(self):
return self.num_eq // self.batch_size
class TreeDataset(Dataset):
def __init__(self, train):
self.train = train
def __getitem__(self, idx):
return self.train[idx]
def __len__(self):
return len(self.train)
def create_batch(trees):
t = BatchedNode(trees=trees)
t.create_target()
return t
def logistic_function(iter, total_iters, supremum=0.045):
x = iter/total_iters
return supremum/(1+50*np.exp(-10*x))
def train_hvae(model, trees, epochs=20, batch_size=32, verbose=True):
dataset = TreeDataset(trees)
optimizer = torch.optim.Adam(model.parameters())
criterion = torch.nn.CrossEntropyLoss(ignore_index=-1, reduction="mean")
iter_counter = 0
total_iters = epochs*(len(dataset)//batch_size)
lmbda = logistic_function(iter_counter, total_iters)
midpoint = len(dataset) // (2 * batch_size)
for epoch in range(epochs):
sampler = TreeBatchSampler(batch_size, len(dataset))
bce, kl, total, num_iters = 0, 0, 0, 0
with tqdm(total=len(dataset), desc=f'Testing - Epoch: {epoch + 1}/{epochs}', unit='chunks') as prog_bar:
for i, tree_ids in enumerate(sampler):
batch = create_batch([dataset[j] for j in tree_ids])
mu, logvar, outputs = model(batch)
loss, bcel, kll = outputs.loss(mu, logvar, lmbda, criterion)
bce += bcel.detach().item()
kl += kll.detach().item()
optimizer.zero_grad()
loss.backward()
optimizer.step()
num_iters += 1
prog_bar.set_postfix(**{'run:': "HVAE",
'loss': (bce+kl) / num_iters,
'BCE': bce / num_iters,
'KLD': kl / num_iters})
prog_bar.update(batch_size)
lmbda = logistic_function(iter_counter, total_iters)
iter_counter += 1
if verbose and i == midpoint:
original_trees = batch.to_expr_list()
z = model.encode(batch)[0]
decoded_trees = model.decode(z)
for i in range(10):
print("--------------------")
print(f"O: {original_trees[i]}")
print(f"P: {decoded_trees[i]}")
a = 0
if __name__ == '__main__':
parser = ArgumentParser(prog='Train HVAE', description='A script for training the HVAE model.')
parser.add_argument("-expressions", required=True)
parser.add_argument("-symbols", nargs="+", required=True)
parser.add_argument("-batch", default=32, type=int)
parser.add_argument("-num_vars", default=2, type=int)
parser.add_argument("-has_const", action="store_true")
parser.add_argument("-latent_size", default=32, type=int)
parser.add_argument("-epochs", default=20, type=int)
parser.add_argument("-param_path", default="")
parser.add_argument("-annealing_iters", default=3000, type=int)
parser.add_argument("-verbose", action="store_true")
parser.add_argument("-seed", type=int)
args = parser.parse_args()
if args.seed is not None:
np.random.seed(args.seed)
torch.manual_seed(args.seed)
symbols = generate_symbol_library(args.num_vars, args.symbols, args.has_const)
HVAE.add_symbols(symbols)
s2t = {s["symbol"]: s for s in symbols}
trees = read_expressions_json(args.expressions)
model = HVAE(len(symbols), args.latent_size)
train_hvae(model, trees, args.epochs, args.batch, args.verbose)
if args.param_path != "":
torch.save(model, args.param_path)
| 4,883 | 31.778523 | 112 | py |
HVAE | HVAE-master/src/tree.py | import torch
from torch.autograd import Variable
class Node:
_symbols = None
_s2c = None
def __init__(self, symbol=None, right=None, left=None):
self.symbol = symbol
self.right = right
self.left = left
self.target = None
self.prediction = None
def __str__(self):
return "".join(self.to_list())
def __len__(self):
left = len(self.left) if self.left is not None else 0
right = len(self.right) if self.right is not None else 0
return 1 + left + right
def height(self):
hl = self.left.height() if self.left is not None else 0
hr = self.right.height() if self.right is not None else 0
return max(hl, hr) + 1
def to_list(self, notation="infix"):
if notation == "infix" and Node._symbols is None:
raise Exception("To generate a list of token in the infix notation, symbol library is needed. Please use"
" the Node.add_symbols methods to add them, before using the to_list method.")
left = [] if self.left is None else self.left.to_list(notation)
right = [] if self.right is None else self.right.to_list(notation)
if notation == "prefix":
return [self.symbol] + left + right
elif notation == "postfix":
return left + right + [self.symbol]
elif notation == "infix":
if len(left) > 0 and len(right) == 0 and Node.symbol_precedence(self.symbol) > 0:
return [self.symbol] + ["("] + left + [")"]
elif len(left) > 0 >= Node.symbol_precedence(self.symbol) and len(right) == 0:
return ["("] + left + [")"] + [self.symbol]
if self.left is not None \
and -1 < Node.symbol_precedence(self.left.symbol) < Node.symbol_precedence(self.symbol):
left = ["("] + left + [")"]
if self.right is not None \
and -1 < Node.symbol_precedence(self.right.symbol) < Node.symbol_precedence(self.symbol):
right = ["("] + right + [")"]
return left + [self.symbol] + right
else:
raise Exception("Invalid notation selected. Use 'infix', 'prefix', 'postfix'.")
def to_pexpr(self):
if Node._symbols is None:
raise Exception("To generate a pexpr, symbol library is needed. Please use"
" the Node.add_symbols methods to add them, before using the to_list method.")
left = [] if self.left is None else self.left.to_pexpr()
right = [] if self.right is None else self.right.to_pexpr()
return [Node._symbols[Node._s2c[self.symbol]]["psymbol"]] + left + right
def add_target_vectors(self):
if Node._symbols is None:
raise Exception("Encoding needs a symbol library to create target vectors. Please use Node.add_symbols"
" method to add a symbol library to trees before encoding.")
target = torch.zeros(len(Node._symbols)).float()
target[Node._s2c[self.symbol]] = 1.0
self.target = Variable(target[None, None, :])
if self.left is not None:
self.left.add_target_vectors()
if self.right is not None:
self.right.add_target_vectors()
def loss(self, mu, logvar, lmbda, criterion):
pred = Node.to_matrix(self, "prediction")
target = Node.to_matrix(self, "target")
BCE = criterion(pred, target)
KLD = (lmbda * -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp()))
return BCE + KLD, BCE, KLD
def clear_prediction(self):
if self.left is not None:
self.left.clear_prediction()
if self.right is not None:
self.right.clear_prediction()
self.prediction = None
def to_dict(self):
d = {'s': self.symbol}
if self.left is not None:
d['l'] = self.left.to_dict()
if self.right is not None:
d['r'] = self.right.to_dict()
return d
@staticmethod
def from_dict(d):
left = None
right = None
if "l" in d:
left = Node.from_dict(d["l"])
if 'r' in d:
right = Node.from_dict(d["r"])
return Node(d["s"], right=right, left=left)
@staticmethod
def symbol_precedence(symbol):
return Node._symbols[Node._s2c[symbol]]["precedence"]
@staticmethod
def to_matrix(tree, matrix_type="prediction"):
reps = []
if tree.left is not None:
reps.append(Node.to_matrix(tree.left, matrix_type))
if matrix_type == "target":
reps.append(torch.Tensor([Node._s2c[tree.symbol]]).long())
else:
reps.append(tree.prediction[0, :, :])
if tree.right is not None:
reps.append(Node.to_matrix(tree.right, matrix_type))
return torch.cat(reps)
@staticmethod
def add_symbols(symbols):
Node._symbols = symbols
Node._s2c = {s["symbol"]: i for i, s in enumerate(symbols)}
class BatchedNode():
_symbols = None
_s2c = None
def __init__(self, size=0, trees=None):
self.symbols = ["" for _ in range(size)]
self.left = None
self.right = None
if trees is not None:
for tree in trees:
self.add_tree(tree)
@staticmethod
def add_symbols(symbols):
BatchedNode._symbols = symbols
BatchedNode._s2c = {s["symbol"]: i for i, s in enumerate(symbols)}
def add_tree(self, tree=None):
if tree is None:
self.symbols.append("")
if self.left is not None:
self.left.add_tree()
if self.right is not None:
self.right.add_tree()
else:
self.symbols.append(tree.symbol)
if self.left is not None and tree.left is not None:
self.left.add_tree(tree.left)
elif self.left is not None:
self.left.add_tree()
elif tree.left is not None:
self.left = BatchedNode(size=len(self.symbols)-1)
self.left.add_tree(tree.left)
if self.right is not None and tree.right is not None:
self.right.add_tree(tree.right)
elif self.right is not None:
self.right.add_tree()
elif tree.right is not None:
self.right = BatchedNode(size=len(self.symbols)-1)
self.right.add_tree(tree.right)
def loss(self, mu, logvar, lmbda, criterion):
pred = BatchedNode.get_prediction(self)
pred = torch.permute(pred, [0, 2, 1])
target = BatchedNode.get_target(self)
BCE = criterion(pred, target)
KLD = (lmbda * -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp()))/mu.size(0)
return BCE + KLD, BCE, KLD
def create_target(self):
if BatchedNode._symbols is None:
raise Exception("Encoding needs a symbol library to create target vectors. Please use"
" BatchedNode.add_symbols method to add a symbol library to trees before encoding.")
target = torch.zeros((len(self.symbols), 1, len(Node._symbols)))
mask = torch.ones(len(self.symbols))
for i, s in enumerate(self.symbols):
if s == "":
mask[i] = 0
else:
target[i, 0, Node._s2c[s]] = 1
self.mask = mask
self.target = Variable(target)
if self.left is not None:
self.left.create_target()
if self.right is not None:
self.right.create_target()
def to_expr_list(self):
exprs = []
for i in range(len(self.symbols)):
exprs.append(self.get_expr_at_idx(i))
return exprs
def get_expr_at_idx(self, idx):
symbol = self.symbols[idx]
if symbol == "":
return None
left = self.left.get_expr_at_idx(idx) if self.left is not None else None
right = self.right.get_expr_at_idx(idx) if self.right is not None else None
return Node(symbol, left=left, right=right)
@staticmethod
def get_prediction(tree):
reps = []
if tree.left is not None:
reps.append(BatchedNode.get_prediction(tree.left))
target = tree.prediction[:, 0, :]
reps.append(target[:, None, :])
if tree.right is not None:
reps.append(BatchedNode.get_prediction(tree.right))
return torch.cat(reps, dim=1)
@staticmethod
def get_target(tree):
reps = []
if tree.left is not None:
reps.append(BatchedNode.get_target(tree.left))
target = torch.zeros(len(tree.symbols)).long()
for i, s in enumerate(tree.symbols):
if s == "":
target[i] = -1
else:
target[i] = BatchedNode._s2c[s]
reps.append(target[:, None])
if tree.right is not None:
reps.append(BatchedNode.get_target(tree.right))
return torch.cat(reps, dim=1)
| 9,097 | 34.263566 | 117 | py |
HVAE | HVAE-master/src/utils.py | import json
from symbol_library import SymType
from tree import Node
def read_expressions(filepath):
expressions = []
with open(filepath, "r") as file:
for line in file:
expressions.append(line.strip().split(" "))
return expressions
def read_expressions_json(filepath):
with open(filepath, "r") as file:
return [Node.from_dict(d) for d in json.load(file)]
def tokens_to_tree(tokens, symbols):
"""
tokens : list of string tokens
symbols: dictionary of possible tokens -> attributes, each token must have attributes: nargs (0-2), order
"""
num_tokens = len([t for t in tokens if t != "(" and t != ")"])
expr_str = ''.join(tokens)
tokens = ["("] + tokens + [")"]
operator_stack = []
out_stack = []
for token in tokens:
if token == "(":
operator_stack.append(token)
elif token in symbols and symbols[token]["type"] in [SymType.Var, SymType.Const, SymType.Literal]:
out_stack.append(Node(token))
elif token in symbols and symbols[token]["type"] is SymType.Fun:
if symbols[token]["precedence"] <= 0:
out_stack.append(Node(token, left=out_stack.pop()))
else:
operator_stack.append(token)
elif token in symbols and symbols[token]["type"] is SymType.Operator:
while len(operator_stack) > 0 and operator_stack[-1] != '(' \
and symbols[operator_stack[-1]]["precedence"] > symbols[token]["precedence"]:
if symbols[operator_stack[-1]]["type"] is SymType.Fun:
out_stack.append(Node(operator_stack.pop(), left=out_stack.pop()))
else:
out_stack.append(Node(operator_stack.pop(), out_stack.pop(), out_stack.pop()))
operator_stack.append(token)
else:
while len(operator_stack) > 0 and operator_stack[-1] != '(':
if symbols[operator_stack[-1]]["type"] is SymType.Fun:
out_stack.append(Node(operator_stack.pop(), left=out_stack.pop()))
else:
out_stack.append(Node(operator_stack.pop(), out_stack.pop(), out_stack.pop()))
operator_stack.pop()
if len(operator_stack) > 0 and operator_stack[-1] in symbols \
and symbols[operator_stack[-1]]["type"] is SymType.Fun:
out_stack.append(Node(operator_stack.pop(), left=out_stack.pop()))
if len(out_stack[-1]) == num_tokens:
return out_stack[-1]
else:
raise Exception(f"Error while parsing expression {expr_str}.")
| 2,630 | 41.435484 | 109 | py |
HVAE | HVAE-master/src/model.py | import torch
from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn as nn
from tree import Node
from symbol_library import SymType
class HVAE(nn.Module):
_symbols = None
def __init__(self, input_size, output_size, hidden_size=None):
super(HVAE, self).__init__()
if hidden_size is None:
hidden_size = output_size
self.encoder = Encoder(input_size, hidden_size, output_size)
self.decoder = Decoder(output_size, hidden_size, input_size)
def forward(self, tree):
mu, logvar = self.encoder(tree)
z = self.sample(mu, logvar)
out = self.decoder(z, tree)
return mu, logvar, out
def sample(self, mu, logvar):
eps = Variable(torch.randn(mu.size()))
std = torch.exp(logvar / 2.0)
return mu + eps * std
def encode(self, tree):
mu, logvar = self.encoder(tree)
return mu, logvar
def decode(self, z):
if HVAE.symbols is None:
raise Exception("To generate expression trees, a symbol library is needed. Please add it using the"
" HVAE.add_symbols method.")
return self.decoder.decode(z, HVAE.symbols)
@staticmethod
def add_symbols(symbols):
HVAE.symbols = symbols
Node.add_symbols(symbols)
class Encoder(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(Encoder, self).__init__()
self.hidden_size = hidden_size
self.gru = GRU221(input_size=input_size, hidden_size=hidden_size)
self.mu = nn.Linear(in_features=hidden_size, out_features=output_size)
self.logvar = nn.Linear(in_features=hidden_size, out_features=output_size)
torch.nn.init.xavier_uniform_(self.mu.weight)
torch.nn.init.xavier_uniform_(self.logvar.weight)
def forward(self, tree):
# Check if the tree has target vectors
if tree.target is None:
tree.add_target_vectors()
tree_encoding = self.recursive_forward(tree)
mu = self.mu(tree_encoding)
logvar = self.logvar(tree_encoding)
return mu, logvar
def recursive_forward(self, tree):
left = self.recursive_forward(tree.left) if tree.left is not None \
else torch.zeros(tree.target.size(0), 1, self.hidden_size)
right = self.recursive_forward(tree.right) if tree.right is not None \
else torch.zeros(tree.target.size(0), 1, self.hidden_size)
hidden = self.gru(tree.target, left, right)
return hidden
class Decoder(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(Decoder, self).__init__()
self.hidden_size = hidden_size
self.z2h = nn.Linear(input_size, hidden_size)
self.h2o = nn.Linear(hidden_size, output_size)
self.gru = GRU122(input_size=output_size, hidden_size=hidden_size)
torch.nn.init.xavier_uniform_(self.z2h.weight)
torch.nn.init.xavier_uniform_(self.h2o.weight)
# Used during training to guide the learning process
def forward(self, z, tree):
hidden = self.z2h(z)
self.recursive_forward(hidden, tree)
return tree
def recursive_forward(self, hidden, tree):
prediction = self.h2o(hidden)
symbol_probs = F.softmax(prediction, dim=2)
tree.prediction = prediction
if tree.left is not None or tree.right is not None:
left, right = self.gru(symbol_probs, hidden)
if tree.left is not None:
self.recursive_forward(left, tree.left)
if tree.right is not None:
self.recursive_forward(right, tree.right)
# Used for inference to generate expression trees from latent vectorS
def decode(self, z, symbols):
with torch.no_grad():
hidden = self.z2h(z)
tree = self.recursive_decode(hidden, symbols)
return tree
def recursive_decode(self, hidden, symbols):
prediction = self.h2o(hidden)
# Sample symbol in a given node
sampled, symbol, stype = self.sample_symbol(prediction, symbols)
# print(symbol)
if stype.value is SymType.Fun.value:
left, right = self.gru(sampled, hidden)
l_tree = self.recursive_decode(left, symbols)
r_tree = None
elif stype.value is SymType.Operator.value:
left, right = self.gru(sampled, hidden)
l_tree = self.recursive_decode(left, symbols)
r_tree = self.recursive_decode(right, symbols)
else:
l_tree = None
r_tree = None
return Node(symbol, right=r_tree, left=l_tree)
def sample_symbol(self, prediction, symbol_dict):
sampled = F.softmax(prediction, dim=2)
# Select the symbol with the highest value ("probability")
symbol = symbol_dict[torch.argmax(sampled).item()]
return sampled, symbol["symbol"], symbol["type"]
class GRU221(nn.Module):
def __init__(self, input_size, hidden_size):
super(GRU221, self).__init__()
self.wir = nn.Linear(in_features=input_size, out_features=hidden_size)
self.whr = nn.Linear(in_features=2*hidden_size, out_features=hidden_size)
self.wiz = nn.Linear(in_features=input_size, out_features=hidden_size)
self.whz = nn.Linear(in_features=2 * hidden_size, out_features=hidden_size)
self.win = nn.Linear(in_features=input_size, out_features=hidden_size)
self.whn = nn.Linear(in_features=2 * hidden_size, out_features=hidden_size)
torch.nn.init.xavier_uniform_(self.wir.weight)
torch.nn.init.xavier_uniform_(self.whr.weight)
torch.nn.init.xavier_uniform_(self.wiz.weight)
torch.nn.init.xavier_uniform_(self.whz.weight)
torch.nn.init.xavier_uniform_(self.win.weight)
torch.nn.init.xavier_uniform_(self.whn.weight)
def forward(self, x, h1, h2):
h = torch.cat([h1, h2], dim=2)
r = torch.sigmoid(self.wir(x) + self.whr(h))
z = torch.sigmoid(self.wiz(x) + self.whz(h))
n = torch.tanh(self.win(x) + r * self.whn(h))
return (1 - z) * n + (z / 2) * h1 + (z / 2) * h2
class GRU122(nn.Module):
def __init__(self, input_size, hidden_size):
super(GRU122, self).__init__()
self.hidden_size = hidden_size
self.wir = nn.Linear(in_features=input_size, out_features=2*hidden_size)
self.whr = nn.Linear(in_features=hidden_size, out_features=2*hidden_size)
self.wiz = nn.Linear(in_features=input_size, out_features=2*hidden_size)
self.whz = nn.Linear(in_features=hidden_size, out_features=2*hidden_size)
self.win = nn.Linear(in_features=input_size, out_features=2*hidden_size)
self.whn = nn.Linear(in_features=hidden_size, out_features=2*hidden_size)
torch.nn.init.xavier_uniform_(self.wir.weight)
torch.nn.init.xavier_uniform_(self.whr.weight)
torch.nn.init.xavier_uniform_(self.wiz.weight)
torch.nn.init.xavier_uniform_(self.whz.weight)
torch.nn.init.xavier_uniform_(self.win.weight)
torch.nn.init.xavier_uniform_(self.whn.weight)
def forward(self, x, h):
r = torch.sigmoid(self.wir(x) + self.whr(h))
z = torch.sigmoid(self.wiz(x) + self.whz(h))
n = torch.tanh(self.win(x) + r * self.whn(h))
dh = h.repeat(1, 1, 2)
out = (1 - z) * n + z * dh
return torch.split(out, self.hidden_size, dim=2)
| 7,496 | 39.090909 | 111 | py |
HVAE | HVAE-master/src/reconstruction_accuracy.py | from argparse import ArgumentParser
import numpy as np
import torch
from sklearn.model_selection import KFold
import editdistance
from utils import read_expressions, tokens_to_tree
from symbol_library import generate_symbol_library
from model import HVAE
from train import train_hvae
def one_fold(model, train, test, epochs, batch_size, annealing_iters, verbose):
train_hvae(model, train, epochs, batch_size, annealing_iters, verbose)
total_distance = []
for t in test:
latent = model.encode(t)[0]
pt = model.decode(latent)
total_distance.append(editdistance.eval(t.to_list(notation="postfix"), pt.to_list(notation="postfix")))
return total_distance
def one_experiment(name, trees, input_dim, latent_dim, epochs, batch_size, annealing_iters, verbose, seed,
smaller_dataset=False, examples=2000):
kf = KFold()
distances = []
for i, (train_idx, test_idx) in enumerate(kf.split(trees)):
print(f"Fold {i + 1}")
if smaller_dataset:
np.random.seed(seed + i)
torch.manual_seed(seed + i)
inds = np.random.permutation(train_idx)
inds = inds[:examples]
train = [trees[i] for i in inds]
else:
train = [trees[i] for i in train_idx]
test = [trees[i] for i in test_idx]
model = HVAE(input_dim, latent_dim)
distances.append(one_fold(model, train, test, epochs, batch_size, annealing_iters, verbose))
print(f"Mean: {np.mean(distances[-1])}, Var: {np.var(distances[-1])}")
print()
fm = [np.mean(d) for d in distances]
with open("../results/hvae.txt", "a") as file:
file.write(f"{name}\t Mean: {np.mean(fm)}, Std dev: {np.std(fm)}, All: {', '.join([str(f) for f in fm])}\n")
print(f"Mean: {np.mean(fm)}, Std dev: {np.std(fm)}, All: {', '.join([str(f) for f in fm])}")
return fm
if __name__ == '__main__':
parser = ArgumentParser(prog='Train HVAE', description='A script for training the HVAE model.')
parser.add_argument("-expressions", required=True)
parser.add_argument("-symbols", nargs="+", required=True)
parser.add_argument("-batch", default=32, type=int)
parser.add_argument("-num_vars", default=2, type=int)
parser.add_argument("-has_const", action="store_true")
parser.add_argument("-latent_size", default=128, type=int)
parser.add_argument("-epochs", default=20, type=int)
parser.add_argument("-annealing_iters", default=1800, type=int)
parser.add_argument("-verbose", action="store_true")
parser.add_argument("-seed", default=18, type=int)
args = parser.parse_args()
if args.seed is not None:
np.random.seed(args.seed)
torch.manual_seed(args.seed)
equations = read_expressions(args.expressions)
symbols = generate_symbol_library(args.num_vars, args.symbols, args.has_const)
input_dim = len(symbols)
HVAE.add_symbols(symbols)
s2t = {s["symbol"]: s for s in symbols}
trees = [tokens_to_tree(eq, s2t) for eq in equations]
one_experiment(args.expressions, trees, input_dim, args.latent_size, args.epochs, args.batch, args.annealing_iters,
args.verbose, args.seed)
| 3,214 | 38.691358 | 119 | py |
HVAE | HVAE-master/src/__init__.py | 0 | 0 | 0 | py |
|
HVAE | HVAE-master/src/evaluation.py | from rusteval import Evaluator
import numpy as np
from pymoo.core.problem import ElementwiseProblem
from pymoo.algorithms.soo.nonconvex.de import DE
from pymoo.operators.sampling.lhs import LHS
from pymoo.optimize import minimize
from pymoo.termination.default import DefaultSingleObjectiveTermination
def read_eq_data(filename):
train = []
with open(filename, "r") as file:
for line in file:
train.append([float(v) for v in line.strip().split(",")])
return np.array(train)
class PymooProblem(ElementwiseProblem):
def __init__(self, model, constants, evaluator, estimation_settings, lower=-5, upper=5, default_error=1e10):
xl = np.full(constants, lower)
xu = np.full(constants, upper)
super().__init__(n_var=constants, n_obj=1, n_constr=0, xl=xl, xu=xu)
self.model = model
self.evaluator = evaluator
self.default_error = default_error
self.estimation_settings = estimation_settings
def _evaluate(self, x, out, *args, **kwargs):
try:
rmse = self.evaluator.get_rmse(self.model, [float(v) for v in x])
out["F"] = rmse
except:
out["F"] = self.default_error
def DE_pymoo(model, constants, evaluator, **estimation_settings):
pymoo_problem = PymooProblem(model, constants, evaluator, estimation_settings)
strategy = "DE/best/1/bin"
algorithm = DE(
pop_size=20,
sampling=LHS(),
variant=strategy,
CR=0.7,
dither="vector",
jitter=False
)
termination = DefaultSingleObjectiveTermination(
xtol=0.7,
cvtol=1e-6,
ftol=1e-6,
period=20,
n_max_gen=1000,
)
output = minimize(pymoo_problem,
algorithm,
termination,
verbose=True,
save_history=False)
return output.X, output.F
class RustEval:
variable_names = 'ABDEFGHIJKLMNOPQRSTUVWXYZČŠŽ'
def __init__(self, data, verbose=False):
self.data = data
d = data.T
columns = []
names = []
for i in range(d.shape[0]-1):
columns.append([float(v) for v in d[i]])
names.append(RustEval.variable_names[i])
target = [float(v) for v in d[-1]]
self.verbose = verbose
self.evaluator = Evaluator(columns, names, target)
def evaluate(self, expression, constants=None):
if constants is None:
constants = []
try:
return self.evaluator.eval_expr(expression, constants)
except Exception as e:
if self.verbose:
print(e)
return None
def get_error(self, expression, constants=None):
if constants is None:
constants = []
try:
return self.evaluator.get_rmse(expression, constants)
except Exception as e:
if self.verbose:
print(e)
return None
def fit_and_evaluate(self, expr):
num_constants = sum([1 for t in expr if t == "C"])
if num_constants > 0:
x, rmse = DE_pymoo(expr, num_constants, self.evaluator)
return rmse, x
else:
return self.get_error(expr), []
if __name__ == '__main__':
data = read_eq_data("/home/sebastianmeznar/Projects/HVAE/data/nguyen/nguyen10_test.csv")
data = np.array([[1., 2., 3., 4.], [2., 3., 4., 5.]]).T
rev = RustEval(data)
print(rev.fit_and_evaluate(["A", "C", "-"]))
# names = ["X", "Y"]
# evaluator = Evaluator(data, names)
# print(evaluator.eval_expr(["X", "Y", "+"])) | 3,639 | 29.847458 | 112 | py |
HVAE | HVAE-master/src/linear_interpolation.py | import torch
from model import HVAE
from utils import tokens_to_tree
from symbol_library import generate_symbol_library
def interpolateAB(model, exprA, exprB, steps=5):
tokensA = exprA.split(" ")
tokensB = exprB.split(" ")
treeA = tokens_to_tree(tokensA, s2t)
treeB = tokens_to_tree(tokensB, s2t)
l1 = model.encode(treeA)[0]
l2 = model.encode(treeB)[0]
print(f"Expr A:\t{str(treeA)}")
print(f"a=0:\t{str(model.decode(l1))}")
for i in range(1, steps-1):
a = i/(steps-1)
la = (1-a) * l1 + a * l2
print(f"a={str(a)[:5]}:\t{str(model.decode(la))}")
print(f"a=1:\t{str(model.decode(l2))}")
print(f"Expr B:\t{str(treeB)}")
if __name__ == '__main__':
param_file = "../params/4_2k.pt"
symbols = generate_symbol_library(1, ["+", "-", "*", "/", "^"])
HVAE.add_symbols(symbols)
s2t = {s["symbol"]: s for s in symbols}
steps = 5
model = torch.load(param_file)
interpolateAB(model, "A + A / A", "A * C ^ A")
# TODO: Create reproducible results of linear interpolation and add them to the paper
| 1,089 | 28.459459 | 89 | py |
HVAE | HVAE-master/src/train.py | from argparse import ArgumentParser
import numpy as np
import torch
from torch.utils.data import Sampler, Dataset, DataLoader
from tqdm import tqdm
from utils import tokens_to_tree, read_expressions, read_json
from model import HVAE
from symbol_library import generate_symbol_library
def collate_fn(batch):
return batch
class TreeSampler(Sampler):
def __init__(self, batch_size, num_eq):
self.batch_size = batch_size
self.num_eq = num_eq
def __iter__(self):
for i in range(len(self)):
batch = np.random.randint(low=0, high=self.num_eq, size=self.batch_size)
yield batch
def __len__(self):
return self.num_eq // self.batch_size
class TreeDataset(Dataset):
def __init__(self, train):
self.train = train
def __getitem__(self, idx):
return self.train[idx]
def __len__(self):
return len(self.train)
def train_hvae(model, trees, epochs=20, batch_size=32, annealing_iters=2800, verbose=True):
dataset = TreeDataset(trees)
sampler = TreeSampler(batch_size, len(dataset))
trainloader = DataLoader(dataset, batch_sampler=sampler, collate_fn=collate_fn, num_workers=0)
optimizer = torch.optim.Adam(model.parameters())
criterion = torch.nn.CrossEntropyLoss()
iter_counter = 0
lmbda = (np.tanh(-4.5) + 1) / 2
midpoint = len(dataset) // (2 * batch_size)
for epoch in range(epochs):
bce, kl, total, num_trees = 0, 0, 0, 0
with tqdm(total=len(dataset), desc=f'Testing - Epoch: {epoch + 1}/{epochs}', unit='chunks') as prog_bar:
for i, trees in enumerate(trainloader):
batch_loss = 0
for tree in trees:
mu, logvar, outputs = model(tree)
loss, bcel, kll = outputs.loss(mu, logvar, lmbda, criterion)
batch_loss += loss
total += loss.detach().item()
bce += bcel.detach().item()
kl += kll.detach().item()
num_trees += batch_size
optimizer.zero_grad()
batch_loss = batch_loss / batch_size
batch_loss.backward()
optimizer.step()
prog_bar.set_postfix(**{'run:': "HVAE",
'loss': total / num_trees,
'BCE': bce / num_trees,
'KLD': kl / num_trees})
prog_bar.update(batch_size)
if iter_counter < annealing_iters:
lmbda = (np.tanh((iter_counter - 4500) / 1000) + 1) / 2
iter_counter += 1
if verbose and i == midpoint:
z = model.encode(trees[0])[0]
decoded_tree = model.decode(z)
print("\nO: {}".format(str(trees[0])))
print("P: {}".format(str(decoded_tree)))
for t in trees:
t.clear_prediction()
if __name__ == '__main__':
parser = ArgumentParser(prog='Train HVAE', description='A script for training the HVAE model.')
parser.add_argument("-expressions", required=True)
parser.add_argument("-symbols", nargs="+", required=True)
parser.add_argument("-batch", default=32, type=int)
parser.add_argument("-num_vars", default=2, type=int)
parser.add_argument("-has_const", action="store_true")
parser.add_argument("-latent_size", default=32, type=int)
parser.add_argument("-epochs", default=20, type=int)
parser.add_argument("-param_path", default="")
parser.add_argument("-annealing_iters", default=2800, type=int)
parser.add_argument("-verbose", action="store_true")
parser.add_argument("-seed", type=int)
args = parser.parse_args()
if args.seed is not None:
np.random.seed(args.seed)
torch.manual_seed(args.seed)
symbols = generate_symbol_library(args.num_vars, args.symbols, args.has_const)
HVAE.add_symbols(symbols)
if args.expressions.strip().split(".")[-1] == "json":
trees = read_json(args.expressions)
else:
s2t = {s["symbol"]: s for s in symbols}
equations = read_expressions(args.expressions)
trees = [tokens_to_tree(eq, s2t) for eq in equations]
model = HVAE(len(symbols), args.latent_size)
train_hvae(model, trees, args.epochs, args.batch, args.annealing_iters, args.verbose)
if args.param_path != "":
torch.save(model, args.param_path)
| 4,523 | 34.904762 | 112 | py |
HVAE | HVAE-master/src/symbol_library.py | from enum import Enum
class SymType(Enum):
Var = 1
Const = 2
Operator = 3
Fun = 4
Literal = 5
def generate_symbol_library(num_vars, symbol_list, has_constant=True):
all_symbols = {
"+": {"symbol": '+', "type": SymType.Operator, "precedence": 0, "psymbol": "add"},
"-": {"symbol": '-', "type": SymType.Operator, "precedence": 0, "psymbol": "sub"},
"*": {"symbol": '*', "type": SymType.Operator, "precedence": 1, "psymbol": "mul"},
"/": {"symbol": '/', "type": SymType.Operator, "precedence": 1, "psymbol": "div"},
"^": {"symbol": "^", "type": SymType.Operator, "precedence": 2, "psymbol": "pow"},
"sqrt": {"symbol": 'sqrt', "type": SymType.Fun, "precedence": 5, "psymbol": "sqrt"},
"sin": {"symbol": 'sin', "type": SymType.Fun, "precedence": 5, "psymbol": "sin"},
"cos": {"symbol": 'cos', "type": SymType.Fun, "precedence": 5, "psymbol": "cos"},
"exp": {"symbol": 'exp', "type": SymType.Fun, "precedence": 5, "psymbol": "exp"},
"log": {"symbol": 'log', "type": SymType.Fun, "precedence": 5, "psymbol": "log"},
"^2": {"symbol": '^2', "type": SymType.Fun, "precedence": -1, "psymbol": "n2"},
"^3": {"symbol": '^3', "type": SymType.Fun, "precedence": -1, "psymbol": "n3"},
"^4": {"symbol": '^4', "type": SymType.Fun, "precedence": -1, "psymbol": "n4"},
"^5": {"symbol": '^5', "type": SymType.Fun, "precedence": -1, "psymbol": "n5"},
}
variable_names = 'ABDEFGHIJKLMNOPQRSTUVWXYZČŠŽ'
symbols = []
for i in range(num_vars):
if i < len(variable_names):
symbols.append({"symbol": variable_names[i], "type": SymType.Var, "precedence": 5, "psymbol": variable_names[i]})
else:
raise Exception("Insufficient symbol names, please add additional symbols into the variable_names variable"
" from the generate_symbol_library method in symbol_library.py")
if has_constant:
symbols.append({"symbol": 'C', "type": SymType.Const, "precedence": 5, "psymbol": "const"})
for s in symbol_list:
if s in all_symbols:
symbols.append(all_symbols[s])
else:
raise Exception(f"Symbol {s} is not in the standard library, please add it into the all_symbols variable"
f" from the generate_symbol_library method in symbol_library.py")
return symbols
| 2,430 | 48.612245 | 125 | py |
RL4SRD | RL4SRD-master/RL4SRD.py | """
Created on 2016-12-11
class: RL4SRD
@author: Long Xia
@contact: [email protected]
"""
# !/usr/bin/python
# -*- coding:utf-8 -*-
import sys
import json
import yaml
import copy
import math
import random
import numpy as np
import os
class RL4SRD(object):
"""docstring for RL4SRD"""
def __init__(self, fileQueryPermutaion, fileQueryRepresentation, fileDocumentRepresentation, fileQueryDocumentSubtopics, folder):
super(RL4SRD, self).__init__()
with open(fileQueryPermutaion) as self.fileQueryPermutaion:
self.dictQueryPermutaion = json.load(self.fileQueryPermutaion)
with open(fileQueryRepresentation) as self.fileQueryRepresentation:
self.dictQueryRepresentation = json.load(self.fileQueryRepresentation)
for query in self.dictQueryRepresentation:
self.dictQueryRepresentation[query] = np.matrix([self.dictQueryRepresentation[query]], dtype=np.float)
self.dictQueryRepresentation[query] = np.transpose(self.dictQueryRepresentation[query])
with open(fileDocumentRepresentation) as self.fileDocumentRepresentation:
self.dictDocumentRepresentation = json.load(self.fileDocumentRepresentation)
for doc in self.dictDocumentRepresentation:
self.dictDocumentRepresentation[doc] = np.matrix([self.dictDocumentRepresentation[doc]], dtype=np.float)
self.dictDocumentRepresentation[doc] = np.transpose(self.dictDocumentRepresentation[doc])
with open(fileQueryDocumentSubtopics) as self.fileQueryDocumentSubtopics:
self.dictQueryDocumentSubtopics = json.load(self.fileQueryDocumentSubtopics)
self.folder = folder
with open(self.folder + '/config.yml') as self.confFile:
self.dictConf = yaml.load(self.confFile)
self.floatLearningRate = self.dictConf['learning_rate']
self.listTestSet = self.dictConf['test_set']
self.listValidationSet = self.dictConf['validation_set']
self.lenTrainPermutation = self.dictConf['length_train_permutation']
self.K = self.dictConf['K']
self.gamma = self.dictConf['gamma']
self.hidden_dim = self.dictConf['hidden_dim']
self.fileResult = open(self.folder + '/RL_result.dat', 'w')
self.fileValidation = open(self.folder + '/RL_validation.dat', 'w')
self.floatTestTime = 0.0
self.__RL_build__()
def __del__(self):
self.fileResult.close()
self.fileValidation.close()
def __RL_build__(self):
#self.U = np.random.uniform(-np.sqrt(1./self.hidden_dim), np.sqrt(1./self.hidden_dim), (100, self.hidden_dim))
#self.V_q = np.random.uniform(-np.sqrt(1./self.hidden_dim), np.sqrt(1./self.hidden_dim), (self.hidden_dim, 100))
#self.V = np.random.uniform(-np.sqrt(1./self.hidden_dim), np.sqrt(1./self.hidden_dim), (self.hidden_dim, 100))
#self.W = np.random.uniform(-np.sqrt(1./self.hidden_dim), np.sqrt(1./self.hidden_dim), (self.hidden_dim, self.hidden_dim))
self.U = np.random.uniform(-1./self.hidden_dim, 1./self.hidden_dim, (100, self.hidden_dim))
self.V_q = np.random.uniform(-1./self.hidden_dim, 1./self.hidden_dim, (self.hidden_dim, 100))
self.V = np.random.uniform(-1./self.hidden_dim, 1./self.hidden_dim, (self.hidden_dim, 100))
self.W = np.random.uniform(-1./self.hidden_dim, 1./self.hidden_dim, (self.hidden_dim, self.hidden_dim))
def __RL_derive_assign(self):
self.U_derive = np.zeros((100, self.hidden_dim))
self.V_q_derive = np.zeros((self.hidden_dim, 100))
self.V_derive = np.zeros((self.hidden_dim, 100))
self.W_derive = np.zeros((self.hidden_dim, self.hidden_dim))
def __RL_derive_list(self):
self.list_U_derive = []
self.list_V_derive = []
self.list_V_q_derive = []
self.list_W_derive = []
self.list_h = []
self.list_diag_h = []
self.list_G_t = []
def __sigmoid(self, arrayX):
return 1 / (1+np.exp(-arrayX))
def __sigmoid_derive(self, arrayX):
return arrayX * (1-arrayX)
def __sigmoid_diag(self, arrayX):
Ashape = arrayX.shape
tmp = np.zeros(Ashape[0])
for i in xrange(Ashape[0]):
tmp[i] = arrayX[i][0] * ( 1 - arrayX[i][0] )
return np.diag(tmp)
def preference(self, o_list):
tmp = random.random()
for i in xrange(len(o_list)):
if tmp < o_list[i]:
return i
def alphaDCG(self, alpha, query, docList, k):
DCG = 0.0
subtopics = []
for i in xrange(20):
subtopics.append(0)
for i in xrange(k):
G = 0.0
if docList[i] not in self.dictQueryDocumentSubtopics[query]:
continue
listDocSubtopics = self.dictQueryDocumentSubtopics[query][docList[i]]
if len(listDocSubtopics) == 0:
G = 0.0
else:
for subtopic in listDocSubtopics:
G += (1-alpha) ** subtopics[int(subtopic)-1]
subtopics[int(subtopic)-1] += 1
DCG += G/math.log(i+2, 2)
return DCG
def subtopic_recall(self):
pass
def Train(self):
listKeys = self.dictQueryPermutaion.keys()
random.shuffle(listKeys)
for query in listKeys:
#if (int(query) in self.listTestSet) or (int(query) in self.listValidationSet):
if int(query) in self.listTestSet:
continue
self.__RL_derive_assign()
self.__RL_derive_list()
q = self.dictQueryRepresentation[query]
self.h_t = self.__sigmoid(np.dot(self.V_q, q))
listPermutation = copy.deepcopy(self.dictQueryPermutaion[query]['permutation'])
listSelectedSet = []
for t in xrange(self.lenTrainPermutation):
#store h_t and diag(h_t * (1-h_t))
h_t_tmp = copy.deepcopy(self.h_t)
self.list_h.append(h_t_tmp)
self.list_diag_h.append(self.__sigmoid_diag(h_t_tmp))
Z_sum = 0.0
derive_U_sum = np.zeros((100, self.hidden_dim))
derive_V_q_sum = np.zeros((self.hidden_dim, 100))
derive_V_sum = np.zeros((self.hidden_dim, 100))
derive_W_sum = np.zeros((self.hidden_dim, self.hidden_dim))
s_t = np.dot(self.U, self.h_t)
x_list = []
x_prob = []
x_prob_sum = 0.0
x_prob_list = []
list_derive_f_U = []
list_derive_f_V_q = []
list_derive_f_V = []
list_derive_f_W = []
for j in xrange(len(listPermutation)):
x_score = np.exp(np.dot(np.transpose(self.dictDocumentRepresentation[listPermutation[j]]), s_t))
x_score = np.array(x_score)
x_score = x_score[0][0]
Z_sum += x_score
x_list.append(x_score)
derive_f_U_tmp = np.dot(self.dictDocumentRepresentation[listPermutation[j]], np.transpose(self.h_t))
list_derive_f_U.append(derive_f_U_tmp)
derive_U_sum += derive_f_U_tmp * x_score
derive_f_h_tmp = np.dot(np.transpose(self.U), self.dictDocumentRepresentation[listPermutation[j]])
if t == 0:
derive_f_V_q_tmp = np.dot(self.list_diag_h[t], np.dot(derive_f_h_tmp, np.transpose(q)))
list_derive_f_V_q.append(derive_f_V_q_tmp)
derive_V_q_sum += derive_f_V_q_tmp * x_score
else:
derive_f_V_tmp = np.dot(self.list_diag_h[t], np.dot(derive_f_h_tmp, np.transpose(self.dictDocumentRepresentation[listSelectedSet[t-1]])))
derive_f_W_tmp = np.dot(self.list_diag_h[t], np.dot(derive_f_h_tmp, np.transpose(self.list_h[t-1])))
for i in xrange(t-1, 1, -1):
derive_f_h_tmp = np.dot(np.dot(np.transpose(self.W),self.list_diag_h[i]), derive_f_h_tmp)
derive_f_V_tmp += np.dot(self.list_diag_h[i-1], np.dot(derive_f_h_tmp, np.transpose(self.dictDocumentRepresentation[listSelectedSet[i-2]])))
derive_f_W_tmp += np.dot(self.list_diag_h[i-1], np.dot(derive_f_h_tmp, np.transpose(self.list_h[i-1])))
list_derive_f_V.append(derive_f_V_tmp)
list_derive_f_W.append(derive_f_W_tmp)
derive_V_sum += derive_f_V_tmp * x_score
derive_W_sum += derive_f_W_tmp * x_score
#generage policy pi
for item in x_list:
x_one = item/Z_sum
x_prob.append(x_one)
x_prob_sum += x_one
x_prob_list.append(x_prob_sum)
#sample action
preference_j = self.preference(x_prob_list)
listSelectedSet.append(listPermutation[preference_j])
R = self.alphaDCG(0.5, query, listSelectedSet, t+1) - self.alphaDCG(0.5, query, listSelectedSet, t)
self.list_G_t.append(R)
x_t = self.dictDocumentRepresentation[listPermutation[preference_j]]
self.h_t = self.__sigmoid(np.dot(self.V, x_t) + np.dot(self.W, self.h_t))
self.list_U_derive.append(list_derive_f_U[preference_j] - derive_U_sum/Z_sum)
if t == 0:
self.list_V_q_derive.append(list_derive_f_V_q[preference_j] - derive_V_q_sum/Z_sum)
else:
self.list_V_derive.append(list_derive_f_V[preference_j] - derive_V_sum/Z_sum)
self.list_W_derive.append(list_derive_f_W[preference_j] - derive_W_sum/Z_sum)
#X = X/x_t
del listPermutation[preference_j]
for t in xrange(len(self.list_G_t)):
G = 0.0
for j in xrange(t, len(self.list_G_t)):
G += self.list_G_t[j] * (self.gamma ** j)
self.V_q_derive += (self.gamma ** t) * G * self.list_V_q_derive[0]
self.U_derive += (self.gamma ** t) * G * self.list_U_derive[t]
if t > 0:
self.V_derive += (self.gamma ** t) * G * self.list_V_derive[t-1]
self.W_derive += (self.gamma ** t) * G * self.list_W_derive[t-1]
self.U += self.floatLearningRate * self.U_derive
self.V += self.floatLearningRate * self.V_derive
self.V_q += self.floatLearningRate * self.V_q_derive
self.W += self.floatLearningRate * self.W_derive
def Prediction(self, listInput, boolTest):
if not os.path.exists(self.folder + '/ranking'):
os.makedirs(self.folder + '/ranking')
floatSumResultScore = 0.0
dictResult = {}
for query in listInput:
if boolTest:
fileRankingResult = open(self.folder + '/ranking/' + 'test' + str(query) + '.ranking', 'w')
else:
fileRankingResult = open(self.folder + '/ranking/' + 'val' + str(query) + '.ranking', 'w')
listSelectedSet = []
listTest = copy.deepcopy(self.dictQueryPermutaion[str(query)]['permutation'])
idealScore = self.alphaDCG(0.5, str(query), listTest, self.K)
if idealScore == 0:
continue
random.shuffle(listTest)
self.s_t = self.__sigmoid(np.dot(self.V_q, self.dictQueryRepresentation[str(query)]) + np.dot(self.W, np.zeros((self.hidden_dim,1))))
while len(listSelectedSet) < self.K:
bestScore = -10000000.0
bestDoc = ''
s_tmp = self.s_t
for doc in listTest:
o_tmp = np.dot(self.U, s_tmp)
doc_score = np.dot(np.transpose(o_tmp), self.dictDocumentRepresentation[doc])
if doc_score > bestScore and doc not in listSelectedSet:
bestScore = doc_score
bestDoc = doc
self.s_t = self.__sigmoid(np.dot(self.V, self.dictDocumentRepresentation[bestDoc]) + np.dot(self.W, s_tmp))
listSelectedSet.append(bestDoc)
fileRankingResult.write(bestDoc + '\n')
resultScore = self.alphaDCG(0.5, str(query), listSelectedSet, self.K)
dictResult[query] = resultScore/idealScore
floatSumResultScore += resultScore/idealScore
fileRankingResult.close()
print dictResult
return floatSumResultScore/len(dictResult.keys())
def main(self):
iteration = 1
#while (iteration < 151):
while True:
print 'iteration:' + str(iteration)
self.Train()
#validation = self.Prediction(self.listValidationSet, False)
#print round(validation, 4)
#print '\n'
#self.fileValidation.write(str(iteration) + ' ' + str(validation) + '\n')
#self.fileValidation.flush()
result = self.Prediction(self.listTestSet, True)
print 'ndcg:' + str(round(result, 4))
self.fileResult.write(str(iteration) + ' ' + str(result) + '\n')
self.fileResult.flush()
print '\n'
iteration += 1
if __name__ == '__main__':
if len(sys.argv) != 6:
print 'Error: params number is 5!'
print 'Need: query permutation file, query representation file, document representation file, query document subtopics file, and folder!'
sys.exit(-1)
carpe_diem = RL4SRD(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5])
carpe_diem.main()
del carpe_diem
print 'Game over!'
| 13,959 | 41.953846 | 168 | py |
User-Object-Attention-Level | User-Object-Attention-Level-master/data_generate/util.py | import numpy as np
def ade_classes():
"""ADE20K class names for external use."""
return [
'wall', 'building', 'sky', 'floor', 'tree', 'ceiling', 'road', 'bed ',
'windowpane', 'grass', 'cabinet', 'sidewalk', 'person', 'earth',
'door', 'table', 'mountain', 'plant', 'curtain', 'chair', 'car',
'water', 'painting', 'sofa', 'shelf', 'house', 'sea', 'mirror', 'rug',
'field', 'armchair', 'seat', 'fence', 'desk', 'rock', 'wardrobe',
'lamp', 'bathtub', 'railing', 'cushion', 'base', 'box', 'column',
'signboard', 'chest of drawers', 'counter', 'sand', 'sink',
'skyscraper', 'fireplace', 'refrigerator', 'grandstand', 'path',
'stairs', 'runway', 'case', 'pool table', 'pillow', 'screen door',
'stairway', 'river', 'bridge', 'bookcase', 'blind', 'coffee table',
'toilet', 'flower', 'book', 'hill', 'bench', 'countertop', 'stove',
'palm', 'kitchen island', 'computer', 'swivel chair', 'boat', 'bar',
'arcade machine', 'hovel', 'bus', 'towel', 'light', 'truck', 'tower',
'chandelier', 'awning', 'streetlight', 'booth', 'television receiver',
'airplane', 'dirt track', 'apparel', 'pole', 'land', 'bannister',
'escalator', 'ottoman', 'bottle', 'buffet', 'poster', 'stage', 'van',
'ship', 'fountain', 'conveyer belt', 'canopy', 'washer', 'plaything',
'swimming pool', 'stool', 'barrel', 'basket', 'waterfall', 'tent',
'bag', 'minibike', 'cradle', 'oven', 'ball', 'food', 'step', 'tank',
'trade name', 'microwave', 'pot', 'animal', 'bicycle', 'lake',
'dishwasher', 'screen', 'blanket', 'sculpture', 'hood', 'sconce',
'vase', 'traffic light', 'tray', 'ashcan', 'fan', 'pier', 'crt screen',
'plate', 'monitor', 'bulletin board', 'shower', 'radiator', 'glass',
'clock', 'flag'
]
if __name__ == '__main__':
# import json
#
# with open("test_data.json", 'r') as load_f:
# load_dict = json.load(load_f)
# # print(load_dict)
# l = [len(load_dict[j]) for j in load_dict]
# print(l)
# gd = np.loadtxt('gd.txt')
# gd[gd==0]=1
# gd = np.log(gd)
# np.savetxt('gd2.txt', gd)
# raw_filter = [
# 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17
# , 18, 19, 20, 21, 22, 23, 24, 26, 27, 28, 29, 30, 31, 32, 33, 34, 36, 38
# , 39, 40, 41, 42, 43, 44, 45, 46, 47, 50, 51, 52, 53, 55, 57, 59, 60, 61
# , 62, 63, 64, 66, 67, 69, 70, 71, 72, 74, 75, 76, 80, 81, 82, 83, 85, 86
# , 87, 88, 89, 90, 92, 93, 95, 97, 98, 100, 101, 102, 104, 108, 110, 111, 112, 115
# , 116, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 129, 131, 132, 133, 134, 135, 136
# , 137, 138, 139, 140, 141, 142, 143, 144, 146, 147, 148, 149
# ]
#
# dell = [59, 46, 50, 51, 52, 74, 77, 81, 83, 72, 90, 93, 94, 110, 98, 103, 100, 86,
# 44, 27, 64, 61]
#
# new = []
# for s, i in enumerate(raw_filter):
# if s in dell:
# continue
# new.append(i)
# print(len(new))
import json
save_name = 'temp.json'
with open(save_name,'r') as load_f:
person_choose = json.load(load_f)
s = ''
for k in person_choose:
s+=' '.join(person_choose[k].keys())+'\n'
w = open('experiment.txt', 'w')
w.write(s)
w.close() | 3,390 | 43.038961 | 102 | py |
User-Object-Attention-Level | User-Object-Attention-Level-master/data_generate/convert.py | import os
import shutil
import numpy as np
import json
import matplotlib.pyplot as plt
import cv2
from util import ade_classes
from tqdm import tqdm
import numpy as np
import pandas as pd
save = '../UOAL/Labels'
raw_image = '../UOAL/Images'
fix = '../UOAL/Attention'
# save = '/Users/liujiazhen/Downloads/pas_save_new'
# raw_image = '/Users/liujiazhen/Downloads/all_images_release'
# fix = '/Users/liujiazhen/Downloads/fixation_map_30_release'
def init_list_of_objects(size):
list_of_objects = list()
for i in range(0, size):
list_of_objects.append( list() ) #different object reference each time
return list_of_objects
class PersonSplit():
def __init__(self, seg_path, image_path, fix_map_path):
self.seg_path = seg_path
self.image_path = image_path
self.fix_map_path = fix_map_path
self.seg_files = os.listdir(seg_path)[:]
self.seg_suffix = '.txt'
self.image_files = os.listdir(image_path)[:]
self.image_suffix = '.jpg'
self.fix_map_files = os.listdir(fix_map_path)[:] # contain dirs
self.fix_suffix = '.npy'
self.pre_load_seg = {}
self.pre_load_fix = {}
self.pre_load_img = {}
self.raw_filter = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 26, 27,
28, 30, 31, 32, 33, 34, 36, 38,
39, 41, 42, 43, 44, 45, 46,
47, 51, 53, 55, 57, 62, 63, 64,
66, 67, 69, 71, 74, 75, 80, 81,
82, 83, 85, 86, 87, 89, 92, 93, 97,
98, 100, 102, 108, 110, 112, 115, 116,
119, 120, 123, 124, 125, 127, 131, 132,
134, 135, 136, 137, 138, 139, 141, 142, 143,
144, 146, 147, 148, 149]
for file in tqdm(self.seg_files):
self.pre_load_seg[file] = np.loadtxt(os.path.join(self.seg_path, file)).astype(int)
for file in tqdm(self.fix_map_files):
self.pre_load_fix[file] = {}
if not os.path.isdir(os.path.join(self.fix_map_path, file)):
continue
for sub_file in os.listdir(os.path.join(self.fix_map_path, file)):
if sub_file.split(self.fix_suffix)[0]+self.seg_suffix not in self.seg_files:
continue
self.pre_load_fix[file][sub_file] = np.load(os.path.join(self.fix_map_path, file, sub_file))
print(len(self.raw_filter))
s = 0
self.filter = {}
for i in self.raw_filter:
self.filter[i] = s
s += 1
@staticmethod
def getCluRes(path='clu_label.txt', suffix='.txt'):
"""
Parameters
----------
path clu_results.txt: dir/path, class
Returns dict: classes of all images
-------
"""
maxx = -1
clu = open(path, 'r')
clu_cs = {}
for i in clu.readlines():
name = i.split('\t')[0]
if '\\' in name:
name = name.split('\\')[-1].split(suffix)[0]
else:
name = os.path.split(name)[-1].split(suffix)[0]
cls = int(i.split('\t')[1].replace('\n', ''))
clu_cs[name] = cls # 下标从0开始,连续
maxx = max(maxx, cls)
clu.close()
return clu_cs, maxx + 1
def get_person_all(self, person_num=30):
persons_see = {}
persons_value = {}
for person in range(person_num):
person = str(person)
person_image = self.seg_files
persons_see[person] = {}
persons_value[person] = {}
for im in tqdm(person_image):
im = im.replace(self.seg_suffix, '')
seg_result = self.pre_load_seg[im + self.seg_suffix]
# fix_file = os.path.join(fix, 'Sub_' + str(person + 1), im+self.fix_suffix)
fix_im = self.pre_load_fix['User' + str(int(person) + 1)][im + self.fix_suffix]
if not fix_im.shape == seg_result.shape:
print(im)
continue
cls_set = set(list(seg_result.reshape(-1)))
tmp = []
for cc in cls_set:
if cc in self.filter:
tmp.append(cc)
# else:
# fix_im[seg_result == int(cc)] = 0 # 不在筛选的类里,直接全部删除
cls_set = tmp
# sm = fix_im.sum()
for cls in cls_set: # get number of each person's scene
trans_cls = str(self.filter[cls])
cls = str(cls)
if trans_cls not in persons_see[person]:
persons_see[person][trans_cls] = 1
persons_value[person][trans_cls] = (fix_im[seg_result == int(cls)]).sum() / 255
else:
persons_see[person][trans_cls] += 1
persons_value[person][trans_cls] += (fix_im[seg_result == int(cls)]).sum() / 255
final_value = {}
for k in persons_see[person]:
times = persons_see[person][k]
final_value[k] = float(persons_value[person][k] / times)
persons_value[person] = final_value
persons_value, self.values = self.split_ranking_dep(persons_value)
item_maxx = -1
for p in persons_value:
mx = np.array([int(k) for k in persons_value[p].keys()]).max()
item_maxx = max(item_maxx, mx)
print(item_maxx)
gd = np.zeros([person_num, item_maxx+1])
for p in persons_value:
for c in persons_value[p]:
gd[int(p), int(c)] = persons_value[p][c]
print(gd.shape)
np.savetxt('gd.txt', gd)
def get_person_choose(self, clu_cs, group=10, person_num=30, filter_times=10, chose_group=3):
clu_ls = init_list_of_objects(group)
for seg in self.seg_files:
if not seg.endswith(self.seg_suffix):
continue
name = seg.split(self.seg_suffix)[0]
cls = int(clu_cs[name])
clu_ls[cls].append(name)
persons_see = {}
persons_value = {}
for person in range(person_num):
# select_id = person % len(clu_ls)
person = str(person)
person_image = []
for tt in range(chose_group):
select_id = np.random.randint(len(clu_ls))
person_image += clu_ls[select_id]
np.random.shuffle(person_image)
person_image = person_image[:len(person_image)//2]
persons_see[person] = {}
persons_value[person] = {}
for im in tqdm(person_image):
seg_result = self.pre_load_seg[im+self.seg_suffix]
# fix_file = os.path.join(fix, 'Sub_' + str(person + 1), im+self.fix_suffix)
fix_im = self.pre_load_fix['User' + str(int(person) + 1)][im+self.fix_suffix]
if not fix_im.shape == seg_result.shape:
print(im)
continue
cls_set = set(list(seg_result.reshape(-1)))
tmp = []
for cc in cls_set:
if cc in self.filter:
tmp.append(cc)
# else:
# fix_im[seg_result == int(cc)] = 0 # 不在筛选的类里,直接全部删除
cls_set = tmp
# sm = fix_im.sum()
for cls in cls_set: # get number of each person's scene
trans_cls = str(self.filter[cls])
cls = str(cls)
if trans_cls not in persons_see[person]:
persons_see[person][trans_cls] = 1
persons_value[person][trans_cls] = (fix_im[seg_result == int(cls)]).sum() / 255
else:
persons_see[person][trans_cls] += 1
persons_value[person][trans_cls] += (fix_im[seg_result == int(cls)]).sum() / 255
final_value = {}
for k in persons_see[person]:
times = persons_see[person][k]
if times < filter_times:
continue
final_value[k] = float(persons_value[person][k] / times)
persons_value[person] = final_value
persons_value, _ = self.split_ranking_dep(persons_value)
return persons_value
def split_ranking_dep(self, persons_value, values=None):
if values is None:
for p in persons_value:
scores = []
for c in persons_value[p]:
scores.append(persons_value[p][c])
scores = np.array(scores)
scores = np.sort(scores)
arr = np.array_split(scores, 5)
values = np.array([v[0] for v in arr])
for s, c in enumerate(persons_value[p]):
try:
judge = list(values > persons_value[p][c]).index(1)
except Exception:
judge = 5
persons_value[p][c] = judge
# for p in persons_value:
# for c in persons_value[p]:
# try:
# judge = list(values>persons_value[p][c]).index(1)
# except Exception:
# judge = 5
# persons_value[p][c] = judge
return persons_value, values
def split_ranking(self, persons_value, values=None):
if values is None:
scores = []
for p in persons_value:
for c in persons_value[p]:
scores.append(persons_value[p][c])
scores = np.array(scores)
scores = np.sort(scores)
arr = np.array_split(scores, 5)
values = np.array([v[0] for v in arr])
for p in persons_value:
for c in persons_value[p]:
try:
judge = list(values>persons_value[p][c]).index(1)
except Exception:
judge = 5
persons_value[p][c] = judge
return persons_value, values
def seg2Hist(self, n_clusters=5):
from sklearn.cluster import KMeans
cls = 150
hots = []
person_image = self.seg_files
for im in tqdm(person_image):
hot = np.zeros(150)
im = im.replace(self.seg_suffix, '')
seg_result = self.pre_load_seg[im + self.seg_suffix]
for i in range(cls):
hot[i] = (seg_result==i).sum()
hots.append(hot)
hots = np.array(hots)
Zmax, Zmin = hots.max(axis=0), hots.min(axis=0)
hots = (hots - Zmin) / (Zmax - Zmin + 1e-6)
# np.savetxt('hots.txt', hots)
estimator = KMeans(n_clusters=n_clusters, max_iter=100, tol=0.001)
# 实现聚类结果
estimator.fit(hots)
label = estimator.labels_
strr = ''
for s, i in enumerate(person_image):
strr += 'seg\\'+i+'\t'+str(label[s])+'\n'
f = open('clu_label.txt', 'w')
f.write(strr)
f.close()
class ConvertFix2Ranking():
def __init__(self, person_choose):
self.person_choose = person_choose
def convert2Rating(self):
colunm = ['userId', 'objectId', 'rating', 'timestamp']
df = pd.DataFrame()
# for i in colunm:
# df[i] = data[i]
data = {'userId':[], 'objectId':[], 'rating':[], 'timestamp':[]}
for p in self.person_choose:
value = person_choose[p]
for cls in value:
data['userId'].append(int(p))
data['objectId'].append(int(cls))
data['rating'].append(float(value[cls]))
data['timestamp'] = data['rating'].copy()
for i in colunm:
df[i] = data[i]
df.reset_index(drop=True, inplace=True)
df.to_csv('my_rating.csv', index=False)
n_clusters = 5
chose_group = 3
c = PersonSplit(save, raw_image, fix)
c.seg2Hist(n_clusters=n_clusters)
c.get_person_all()
clu_cs, group = PersonSplit.getCluRes()
person_choose = c.get_person_choose(clu_cs, group, chose_group=chose_group)
# print(person_choose)
#
# # save
save_name = 'temp.json'
json_str = json.dumps(person_choose)
with open(save_name, 'w') as json_file:
json_file.write(json_str)
##########################################
with open(save_name,'r') as load_f:
person_choose = json.load(load_f)
convert = ConvertFix2Ranking(person_choose)
convert.convert2Rating()
pass
| 12,772 | 36.239067 | 108 | py |
lolo | lolo-main/python/setup.py | from setuptools import setup
from glob import glob
import shutil
import os
# single source of truth for package version
version_ns = {}
with open(os.path.join("lolopy", "version.py")) as f:
exec(f.read(), version_ns)
version = version_ns['__version__']
# Find the lolo jar
JAR_FILE = glob(os.path.join('..', 'target', 'scala-2.13', 'lolo-jar-with-dependencies.jar'))
if len(JAR_FILE) == 0:
raise Exception('No Jar files found. Build lolo first by calling "make" or "cd ..; sbt assembly"')
elif len(JAR_FILE) > 1:
raise Exception('Found >1 Jar file. Clean and rebuild lolopy: cd ..; sbt assembly')
# Copy the jar file to a directory at the same level as the package
jar_path = os.path.join('lolopy', 'jar')
if os.path.isdir(jar_path):
shutil.rmtree(jar_path)
os.mkdir(jar_path)
shutil.copy(JAR_FILE[0], os.path.join(jar_path, 'lolo-jar-with-dependencies.jar'))
with open('README.md') as f:
long_description = f.read()
# Make the installation
setup(
name='lolopy',
version=version,
url='https://github.com/CitrineInformatics/lolo',
maintainer='Max Hutchinson',
maintainer_email='[email protected]',
packages=[
'lolopy',
'lolopy.jar' # Used for the PyPi packaging
],
include_package_data=True,
package_data={'lolopy.jar': ['*.jar']},
install_requires=['scikit-learn', 'py4j'],
description='Python wrapper for the Lolo machine learning library',
long_description=long_description,
long_description_content_type="text/markdown",
)
| 1,522 | 31.404255 | 102 | py |
lolo | lolo-main/python/lolopy/utils.py | import sys
import numpy as np
def send_feature_array(gateway, X):
"""Send a feature array to the JVM
Args:
gateway (JavaGateway): Connection the JVM
X ([[double]]): 2D array of features
Returns:
(Seq[Vector[Double]]) Reference to feature array in JVM
"""
# Convert X to a numpy array
X = np.array(X, dtype=np.float64)
big_end = sys.byteorder == "big"
# Send X to the JVM
X_java = gateway.jvm.io.citrine.lolo.util.LoloPyDataLoader.getFeatureArray(X.tobytes(), X.shape[1],
big_end)
return X_java
def send_1D_array(gateway, y, is_float):
"""Send a feature array to the JVM
Args:
gateway (JavaGateway): Connection the JVM
y ([[double]]): 1D array to be sent
is_float (bool): Whether to send data as a float
Returns:
(Seq[Vector[Double]]) Reference to feature array in JVM
"""
# Convert X to a numpy array
y = np.array(y, dtype=np.float64 if is_float else np.int32)
big_end = sys.byteorder == "big"
# Send X to the JVM
y_java = gateway.jvm.io.citrine.lolo.util.LoloPyDataLoader.get1DArray(y.tobytes(), is_float, big_end)
return y_java | 1,266 | 29.902439 | 105 | py |
lolo | lolo-main/python/lolopy/loloserver.py | """Methods related to starting and stopping the Java Gateway"""
from py4j.java_gateway import JavaGateway
import sys
import os
# Directory where the lolo project root should be
_lolo_root = os.path.join(os.path.dirname(__file__), '..', '..')
# Used for allowing multiple objects to use the same gateway
_lolopy_gateway = None
def _is_development_installation():
"""Check whether lolopy is in a folder with the rest of lolo"""
# Look for the lolo scala source directory
return os.path.isdir(os.path.join(_lolo_root, 'src', 'main', 'scala', 'io', 'citrine', 'lolo'))
def find_lolo_jar(skip_devel_version=False):
"""Attempt to automatically find a jar file for Lolo
Args:
skip_devel_version (bool): Skip looking for the development version of lolo
Returns:
(string) Path to the Jar file
"""
if not skip_devel_version and _is_development_installation():
# Get the appropriate Jar
jar_path = os.path.join(_lolo_root, 'target', 'scala-2.13', 'lolo-jar-with-dependencies.jar')
if not os.path.isfile(jar_path):
raise RuntimeError('Current version of lolo jar not found. Try re-building project with make')
else:
# Use the local installation
jar_path = os.path.join(os.path.dirname(__file__), 'jar', 'lolo-jar-with-dependencies.jar')
if not os.path.isfile(jar_path):
raise RuntimeError('Lolo not found. Try reinstalling lolo from PyPi.')
return jar_path
def get_java_gateway(reuse=True, skip_devel_version=False):
"""Get a JavaGateway with Lolo on the class path
Args:
reuse (bool): Whether to reuse an already-existing gateway
skip_devel_version (bool): Whether to skip looking for the development version of lolopy
Returns:
(JavaGateway) A launched JavaGateway instance
"""
global _lolopy_gateway
# Set any default java options
java_options = [] # No default options for now
# Get an environmental variable set for the amount of heap memory
if 'LOLOPY_JVM_MEMORY' in os.environ:
java_options.append('-Xmx' + os.environ['LOLOPY_JVM_MEMORY'])
# Make the gateway if none already active or user requests a fresh JVM
if _lolopy_gateway is None or not reuse:
lolo_path = find_lolo_jar(skip_devel_version)
_lolopy_gateway = JavaGateway.launch_gateway(
classpath=os.path.pathsep.join([os.path.abspath(lolo_path)]),
javaopts=java_options,
redirect_stdout=sys.stdout, die_on_exit=True)
return _lolopy_gateway
| 2,571 | 35.225352 | 106 | py |
lolo | lolo-main/python/lolopy/version.py | # single source of truth for package version,
# see https://packaging.python.org/en/latest/single_source_version/
__version__ = "3.0.0"
| 136 | 33.25 | 67 | py |
lolo | lolo-main/python/lolopy/metrics.py | """Functions to call lolo Merit classes, which describe the performance of a machine learning model
These are very similar to the "metrics" from scikit-learn, which is the reason for the name of this module.
"""
from lolopy.loloserver import get_java_gateway
from lolopy.utils import send_1D_array
import numpy as np
def _call_lolo_merit(metric_name, y_true, y_pred, random_seed=None, y_std=None, *args):
"""Call a metric from lolopy
Args:
metric_name (str): Name of a Merit class (e.g., UncertaintyCorrelation)
y_true ([double]): True value
y_pred ([double]): Predicted values
random_seed (int): for reproducibility (only used by some metrics)
y_std ([double]): Prediction uncertainties (only used by some metrics)
*args: Any parameters to the constructor of the Metric
Returns:
(double): Metric score
"""
# If needed, set y_std to 1 for all entries
if y_std is None:
y_std = np.ones(len(y_true))
gateway = get_java_gateway()
# Get default rng
rng = gateway.jvm.io.citrine.lolo.util.LoloPyRandom.getRng(random_seed) if random_seed \
else gateway.jvm.io.citrine.lolo.util.LoloPyRandom.getRng()
# Get the metric object
metric = getattr(gateway.jvm.io.citrine.lolo.validation, metric_name)
if len(args) > 0:
metric = metric(*args)
# Convert the data arrays to Java
y_true_java = send_1D_array(gateway, y_true, True)
y_pred_java = send_1D_array(gateway, y_pred, True)
y_std_java = send_1D_array(gateway, y_std, True)
# Make the prediction result
pred_result = gateway.jvm.io.citrine.lolo.util.LoloPyDataLoader.makeRegressionPredictionResult(y_pred_java, y_std_java)
# Run the prediction result through the metric
return metric.evaluate(pred_result, y_true_java, rng)
def root_mean_squared_error(y_true, y_pred):
"""Compute the root mean squared error
Args:
y_true ([double]): True value
y_pred ([double]): Predicted values
Returns:
(double): RMSE
"""
return _call_lolo_merit('RootMeanSquareError', y_true, y_pred)
def standard_confidence(y_true, y_pred, y_std):
"""Fraction of entries that have errors within the predicted confidence interval.
Args:
y_true ([double]): True value
y_pred ([double]): Predicted values
y_std ([double]): Predicted uncertainty
Returns:
(double): standard confidence
"""
return _call_lolo_merit('StandardConfidence', y_true, y_pred, y_std=y_std)
def standard_error(y_true, y_pred, y_std, rescale=1.0):
"""Root mean square of the error divided by the predicted uncertainty
Args:
y_true ([double]): True value
y_pred ([double]): Predicted values
y_std ([double]): Predicted uncertainty
rescale (double): Multiplicative factor with which to rescale error
Returns:
(double): standard error
"""
return _call_lolo_merit('StandardError', y_true, y_pred, None, y_std, float(rescale))
def uncertainty_correlation(y_true, y_pred, y_std, random_seed=None):
"""Measure of the correlation between the predicted uncertainty and error magnitude
Args:
y_true ([double]): True value
y_pred ([double]): Predicted values
y_std ([double]): Predicted uncertainty
random_seed (int): for reproducibility
Returns:
(double):
"""
return _call_lolo_merit('UncertaintyCorrelation', y_true, y_pred, random_seed=random_seed, y_std=y_std)
| 3,556 | 33.201923 | 123 | py |
lolo | lolo-main/python/lolopy/__init__.py | 0 | 0 | 0 | py |
|
lolo | lolo-main/python/lolopy/learners.py | from abc import abstractmethod, ABCMeta
import numpy as np
from lolopy.loloserver import get_java_gateway
from lolopy.utils import send_feature_array, send_1D_array
from sklearn.base import BaseEstimator, RegressorMixin, ClassifierMixin, is_regressor
from sklearn.exceptions import NotFittedError
__all__ = [
'RandomForestRegressor',
'RandomForestClassifier',
'MultiTaskRandomForest',
'ExtraRandomTreesRegressor',
'ExtraRandomTreesClassifier'
]
class BaseLoloLearner(BaseEstimator, metaclass=ABCMeta):
"""Base object for all leaners that use Lolo.
Contains logic for starting the JVM gateway, and the fit operations.
It is only necessary to implement the `_make_learner` object and create an `__init__` function
to adapt a learner from the Lolo library for use in lolopy.
The logic for making predictions (i.e., `predict` and `predict_proba`) is specific to whether the learner
is a classification or regression model.
In lolo, learners are not specific to a regression or classification problem and the type of problem is determined
when fitting data is provided to the algorithm.
In contrast, Scikit-learn learners for regression or classification problems are different classes.
We have implemented `BaseLoloRegressor` and `BaseLoloClassifier` abstract classes to make it easier to create
a classification or regression version of a Lolo base class.
The pattern for creating a scikit-learn compatible learner is to first implement the `_make_learner` and `__init__`
operations in a special "Mixin" class that inherits from `BaseLoloLearner`, and then create a regression- or
classification-specific class that inherits from both `BaseClassifier` or `BaseRegressor` and your new "Mixin".
See the RandomForest models as an example of this approach.
"""
def __init__(self):
self.gateway = get_java_gateway()
# Create a placeholder for the model
self.model_ = None
self._num_outputs = None
self._compress_level = 9
self.feature_importances_ = None
def __getstate__(self):
# Get the current state
try:
state = super(BaseLoloLearner, self).__getstate__()
except AttributeError:
state = self.__dict__.copy()
# Delete the gateway data
del state['gateway']
# If there is a model set, replace it with the JVM copy
if self.model_ is not None:
state['model_'] = self.gateway.jvm.io.citrine.lolo.util.LoloPyDataLoader.serializeObject(self.model_,
self._compress_level)
return state
def __setstate__(self, state):
# Unpickle the object
super(BaseLoloLearner, self).__setstate__(state)
# Get a pointer to the gateway
self.gateway = get_java_gateway()
# If needed, load the model into memory
if state['model_'] is not None:
bytes = state.pop('model_')
self.model_ = self.gateway.jvm.io.citrine.lolo.util.LoloPyDataLoader.deserializeObject(bytes)
def fit(self, X, y, weights=None, random_seed=None):
# Instantiate the JVM object
learner = self._make_learner()
# Determine the number of outputs
y_shape = np.asarray(y).shape
if len(y_shape) == 1:
self._num_outputs = 1
elif len(y_shape) == 2:
self._num_outputs = y.shape[1]
else:
raise ValueError("Output array must be either 1- or 2-dimensional")
# Convert all of the training data to Java training rows
training_data = self._convert_training_data(X, y, weights)
assert training_data.length() == len(X), "Array copy failed"
assert training_data.head().inputs().length() == len(X[0]), "Wrong number of features"
# Train the model
rng = self.gateway.jvm.io.citrine.lolo.util.LoloPyRandom.getRng(random_seed) if random_seed \
else self.gateway.jvm.io.citrine.lolo.util.LoloPyRandom.getRng()
result = learner.train(training_data, rng)
# Unlink the training data, which is no longer needed (to save memory)
self.gateway.detach(training_data)
# Get the model out
self.model_ = result.model()
# Store the feature importances
feature_importances_java = result.featureImportance().get()
feature_importances_bytes = self.gateway.jvm.io.citrine.lolo.util.LoloPyDataLoader.send1DArray(feature_importances_java)
self.feature_importances_ = np.frombuffer(feature_importances_bytes, 'float')
return self
@abstractmethod
def _make_learner(self):
"""Instantiate the learner used by Lolo to train a model
Returns:
(JavaObject) A lolo "Learner" object, which can be used to train a model"""
pass
def clear_model(self):
"""Utility operation for deleting model from JVM when no longer needed"""
if self.model_ is not None:
self.gateway.detach(self.model_)
self.model_ = None
def _convert_training_data(self, X, y, weights=None):
"""Convert the training data to a form accepted by Lolo
Args:
X (ndarray): Input variables
y (ndarray): Output variables
weights (ndarray): Weights for each sample
Returns
training_data (JavaObject): Pointer to the rows of training data in Java
"""
# Make some default weights
if weights is None:
weights = np.ones(len(y))
# Convert y and w to float64 or int32 with native ordering
y = np.array(y, dtype=np.float64 if is_regressor(self) else np.int32)
weights = np.array(weights, dtype=np.float64)
# Convert X, y, and w to Java Objects
X_java = send_feature_array(self.gateway, X)
if self._num_outputs == 1:
y_java = send_1D_array(self.gateway, y, is_regressor(self))
else:
y_java = send_feature_array(self.gateway, y)
assert y_java.length() == len(y) == len(X)
w_java = send_1D_array(self.gateway, weights, True)
assert w_java.length() == len(weights)
# Build the training rows
training_data = self.gateway.jvm.io.citrine.lolo.util.LoloPyDataLoader.buildTrainingRows(X_java, y_java, w_java)
# Detach the intermediate arrays before returning
self.gateway.detach(X_java)
self.gateway.detach(y_java)
self.gateway.detach(w_java)
return training_data
def _convert_run_data(self, X):
"""Convert the data to be run by the model
Args:
X (ndarray): Input data
Returns:
(JavaObject): Pointer to run data in Java
"""
if not isinstance(X, np.ndarray):
X = np.array(X)
return self.gateway.jvm.io.citrine.lolo.util.LoloPyDataLoader.getFeatureArray(X.tobytes(), X.shape[1], False)
def get_importance_scores(self, X):
"""Get the importance scores for each entry in the training set for each prediction
Args:
X (ndarray): Inputs for each entry to be assessed
"""
pred_result = self._get_prediction_result(X)
y_import_bytes = self.gateway.jvm.io.citrine.lolo.util.LoloPyDataLoader.getImportanceScores(pred_result)
y_import = np.frombuffer(y_import_bytes, 'float').reshape(len(X), -1)
return y_import
def _get_prediction_result(self, X):
"""Get the PredictionResult from the lolo JVM
The PredictionResult class holds methods that will generate the expected predictions, uncertainty intervals, etc
Args:
X (ndarray): Input features for each entry
Returns:
(JavaObject): Prediction result produced by evaluating the model
"""
# Check that the model is fitted
if self.model_ is None:
raise NotFittedError()
# Convert the data to Java
X_java = self._convert_run_data(X)
# Get the PredictionResult
pred_result = self.model_.transform(X_java)
# Unlink the run data, which is no longer needed (to save memory)
self.gateway.detach(X_java)
return pred_result
class BaseLoloRegressor(BaseLoloLearner, RegressorMixin):
"""Abstract class for models that produce regression models.
As written, this allows for both single-task and multi-task models.
Implements the predict operation."""
def predict(self, X, return_std = False, return_cov_matrix = False):
"""
Apply the model to a matrix of inputs, producing predictions and optionally some measure of uncertainty
Args:
X (ndarray): Input array
return_std (bool): if True, return the standard deviations along with the predictions
return_cov_matrix (bool): If True, return the covariance matrix along with the predictions
Returns
Sequence of predictions OR
(Sequence of predictions, Sequence of standard deviations) OR
(Sequence of predictions, Sequence of covariance matrices).
Each prediction and standard deviation is a float (for single-output learners) or an array (for multi-output learners).
Each covariance matrix entry is a (# outputs x # outputs) matrix.
"""
if return_std and return_cov_matrix:
raise ValueError("Only one of return_std or return_cov_matrix can be True")
# Start the prediction process
pred_result = self._get_prediction_result(X)
# Pull out the expected values
if self._num_outputs == 1:
y_pred_byte = self.gateway.jvm.io.citrine.lolo.util.LoloPyDataLoader.getRegressionExpected(pred_result)
y_pred = np.frombuffer(y_pred_byte, dtype='float') # Lolo gives a byte array back
else:
y_pred_byte = self.gateway.jvm.io.citrine.lolo.util.LoloPyDataLoader.getMultiRegressionExpected(pred_result)
y_pred = np.frombuffer(y_pred_byte, dtype='float').reshape(-1, self._num_outputs)
if return_std:
y_std = self._get_std(X, pred_result)
return y_pred, y_std
if return_cov_matrix:
corr_matrix = self._get_corr_matrix(X, pred_result)
y_std = self._get_std(X, pred_result).reshape(-1, self._num_outputs)
sigma_sq_matrix = np.array([np.outer(y_std[i, :], y_std[i, :]) for i in range(len(X))])
# both sigma_squared and correlation matrices have size (# predictions, # outputs, # outputs).
# They are multiplied term-by-term to produce the covariance matrix.
cov_matrix = sigma_sq_matrix * corr_matrix
return y_pred, cov_matrix
# Get the expected values
return y_pred
def _get_std(self, X, pred_result):
# TODO: This part fails on Windows because the NativeSystemBLAS is not found. Fix that
if self._num_outputs == 1:
y_std_bytes = self.gateway.jvm.io.citrine.lolo.util.LoloPyDataLoader.getRegressionUncertainty(pred_result)
return np.frombuffer(y_std_bytes, 'float')
else:
y_std_bytes = self.gateway.jvm.io.citrine.lolo.util.LoloPyDataLoader.getMultiRegressionUncertainty(pred_result)
return np.frombuffer(y_std_bytes, 'float').reshape(-1, self._num_outputs)
def _get_corr_matrix(self, X, pred_result):
num_predictions = len(X)
corr_matrix = np.zeros((num_predictions, self._num_outputs, self._num_outputs))
idx = np.arange(self._num_outputs)
corr_matrix[:, idx, idx] = 1.0
for i in range(self._num_outputs - 1):
for j in range(i + 1, self._num_outputs):
rho_bytes = self.gateway.jvm.io.citrine.lolo.util.LoloPyDataLoader.getRegressionCorrelation(pred_result, i, j)
rho = np.frombuffer(rho_bytes, 'float')
corr_matrix[:, i, j] = rho
corr_matrix[:, j, i] = rho
return corr_matrix
class BaseLoloClassifier(BaseLoloLearner, ClassifierMixin):
"""Base class for classification models
Implements a modification to the fit operation that stores the number of classes
and the predict/predict_proba methods"""
def fit(self, X, y, weights=None, random_seed=None):
# Get the number of classes
self.n_classes_ = len(set(y))
return super(BaseLoloClassifier, self).fit(X, y, weights, random_seed)
def predict(self, X):
pred_result = self._get_prediction_result(X)
# Pull out the expected values
y_pred_byte = self.gateway.jvm.io.citrine.lolo.util.LoloPyDataLoader.getClassifierExpected(pred_result)
y_pred = np.frombuffer(y_pred_byte, dtype=np.int32) # Lolo gives a byte array back
return y_pred
def predict_proba(self, X):
pred_result = self._get_prediction_result(X)
# Copy over the class probabilities
probs_byte = self.gateway.jvm.io.citrine.lolo.util.LoloPyDataLoader.getClassifierProbabilities(pred_result, self.n_classes_)
probs = np.frombuffer(probs_byte, dtype='float').reshape(-1, self.n_classes_)
return probs
class RandomForestRegressor(BaseLoloRegressor):
"""Random Forest model used for regression"""
def __init__(self, num_trees=-1, use_jackknife=True, bias_learner=None,
leaf_learner=None, subset_strategy="auto", min_leaf_instances=1,
max_depth=2**30, uncertainty_calibration=False, randomize_pivot_location=False,
randomly_rotate_features=False):
"""Initialize the RandomForest
Args:
num_trees (int): Number of trees to use in the forest (default of -1 sets the number of trees to the number of training rows)
use_jackknife (bool): Whether to use jackknife based variance estimates
bias_learner (BaseLoloLearner): Algorithm used to model bias (default: no model)
leaf_learner (BaseLoloLearner): Learner used at each leaf of the random forest (default: GuessTheMean)
subset_strategy (Union[string,int,float]): Strategy used to determine number of features used at each split
Available options:
"auto": Use the default for lolo (all features for regression, sqrt for classification)
"log2": Use the base 2 log of the number of features
"sqrt": Use the square root of the number of features
integer: Set the number of features explicitly
float: Use a certain fraction of the features
min_leaf_instances (int): Minimum number of features used at each leaf
max_depth (int): Maximum depth to which to allow the decision trees to grow
uncertainty_calibration (bool): whether to re-calibrate the predicted uncertainty based on out-of-bag residuals
randomize_pivot_location (bool): whether to draw pivots randomly or always select the midpoint
randomly_rotate_features (bool): whether to randomly rotate real features for each tree in the forest
"""
super().__init__()
# Store the variables
self.num_trees = num_trees
self.use_jackknife = use_jackknife
self.subset_strategy = subset_strategy
self.bias_learner = bias_learner
self.leaf_learner = leaf_learner
self.min_leaf_instances = min_leaf_instances
self.max_depth = max_depth
self.uncertainty_calibration = uncertainty_calibration
self.randomize_pivot_location = randomize_pivot_location
self.randomly_rotate_features = randomly_rotate_features
def _make_learner(self):
if self.bias_learner is None:
bias_learner = getattr(self.gateway.jvm.io.citrine.lolo.learners.RandomForestRegressor, "$lessinit$greater$default$3")()
else:
bias_learner = self.gateway.jvm.scala.Some(self.bias_learner._make_learner())
if self.leaf_learner is None:
leaf_learner = getattr(self.gateway.jvm.io.citrine.lolo.learners.RandomForestRegressor, "$lessinit$greater$default$4")()
else:
leaf_learner = self.gateway.jvm.scala.Some(self.leaf_learner._make_learner())
return self.gateway.jvm.io.citrine.lolo.learners.RandomForestRegressor(
self.num_trees,
self.use_jackknife,
bias_learner,
leaf_learner,
self.subset_strategy,
self.min_leaf_instances,
self.max_depth,
self.uncertainty_calibration,
self.randomize_pivot_location,
self.randomly_rotate_features
)
class RandomForestClassifier(BaseLoloClassifier):
"""Random Forest model used for classification"""
def __init__(self, num_trees=-1, use_jackknife=False, leaf_learner=None, subset_strategy="auto",
min_leaf_instances=1, max_depth=2**30, randomize_pivot_location=False, randomly_rotate_features=False):
"""Initialize the RandomForest
Args:
num_trees (int): Number of trees to use in the forest (default of -1 sets the number of trees to the number of training rows)
use_jackknife (bool): Whether to use jackknife based variance estimates
leaf_learner (BaseLoloLearner): Learner used at each leaf of the random forest (default: GuessTheMean)
subset_strategy (Union[string,int,float]): Strategy used to determine number of features used at each split
Available options:
"auto": Use the default for lolo (all features for regression, sqrt for classification)
"log2": Use the base 2 log of the number of features
"sqrt": Use the square root of the number of features
integer: Set the number of features explicitly
float: Use a certain fraction of the features
min_leaf_instances (int): Minimum number of features used at each leaf
max_depth (int): Maximum depth to which to allow the decision trees to grow
randomize_pivot_location (bool): whether to draw pivots randomly or always select the midpoint
randomly_rotate_features (bool): whether to randomly rotate real features for each tree in the forest
"""
super().__init__()
# Store the variables
self.num_trees = num_trees
self.use_jackknife = use_jackknife
self.subset_strategy = subset_strategy
self.leaf_learner = leaf_learner
self.min_leaf_instances = min_leaf_instances
self.max_depth = max_depth
self.randomize_pivot_location = randomize_pivot_location
self.randomly_rotate_features = randomly_rotate_features
def _make_learner(self):
if self.leaf_learner is None:
leaf_learner = getattr(self.gateway.jvm.io.citrine.lolo.learners.RandomForestClassifier, "$lessinit$greater$default$3")()
else:
leaf_learner = self.gateway.jvm.scala.Some(self.leaf_learner._make_learner())
return self.gateway.jvm.io.citrine.lolo.learners.RandomForestClassifier(
self.num_trees,
self.use_jackknife,
leaf_learner,
self.subset_strategy,
self.min_leaf_instances,
self.max_depth,
self.randomize_pivot_location,
self.randomly_rotate_features
)
class MultiTaskRandomForest(BaseLoloRegressor):
"""Random Forest model used for regression on multiple outputs."""
def __init__(self, num_trees=-1, use_jackknife=True, bias_learner=None,
subset_strategy="auto", min_leaf_instances=1, max_depth=2**30, uncertainty_calibration=False,
randomize_pivot_location=False, randomly_rotate_features=False):
"""Initialize the RandomForest
Args:
num_trees (int): Number of trees to use in the forest (default of -1 sets the number of trees to the number of training rows)
use_jackknife (bool): Whether to use jackknife based variance estimates
bias_learner (BaseLoloLearner): Algorithm used to model bias (default: no model)
subset_strategy (Union[string,int,float]): Strategy used to determine number of features used at each split
Available options:
"auto": Use the default for lolo (all features for regression, sqrt for classification)
"log2": Use the base 2 log of the number of features
"sqrt": Use the square root of the number of features
integer: Set the number of features explicitly
float: Use a certain fraction of the features
min_leaf_instances (int): Minimum number of features used at each leaf
max_depth (int): Maximum depth to which to allow the decision trees to grow
uncertainty_calibration (bool): whether to re-calibrate the predicted uncertainty based on out-of-bag residuals
randomize_pivot_location (bool): whether to draw pivots randomly or always select the midpoint
randomly_rotate_features (bool): whether to randomly rotate real features for each tree in the forest
"""
super().__init__()
# Store the variables
self.num_trees = num_trees
self.use_jackknife = use_jackknife
self.subset_strategy = subset_strategy
self.bias_learner = bias_learner
self.min_leaf_instances = min_leaf_instances
self.max_depth = max_depth
self.uncertainty_calibration = uncertainty_calibration
self.randomize_pivot_location = randomize_pivot_location
self.randomly_rotate_features = randomly_rotate_features
def _make_learner(self):
if self.bias_learner is None:
bias_learner = getattr(self.gateway.jvm.io.citrine.lolo.learners.MultiTaskRandomForest, "$lessinit$greater$default$3")()
else:
bias_learner = self.gateway.jvm.scala.Some(self.bias_learner._make_learner())
return self.gateway.jvm.io.citrine.lolo.learners.MultiTaskRandomForest(
self.num_trees,
self.use_jackknife,
bias_learner,
self.subset_strategy,
self.min_leaf_instances,
self.max_depth,
self.uncertainty_calibration,
self.randomize_pivot_location,
self.randomly_rotate_features
)
class ExtraRandomTreesRegressor(BaseLoloRegressor):
"""Extra Random Trees model used for regression."""
def __init__(self, num_trees=-1, use_jackknife=False, bias_learner=None,
leaf_learner=None, subset_strategy="auto", min_leaf_instances=1,
max_depth=2**30, uncertainty_calibration=False, disable_bootstrap=True,
randomly_rotate_features=False):
"""Initialize the ExtraRandomTrees ensemble
Args:
num_trees (int): Number of trees to use in the forest (default of -1 sets the number of trees to the number of training rows)
use_jackknife (bool): Whether to use jackknife based variance estimates (default: False)
bias_learner (BaseLoloLearner): Algorithm used to model bias (default: no model)
leaf_learner (BaseLoloLearner): Learner used at each leaf of the random forest (default: GuessTheMean)
subset_strategy (Union[string,int,float]): Strategy used to determine number of features used at each split
Available options:
"auto": Use the default for lolo (all features for regression; classification not supported)
"log2": Use the base 2 log of the number of features
"sqrt": Use the square root of the number of features
integer: Set the number of features explicitly
float: Use a certain fraction of the features
min_leaf_instances (int): Minimum number of features used at each leaf
max_depth (int): Maximum depth to which to allow the decision trees to grow
uncertainty_calibration (bool): whether to re-calibrate the predicted uncertainty based on out-of-bag residuals
disable_bootstrap (bool): whether to disable bootstrapping (default: True)
randomly_rotate_features (bool): whether to randomly rotate real features for each tree in the forest
"""
super().__init__()
# Store the variables
self.num_trees = num_trees
self.use_jackknife = use_jackknife
self.bias_learner = bias_learner
self.leaf_learner = leaf_learner
self.subset_strategy = subset_strategy
self.min_leaf_instances = min_leaf_instances
self.max_depth = max_depth
self.uncertainty_calibration = uncertainty_calibration
self.disable_bootstrap = disable_bootstrap
self.randomly_rotate_features = randomly_rotate_features
def _make_learner(self):
if self.bias_learner is None:
bias_learner = getattr(self.gateway.jvm.io.citrine.lolo.learners.ExtraRandomTreesRegressor, "$lessinit$greater$default$3")()
else:
bias_learner = self.gateway.jvm.scala.Some(self.bias_learner._make_learner())
if self.leaf_learner is None:
leaf_learner = getattr(self.gateway.jvm.io.citrine.lolo.learners.ExtraRandomTreesRegressor, "$lessinit$greater$default$4")()
else:
leaf_learner = self.gateway.jvm.scala.Some(self.leaf_learner._make_learner())
return self.gateway.jvm.io.citrine.lolo.learners.ExtraRandomTreesRegressor(
self.num_trees,
self.use_jackknife,
bias_learner,
leaf_learner,
self.subset_strategy,
self.min_leaf_instances,
self.max_depth,
self.uncertainty_calibration,
self.disable_bootstrap,
self.randomly_rotate_features
)
class ExtraRandomTreesClassifier(BaseLoloClassifier):
"""Extra Random Trees model used for classification."""
def __init__(self, num_trees=-1, use_jackknife=False, bias_learner=None,
leaf_learner=None, subset_strategy="auto", min_leaf_instances=1,
max_depth=2**30, uncertainty_calibration=False, disable_bootstrap=True,
randomly_rotate_features=False):
"""Initialize the ExtraRandomTrees ensemble
Args:
num_trees (int): Number of trees to use in the forest (default of -1 sets the number of trees to the number of training rows)
use_jackknife (bool): Whether to use jackknife based variance estimates (default: False)
leaf_learner (BaseLoloLearner): Learner used at each leaf of the random forest (default: GuessTheMean)
subset_strategy (Union[string,int,float]): Strategy used to determine number of features used at each split
Available options:
"auto": Use the default for lolo (all features for regression; classification not supported)
"log2": Use the base 2 log of the number of features
"sqrt": Use the square root of the number of features
integer: Set the number of features explicitly
float: Use a certain fraction of the features
min_leaf_instances (int): Minimum number of features used at each leaf
max_depth (int): Maximum depth to which to allow the decision trees to grow
disable_bootstrap (bool): whether to disable bootstrapping (default: True)
randomly_rotate_features (bool): whether to randomly rotate real features for each tree in the forest
"""
super().__init__()
# Store the variables
self.num_trees = num_trees
self.use_jackknife = use_jackknife
self.bias_learner = bias_learner
self.leaf_learner = leaf_learner
self.subset_strategy = subset_strategy
self.min_leaf_instances = min_leaf_instances
self.max_depth = max_depth
self.uncertainty_calibration = uncertainty_calibration
self.disable_bootstrap = disable_bootstrap
self.randomly_rotate_features = randomly_rotate_features
def _make_learner(self):
if self.leaf_learner is None:
leaf_learner = getattr(self.gateway.jvm.io.citrine.lolo.learners.ExtraRandomTreesClassifier, "$lessinit$greater$default$3")()
else:
leaf_learner = self.gateway.jvm.scala.Some(self.leaf_learner._make_learner())
return self.gateway.jvm.io.citrine.lolo.learners.ExtraRandomTreesClassifier(
self.num_trees,
self.use_jackknife,
leaf_learner,
self.subset_strategy,
self.min_leaf_instances,
self.max_depth,
self.disable_bootstrap,
self.randomly_rotate_features
)
class RegressionTreeLearner(BaseLoloRegressor):
"""Regression tree learner, based on the decision tree algorithm."""
def __init__(self, num_features=-1, max_depth=30, min_leaf_instances=1, leaf_learner=None):
"""Initialize the learner
Args:
num_features (int): Number of features to consider at each split (-1 to consider all features)
max_depth (int): Maximum depth of the regression tree
min_leaf_instances (int): Minimum number instances per leaf
leaf_learner (BaseLoloLearner): Learner to use on the leaves
"""
super().__init__()
self.num_features = num_features
self.max_depth = max_depth
self.min_leaf_instances = min_leaf_instances
self.leaf_learner = leaf_learner
def _make_learner(self):
if self.leaf_learner is None:
# pull out default learner
leaf_learner = getattr(self.gateway.jvm.io.citrine.lolo.trees.regression.RegressionTreeLearner, "$lessinit$greater$default$4")()
else:
leaf_learner = self.gateway.jvm.scala.Some(self.leaf_learner._make_learner())
# pull out default splitter
splitter = getattr(self.gateway.jvm.io.citrine.lolo.trees.regression.RegressionTreeLearner, "$lessinit$greater$default$5")()
return self.gateway.jvm.io.citrine.lolo.trees.regression.RegressionTreeLearner(
self.num_features,
self.max_depth,
self.min_leaf_instances,
leaf_learner,
splitter
)
class LinearRegression(BaseLoloRegressor):
"""Linear ridge regression with an :math:`L_2` penalty"""
def __init__(self, reg_param=None, fit_intercept=True):
"""Initialize the regressor"""
super().__init__()
self.reg_param = reg_param
self.fit_intercept = fit_intercept
def _make_learner(self):
if self.reg_param is None:
reg_param = getattr(self.gateway.jvm.io.citrine.lolo.linear.LinearRegressionLearner, "$lessinit$greater$default$1")()
else:
reg_param = self.gateway.jvm.scala.Some(float(self.reg_param))
return self.gateway.jvm.io.citrine.lolo.linear.LinearRegressionLearner(reg_param, self.fit_intercept)
| 31,442 | 45.651335 | 140 | py |
lolo | lolo-main/python/lolopy/tests/test_learners.py | from lolopy.learners import (
RandomForestRegressor,
RandomForestClassifier,
MultiTaskRandomForest,
RegressionTreeLearner,
LinearRegression,
ExtraRandomTreesRegressor,
ExtraRandomTreesClassifier
)
from sklearn.exceptions import NotFittedError
from sklearn.metrics import r2_score, accuracy_score, log_loss
from sklearn.datasets import load_iris, load_diabetes, load_linnerud
from unittest import TestCase, main
import pickle as pkl
import numpy as np
import logging
logging.getLogger("py4j.java_gateway").setLevel(logging.ERROR)
def _make_linear_data():
"""Make data corresponding to y = x + 1
Returns:
np.ndarray: X
np.ndarray: y
"""
# Make y = x + 1
X = np.linspace(0, 1, 32)
y = X + 1
# Make X a 2D array
X = X[:, None]
return X, y
class TestRF(TestCase):
def test_rf_regressor(self):
rf = RandomForestRegressor()
# Train the model
X, y = load_diabetes(return_X_y=True)
# Make sure we get a NotFittedError
with self.assertRaises(NotFittedError):
rf.predict(X)
# Fit the model
rf.fit(X, y, random_seed=31247895)
# Run some predictions
y_pred = rf.predict(X)
self.assertEqual(len(y_pred), len(y))
# Test the ability to get importance scores
y_import = rf.get_importance_scores(X[:100, :])
self.assertEqual((100, len(X)), y_import.shape)
# Basic test for functionality. R^2 above 0.88 was measured on 2021-12-09
score = r2_score(y_pred, y)
print('R^2:', score)
self.assertGreater(score, 0.88)
# Test with weights (make sure it doesn't crash)
rf.fit(X, y, [2.0]*len(y))
# Make sure feature importances are stored
self.assertEqual(np.shape(rf.feature_importances_), (X.shape[1],))
self.assertAlmostEqual(1.0, np.sum(rf.feature_importances_))
# Run predictions with std dev
y_pred, y_std = rf.predict(X, return_std=True)
self.assertEqual(len(y_pred), len(y_std))
self.assertTrue((y_std >= 0).all()) # They must be positive
self.assertGreater(np.std(y_std), 0) # Must have a variety of values
# For a single output, the covariance matrix is just the standard deviation squared
_, y_cov = rf.predict(X, return_cov_matrix=True)
assert np.all(y_cov.flatten() == y_std ** 2)
# Make sure the detach operation functions
rf.clear_model()
self.assertIsNone(rf.model_)
def test_reproducibility(self):
seed = 31247895
rf1 = RandomForestRegressor()
rf2 = RandomForestRegressor()
X, y = load_diabetes(return_X_y=True)
rf1.fit(X, y, random_seed=seed)
rf2.fit(X, y, random_seed=seed)
pred1 = rf1.predict(X)
pred2 = rf2.predict(X)
self.assertTrue((pred1 == pred2).all())
def test_rf_multioutput_regressor(self):
rf = MultiTaskRandomForest()
# A regression dataset with 3 outputs
X, y = load_linnerud(return_X_y=True)
num_data = len(X)
num_outputs = y.shape[1]
rf.fit(X, y, random_seed=810355)
y_pred, y_std = rf.predict(X, return_std=True)
_, y_cov = rf.predict(X, return_cov_matrix=True)
# Assert that all returned values have the correct shape
assert y_pred.shape == (num_data, num_outputs)
assert y_std.shape == (num_data, num_outputs)
assert y_cov.shape == (num_data, num_outputs, num_outputs)
# The covariance matrices should be symmetric and the diagonals should be the squares of the standard deviations.
assert np.all(y_cov[:, 0, 1] == y_cov[:, 1, 0])
assert np.all(y_cov[:, 0, 0] == y_std[:, 0] ** 2)
# Make sure the user cannot call predict with both return_std and return_cov_matrix True
with self.assertRaises(ValueError):
rf.predict(X, return_std=True, return_cov_matrix=True)
def test_classifier(self):
rf = RandomForestClassifier()
# Load in the iris dataset
X, y = load_iris(return_X_y=True)
rf.fit(X, y, random_seed=34789)
# Predict the probability of membership in each class
y_prob = rf.predict_proba(X)
self.assertEqual((len(X), 3), np.shape(y_prob))
self.assertAlmostEqual(len(X), np.sum(y_prob))
ll_score = log_loss(y, y_prob)
print('Log loss:', ll_score)
self.assertLess(ll_score, 0.03) # Measured at 0.026 27Dec18
# Test just getting the predicted class
y_pred = rf.predict(X)
self.assertTrue(np.isclose(np.argmax(y_prob, 1), y_pred).all())
self.assertEqual(len(X), len(y_pred))
acc = accuracy_score(y, y_pred)
print('Accuracy:', acc)
self.assertAlmostEqual(acc, 1) # Given default settings, we should get perfect fitness to training data
def test_serialization(self):
rf = RandomForestClassifier()
# Make sure this doesn't error without a model training
data = pkl.dumps(rf)
rf2 = pkl.loads(data)
# Load in the iris dataset and train model
X, y = load_iris(return_X_y=True)
rf.fit(X, y, random_seed=234785)
# Try saving and loading the model
data = pkl.dumps(rf)
rf2 = pkl.loads(data)
# Make sure it yields the same predictions as the first model
probs1 = rf.predict_proba(X)
probs2 = rf2.predict_proba(X)
self.assertTrue(np.isclose(probs1, probs2).all())
def test_regression_tree(self):
tree = RegressionTreeLearner()
# Make sure it trains and predicts properly
X, y = load_diabetes(return_X_y=True)
tree.fit(X, y)
# Make sure the prediction works
y_pred = tree.predict(X)
# Full depth tree should yield perfect accuracy
self.assertAlmostEqual(1, r2_score(y, y_pred))
# Constrain tree depth severely
tree.max_depth = 2
tree.fit(X, y)
y_pred = tree.predict(X)
self.assertAlmostEqual(0.433370098, r2_score(y, y_pred)) # Result is deterministic
# Constrain the tree to a single node, using minimum count per split
tree = RegressionTreeLearner(min_leaf_instances=1000)
tree.fit(X, y)
self.assertAlmostEqual(0, r2_score(y, tree.predict(X)))
def test_linear_regression(self):
lr = LinearRegression()
# Make y = x + 1
X, y = _make_linear_data()
# Fit a linear regression model
lr.fit(X, y)
self.assertEqual(1, r2_score(y, lr.predict(X)))
# Not fitting an intercept
lr.fit_intercept = False
lr.fit(X, y)
self.assertAlmostEqual(0, lr.predict([[0]])[0])
# Add a regularization parameter, make sure the model fits
lr.reg_param = 1
lr.fit(X, y)
def test_adjust_rtree_learners(self):
"""Test modifying the bias and leaf learners of decision trees"""
# Make a tree learner that will make only 1 split on 32 data points
tree = RegressionTreeLearner(min_leaf_instances=16)
# Make y = x + 1
X, y = _make_linear_data()
# Fit the model
tree.fit(X, y)
self.assertEqual(2, len(set(tree.predict(X)))) # Only one split
# Use linear regression on the splits
tree.leaf_learner = LinearRegression()
tree.fit(X, y)
self.assertAlmostEqual(1.0, r2_score(y, tree.predict(X))) # Linear leaves means perfect fit
# Test whether changing leaf learner does something
rf = RandomForestRegressor(leaf_learner=LinearRegression(), min_leaf_instances=16)
rf.fit(X[:16, :], y[:16], random_seed=23478) # Train only on a subset
self.assertAlmostEqual(1.0, r2_score(y, rf.predict(X))) # Should fit perfectly on whole dataset
rf = RandomForestRegressor()
rf.fit(X[:16, :], y[:16], random_seed=7834)
self.assertLess(r2_score(y, rf.predict(X)), 1.0) # Should not fit the whole dataset perfectly
class TestExtraRandomTrees(TestCase):
def test_extra_random_trees_regressor(self):
# Setting disable_bootstrap=False allows us to generate uncertainty estimates from the bagged ensemble
rf = ExtraRandomTreesRegressor(disable_bootstrap=False)
# Train the model
X, y = load_diabetes(return_X_y=True)
# Make sure we get a NotFittedError
with self.assertRaises(NotFittedError):
rf.predict(X)
# Fit the model
rf.fit(X, y, random_seed=378456)
# Run some predictions
y_pred = rf.predict(X)
self.assertEqual(len(y_pred), len(y))
# Test the ability to get importance scores
y_import = rf.get_importance_scores(X[:100, :])
self.assertEqual((100, len(X)), y_import.shape)
# Basic test for functionality. R^2 above 0.88 was measured on 2021-12-09
score = r2_score(y_pred, y)
print("R2: ", score)
self.assertGreater(score, 0.88)
# Test with weights (make sure it doesn't crash)
rf.fit(X, y, [2.0]*len(y))
# Make sure feature importances are stored
self.assertEqual(np.shape(rf.feature_importances_), (X.shape[1],))
self.assertAlmostEqual(1.0, np.sum(rf.feature_importances_))
# Run predictions with std dev
# Requires disable_bootstrap=False on the learner to generate std dev alongside predictions
y_pred, y_std = rf.predict(X, return_std=True)
self.assertEqual(len(y_pred), len(y_std))
self.assertTrue((y_std >= 0).all()) # They must be positive
self.assertGreater(np.std(y_std), 0) # Must have a variety of values
# Make sure the detach operation functions
rf.clear_model()
self.assertIsNone(rf.model_)
def test_reproducibility(self):
seed = 378456
rf1 = ExtraRandomTreesRegressor()
rf2 = ExtraRandomTreesRegressor()
X, y = load_diabetes(return_X_y=True)
rf1.fit(X, y, random_seed=seed)
rf2.fit(X, y, random_seed=seed)
pred1 = rf1.predict(X)
pred2 = rf2.predict(X)
self.assertTrue((pred1 == pred2).all())
def test_extra_random_trees_classifier(self):
rf = ExtraRandomTreesClassifier()
# Load in the iris dataset
X, y = load_iris(return_X_y=True)
rf.fit(X, y, random_seed=378456)
# Predict the probability of membership in each class
y_prob = rf.predict_proba(X)
self.assertEqual((len(X), 3), np.shape(y_prob))
self.assertAlmostEqual(len(X), np.sum(y_prob))
ll_score = log_loss(y, y_prob)
print('Log loss:', ll_score)
self.assertLess(ll_score, 0.03) # Measured at 0.026 on 2020-04-06
# Test just getting the predicted class
y_pred = rf.predict(X)
self.assertTrue(np.isclose(np.argmax(y_prob, 1), y_pred).all())
self.assertEqual(len(X), len(y_pred))
acc = accuracy_score(y, y_pred)
print('Accuracy:', acc)
self.assertAlmostEqual(acc, 1) # Given default settings, we should get perfect fitness to training data
def test_serialization(self):
rf = ExtraRandomTreesClassifier()
# Make sure this doesn't error without a model training
data = pkl.dumps(rf)
rf2 = pkl.loads(data)
# Load in the iris dataset and train model
X, y = load_iris(return_X_y=True)
rf.fit(X, y, random_seed=378945)
# Try saving and loading the model
data = pkl.dumps(rf)
rf2 = pkl.loads(data)
# Make sure it yields the same predictions as the first model
probs1 = rf.predict_proba(X)
probs2 = rf2.predict_proba(X)
self.assertTrue(np.isclose(probs1, probs2).all())
if __name__ == "__main__":
main()
| 11,873 | 33.923529 | 121 | py |
lolo | lolo-main/python/lolopy/tests/test_server.py | from lolopy.loloserver import get_java_gateway
from py4j.java_gateway import java_import, JavaClass
from unittest import TestCase
import os
class TestLoloGateway(TestCase):
def test_launch(self):
# Launch the gateway
gate = get_java_gateway()
# Make sure it runs by making a random number
rnd = gate.jvm.java.util.Random()
self.assertIsInstance(rnd.nextInt(), int)
# Make sure importing Lolo works
java_import(gate.jvm, "io.citrine.lolo.learners.*")
self.assertIsInstance(gate.jvm.RandomForest, JavaClass)
# Make sure requsting a gateway againt returns the same gateway
gate2 = get_java_gateway()
self.assertIs(gate, gate2)
# Test getting a new gateway if needed
gate3 = get_java_gateway(reuse=False)
self.assertIsNot(gate, gate3)
# Make the server using the package version of lolo
gate4 = get_java_gateway(reuse=False, skip_devel_version=True)
java_import(gate4.jvm, "io.citrine.lolo.learners.*")
self.assertIsInstance(gate4.jvm.RandomForest, JavaClass)
def test_memory(self):
# Set an environmental variable (local for this test)
os.environ['LOLOPY_JVM_MEMORY'] ='4g'
with self.assertLogs("py4j.java_gateway", level='DEBUG') as cm:
# Get a gateway
get_java_gateway(reuse=False)
# Make sure the memory amount appears in the logs
self.assertIn('Xmx4g', '\n'.join(cm.output))
| 1,512 | 32.622222 | 71 | py |
lolo | lolo-main/python/lolopy/tests/test_metrics.py | from lolopy.loloserver import get_java_gateway
from lolopy.metrics import (root_mean_squared_error, standard_confidence, standard_error, uncertainty_correlation)
from numpy.random import multivariate_normal, uniform, normal, seed
from unittest import TestCase
class TestMetrics(TestCase):
def test_rmse(self):
self.assertAlmostEqual(root_mean_squared_error([1, 2], [1, 2]), 0)
self.assertAlmostEqual(root_mean_squared_error([4, 5], [1, 2]), 3)
def test_standard_confidene(self):
self.assertAlmostEqual(standard_confidence([1, 2], [2, 3], [1.5, 0.9]), 0.5)
self.assertAlmostEqual(standard_confidence([1, 2], [2, 3], [1.5, 1.1]), 1)
def test_standard_error(self):
self.assertAlmostEqual(standard_error([1, 2], [1, 2], [1, 1]), 0)
self.assertAlmostEqual(standard_error([4, 5], [1, 2], [3, 3]), 1)
def test_uncertainty_correlation(self):
seed(3893789455)
sample_size = 2 ** 15
random_seed = 783245
for expected in [0, 0.75]:
# Make the error distribution
y_true = uniform(0, 1, sample_size)
# Make the errors and uncertainties
draw = multivariate_normal([0, 0], [[1, expected], [expected, 1]], sample_size)
# Add the errors, and separate out the standard deviations
y_pred = y_true + [d[0] * normal(0, 1) for d in draw]
y_std = [abs(d[1]) for d in draw]
# Test with a very large tolerance for now
measured_corr = uncertainty_correlation(y_true, y_pred, y_std, random_seed=random_seed)
corr_error = abs(measured_corr - expected)
self.assertLess(corr_error, 0.25, 'Error for {:.2f}: {:.2f}'.format(expected, corr_error))
| 1,752 | 42.825 | 114 | py |
pyasn | pyasn-master/setup.py | from __future__ import print_function
import codecs
import sys
import platform
import glob
from setuptools import setup, find_packages, Extension
from os.path import abspath, dirname, join
here = abspath(dirname(__file__))
with codecs.open(join(here, 'README.md'), encoding='utf-8') as f:
README = f.read()
libs = ['Ws2_32'] if platform.system() == "Windows" else []
ext = Extension('pyasn.pyasn_radix',
sources=['pyasn/pyasn_radix.c', 'pyasn/_radix/radix.c'],
include_dirs=[join(here, 'pyasn')],
libraries=libs)
extra_kwargs = {'ext_modules': [ext]}
reqs = []
if sys.version_info[0] == 2 and sys.version_info[1] < 7:
reqs.append('ordereddict')
if sys.version_info[0] == 2:
reqs.append('backport-ipaddress')
utils = glob.glob('pyasn-utils/*.py')
__version__ = None
exec(open('pyasn/_version.py').read()) # load the actual __version__
setup(
name='pyasn',
version=__version__,
maintainer='Hadi Asghari',
maintainer_email='[email protected]',
url='https://github.com/hadiasghari/pyasn',
description='Offline IP address to Autonomous System Number lookup module.',
long_description=README,
license='MIT',
classifiers=[
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: System :: Networking',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
keywords='ip asn autonomous system bgp whois prefix radix python routing networking',
install_requires=reqs,
data_files=[],
scripts=utils,
setup_requires=[],
tests_require=['nose', 'coverage'],
packages=find_packages(exclude=['tests', 'tests.*']),
zip_safe=False,
test_suite='nose.collector',
**extra_kwargs
)
| 1,966 | 29.261538 | 89 | py |
pyasn | pyasn-master/pyasn/mrtx.py | # Copyright (c) 2009-2017 Hadi Asghari
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# This file parses the Multi-Threaded Routing Toolkit (MRT) Routing Information Export Format dumps
# Parts of this code are copied/based on the dpkt project, with their respective copyright
# (see: https://code.google.com/p/dpkt/)
"""pyasn.mrtx
Module to parse MRT/RIB BGP table dumps (in order to create the IPASN database).
Functions:
parse_mrt_file() -- main function
util_dump_prefixes_to_textfile()
Other objects:
MRT* and pyasn.mrtx.BGP* classes: internally used to hold and parse the MRT dumps.
"""
from __future__ import print_function, division
from socket import inet_ntoa, inet_aton, AF_INET, AF_INET6
from struct import unpack, pack
from time import time, asctime
from sys import stderr, version_info, stdout
from bz2 import BZ2File
from gzip import GzipFile
try:
from collections import OrderedDict
except ImportError:
# python 2.6 support - needs the ordereddict module
from ordereddict import OrderedDict
try:
from socket import inet_ntop
except ImportError:
# inet_ntop is only available on unix
pass
IS_PYTHON2 = (version_info[0] == 2)
def open_archive(fpath):
"""Open a bz2 or gzip archive."""
# Thanks to Chris poliquin for this method (https://github.com/poliquin)
mode = "rb"
GZIP_MAGIC, BZ2_MAGIC = b"\x1f\x8b", b"\x42\x5a\x68" # magic numbers
with open(fpath, mode) as fh:
hdr = fh.read(max(len(BZ2_MAGIC), len(GZIP_MAGIC)))
if hdr.startswith(BZ2_MAGIC):
return BZ2File(fpath, mode)
elif hdr.startswith(GZIP_MAGIC):
return GzipFile(fpath, mode)
else:
raise TypeError("Cannot determine file type '%s'" % fpath)
def parse_mrt_file(mrt_file,
print_progress=False,
skip_record_on_error=False):
"""parse_file(file, print_progress=False, skip_record_on_error=False):
Parses an MRT/RIB BGP table dump file.\n
in: file-object or string-path to a MRT/RIB archive (.gz/.bz2)
out: { "NETWORK/MASK" : ASN | set([Originating ASNs]) }
\n
The originating ASN is usually one; however, for some prefixes it can be a set.
\n
Both version 1 & 2 TABLE_DUMPS are supported, as well as 32bit ASNs and IPv6."""
prefixes, t0, n = OrderedDict(), time(), 0
if type(mrt_file) is str:
# callee passed a string-path, open it. file will close when this method ends.
# (we could alternatively try mrt_file.tell() to test if it's file-like.)
mrt_file = open_archive(mrt_file)
while True:
mrt = MrtRecord.next_dump_table_record(mrt_file)
if not mrt:
# EOF
break
if not mrt.detail \
or (mrt.type == mrt.TYPE_TABLE_DUMP_V2 and mrt.sub_type == MrtRecord.T2_PEER_INDEX):
# not a prefix/as-path entry
if print_progress:
print('Parsing MRT/RIB archive .. ', mrt, file=stderr)
continue
if mrt.prefix not in prefixes:
try:
origin = mrt.get_first_origin_as()
prefixes[mrt.prefix] = origin
except IndexError:
if skip_record_on_error:
if print_progress:
print(" WARNING: can't get_origin_as for prefix", mrt.prefix, file=stderr)
continue
else:
raise
except:
print(" Exception parsing prefix record", mrt.prefix, file=stderr)
raise # raise it again
else:
# Repeated prefix, WARN if different.
# In TD1, repeated prefixes were normal. We cared only about 'first-match'...
# In TD2, until recently (201701), the MRT/RIB files typically didn't repeat prefixes.
# Recently, repetitions have resurfaced (e.g. bug #39). Such prefixes typically map
# to the same AS-origin, but not always (I'm not sure why)
# Note, we check only for TDV2. On 20170102, 4 differ out of 600k prefixes.
# In TDv1, there were many many reptitions, bogging the conversion.
if mrt.type == mrt.TYPE_TABLE_DUMP_V2:
was = prefixes[mrt.prefix]
new = mrt.get_first_origin_as(ignore_exception=True)
if was != new and print_progress:
was = "{%d ASes}" % len(was) if type(was) is set else str(was)
new = "{%d ASes}" % len(new) if type(new) is set else str(new)
print(" WARNING: repeated prefix '%s' maps to different origin (%s vs %s)"
% (mrt.prefix, was, new), file=stderr)
#
n += 1
if print_progress and n % (100000 if mrt.type == mrt.TYPE_TABLE_DUMP_V2 else 500000) == 0:
print(" MRT record %d @%.fs" % (n, time() - t0), file=stderr)
#
if '0.0.0.0/0' in prefixes:
del prefixes['0.0.0.0/0'] # remove default route - can be parameter
if '::/0' in prefixes:
del prefixes['::/0'] # similarly for IPv6
return prefixes
def dump_screen_mrt_file(mrt_file, record_from=None, record_to=None, screen=stderr):
"""
Parses and dumps an MRT/RIB archive to screen. For debugging purposes.
"""
if type(mrt_file) is str:
mrt_file = open_archive(mrt_file)
print("Dumping MRT/RIB archive to screen:", file=screen)
n = 0
while True:
mrt = MrtRecord.next_dump_table_record(mrt_file, optimize_parse=False)
if not mrt:
break # EOF
if mrt.type not in (mrt.TYPE_TABLE_DUMP, mrt.TYPE_TABLE_DUMP_V2):
print("ERROR: dump_screen_mrt_file() supports only TDv1/TDv2 (type 12/13). Encountered"
" type %d, quitting.\n" % (mrt.TYPE_TABLE_DUMP_V2, mrt.type), file=screen)
break
n += 1
if record_from and n < record_from:
continue
if record_to and n > record_to:
break
print('\nRecord #%06d:' % n, mrt, file=screen)
if mrt.type == mrt.TYPE_TABLE_DUMP_V2 \
and mrt.sub_type in (MrtRecord.T2_RIB_IPV4, MrtRecord.T2_RIB_IPV6):
for i, entry in enumerate(mrt.detail.entries):
for j, attr in enumerate(entry.attrs):
print("\t", "Entry %02d" % (i+1) if j == 0 else ' '*8, attr, file=screen)
origin = mrt.get_first_origin_as(ignore_exception=True)
print("\t => pyasn choice: AS", origin, file=screen)
if mrt.type == mrt.TYPE_TABLE_DUMP:
for i, attr in enumerate(mrt.detail.attrs):
print("\t\t", attr, file=screen)
# FIXIME: pyasn's choice origin should only be shown for first of repeated prefixes
# origin = mrt.get_first_origin_as(ignore_exception=True)
# print("\t => pyasn choice: AS", origin, file=stderr)
def dump_prefixes_to_file(prefixes,
ipasn_file_name,
source_description="",
debug_write_sets=False
):
if IS_PYTHON2:
fw = open(ipasn_file_name, 'wt')
else:
fw = open(ipasn_file_name, 'wt', encoding='ASCII')
fw.write('; IP-ASN32-DAT file\n; Original source: %s\n' % source_description)
n6 = sum(1 for x in prefixes if ':' in x)
n4 = len(prefixes) - n6
fw.write('; Converted on : %s\n; Prefixes-v4 : %s\n; Prefixes-v6 : %s\n; \n' %
(asctime(), n4, n6))
for prefix, origin in prefixes.items():
if not debug_write_sets and isinstance(origin, set):
origin = list(origin)[0] # get an AS randomly, or the only AS if one, from the set
fw.write('%s\t%s\n' % (prefix, origin))
fw.close()
def dump_prefixes_to_text_file(ipasn_data,
out_text_file_name,
orig_mrt_name,
debug_write_sets=False
):
# NAME changed, this is for compatibility with scripts, use dump_prefixes_to_file() instead.
dump_prefixes_to_file(ipasn_data, out_text_file_name, orig_mrt_name, debug_write_sets)
# dump_prefixes_to_binary_file():
# DEPRECATED because our binary format lacked IPv6 support, and its loader wasn't fully tested.
# In place, pyasn_util_convert has '--compress' now, and pyasn can load gzipped IPASN files.
def is_asn_bogus(asn):
"""Returns True if the ASN is in the private-use or reserved list of ASNs"""
# References:
# IANA: http://www.iana.org/assignments/as-numbers/as-numbers.xhtml
# RFCs: rfc1930, rfc6996, rfc7300, rfc5398
# Cymru: http://www.team-cymru.org/Services/Bogons/,
# http://www.cymru.com/BGP/asnbogusrep.html
# WHOIS: https://github.com/rfc1036/whois -- in the program source
# CIDR-Report: http://www.cidr-report.org/as2.0/reserved-ases.html
# Note that the full list of unallocated and bogus ASNs is long, and changes; we use the basic
if asn <= 0:
return True
if 64496 <= asn <= 131071 or asn >= 4200000000: # reserved & private-use-AS
return True
if asn >= 1000000: # way above last allocated block (2014-11-02) -- might change in future
return True
return False
#####################################################################
# MRT headers, tables, and attributes sections
# MRT format spec at: http://tools.ietf.org/html/rfc6396
# BGP attribute spec at: http://tools.ietf.org/html/rfc4271
#
# Performance notes:
# -this code isn't super fast, but that's OK because it's run once to convert/parse the MRT files
# - it can be sped up perhaps by replacing some struct.unpacks(), profiling, or rewriting in C
# - it's not a full MRT parser; we ignore types/attributes we don't need
class MrtRecord:
"""Class for generic MRT Records. Implements common header, and methods for some sub-types"""
# We are interested in MRT-record types Table_Dump, Table_Dump_V2, and some sub-types
TYPE_TABLE_DUMP = 12
TYPE_TABLE_DUMP_V2 = 13
T1_AFI_IPv4 = 1
T1_AFI_IPv6 = 2
T2_PEER_INDEX = 1
T2_RIB_IPV4 = 2
T2_RIB_IPV6 = 4
def __init__(self, header):
self.ts, self.type, self.sub_type, self.data_len = unpack('>IHHI', header)
self.detail = None
@staticmethod
def next_dump_table_record(f, optimize_parse=True):
header_len = 12
buf = f.read(header_len) # read table-header
if not buf: # EOF
return None
mrt = MrtRecord(buf)
buf = f.read(mrt.data_len) # read table-data
assert len(buf) == mrt.data_len
if mrt.type == MrtRecord.TYPE_TABLE_DUMP:
assert mrt.sub_type in (MrtRecord.T1_AFI_IPv4, MrtRecord.T1_AFI_IPv6)
mrt.detail = MrtTD1Record(buf, mrt.sub_type, optimize_parse)
elif mrt.type == MrtRecord.TYPE_TABLE_DUMP_V2:
# only allow these types
assert mrt.sub_type in (MrtRecord.T2_PEER_INDEX,
MrtRecord.T2_RIB_IPV4,
MrtRecord.T2_RIB_IPV6)
mrt.detail = MrtTD2Record(buf, mrt.sub_type, optimize_parse)
else:
raise Exception("MrtTableHeader got an unknown MRT table dump TYPE <%d>!" % mrt.type)
return mrt
def __repr__(self):
if self.detail:
return repr(self.detail)
else:
return "MrtRecord(Unknown type:%d/:%d, ts:%d, data-len:%d, prefix:%s)" \
% (self.type, self.ts, self.sub_type, self.data_len, self.prefix)
return ret
@property
def prefix(self):
return self.detail.prefix if self.detail else None # CIDR/MASK string
def get_first_origin_as(self, ignore_exception=False):
# For TableDumpV2 we only use entry 0's attributes... (TD1 have single entry)
try:
path = None
attrs = self.detail.attrs if self.type == MrtRecord.TYPE_TABLE_DUMP else \
self.detail.entries[0].attrs
for a in attrs:
if a.bgp_type == BgpAttribute.ATTR_AS_PATH:
assert not path # only one as-path attribute in each entry
path = a.path_detail()
assert path
return path.get_origin_as()
except:
if not ignore_exception:
raise
else:
return "<exception>"
class MrtTD1Record:
"""MrtTD1Record: class to hold and parse MRT Table_Dumps records"""
def __init__(self, buf, sub_type, optimize_parse=True):
self.sub_type, self.seq, self.prefix, self.attr_len = sub_type, None, None, None
self.view, self.seq = unpack('>HH', buf[:4])
assert self.sub_type in (MrtRecord.T1_AFI_IPv4, MrtRecord.T1_AFI_IPv6)
octs = 4 if self.sub_type == MrtRecord.T1_AFI_IPv4 else 16
prefix = inet_ntoa(buf[4:4+octs]) if self.sub_type == MrtRecord.T1_AFI_IPv4 \
else inet_ntop(AF_INET6, buf[4:4+octs]) # FIXME: ntop() on Windows?
prefix_len, status, self.orig_ts = unpack('>BBI', buf[4+octs:10+octs])
assert status == 1 # status octet is unused in TDv1 and SHOULD be set to 1
# assert self.view == 0 # view is normally 0, used when having multiple RIB views
# we ignore peer-ip - it can be 4 or 16 octets.
self.peer_as, self.attr_len = unpack('>HH', buf[10+octs*2:14+octs*2])
self.prefix = "%s/%d" % (prefix, prefix_len)
self._attrs = []
self._data_buf = buf[14+octs*2:]
self._optimize = optimize_parse
@property
def attrs(self):
# The BGP Attribute fields contains information for the RIB entry (parsed on demand)
if not self._attrs:
buf = self._data_buf[:]
j = self.attr_len
while j > 0:
a = BgpAttribute(buf, is32=False)
self._attrs.append(a)
buf = buf[len(a):]
j -= len(a)
if a.bgp_type == BgpAttribute.ATTR_AS_PATH and self._optimize:
break # slight optimization: stop parsing other attributes after ASPATH
assert (not j and not buf) or self._optimize # make sure all data is used
return self._attrs
def __repr__(self):
ipv = "IPV4" if self.sub_type == MrtRecord.T1_AFI_IPv4 else "IPV6"
ret = "MrtTD1Record (%s %s, attributes %dB)" % (ipv, self.prefix, self.attr_len)
return ret
class MrtTD2Record:
"""MrtTD2Record: class to hold and parse MRT records form Table_Dumps_V2"""
# Main difference between MTD1 and MTD2 is support of 4-byte ASNs, BGP multiprotocol
# extensions, and that an MRT record can encode multiple table entries for one prefix.
def __init__(self, buf, sub_type, optimize_parse=True):
self.prefix, self.sub_type, self._optimize = None, sub_type, optimize_parse
if self.sub_type == MrtRecord.T2_PEER_INDEX:
# PEER_INDEX_TABLE provides BGP ID of the collector and list of peers
self.collector, vn_len = unpack('>IH', buf[0:6])
self.peer_count = unpack('>H', buf[6+vn_len:6+vn_len+2])[0]
elif self.sub_type in (MrtRecord.T2_RIB_IPV4, MrtRecord.T2_RIB_IPV6):
self.seq, mask = unpack('>IB', buf[0:5])
octets = (mask + 7) // 8
max_octs = 16 if sub_type == MrtRecord.T2_RIB_IPV6 else 4
padding = bytes(max_octs - octets) if not IS_PYTHON2 else '\0'*(max_octs - octets)
if sub_type == MrtRecord.T2_RIB_IPV4:
s = inet_ntoa(buf[5:5+octets] + padding) # ntoa() faster than IPAddress class
elif sub_type == MrtRecord.T2_RIB_IPV6:
s = inet_ntop(AF_INET6, buf[5:5+octets] + padding) # FIXME: ntop() on Windows?
self.prefix = s + "/%d" % mask
self.entry_count = unpack('>H', buf[5 + octets:7 + octets])[0]
buf = buf[7 + octets:]
self.entries = []
for i in range(self.entry_count):
e = self.T2RibEntry(buf, self._optimize)
self.entries.append(e)
if self._optimize:
break # parsing only first entry shaves 50% time
buf = buf[len(e):]
assert not buf or self._optimize # assert fully parsed
else:
# Unknown / unsupported sub-type
pass
def __repr__(self):
if self.sub_type in (MrtRecord.T2_RIB_IPV4, MrtRecord.T2_RIB_IPV6):
ipv = "IPV4" if self.sub_type == MrtRecord.T2_RIB_IPV4 else "IPV6"
more = "+" if self._optimize else ""
ret = "MrtTD2Record (%s-UNICAST %s, %d%s entries)" % (ipv, self.prefix,
len(self.entries), more)
elif self.sub_type == MrtRecord.T2_PEER_INDEX:
ret = "MrtTD2Record (PEER-INDEX-TABLE, collector %s, %d peers)" % (self.collector,
self.peer_count)
else:
ret = "MrtTD2Record (Unknown Subtype %d)" % self.sub_type
return ret
class T2RibEntry:
def __init__(self, buf, optimize):
self.peer, self.orig_ts, self.attr_len = unpack('>HIH', buf[:8])
self._data = buf[8: 8 + self.attr_len]
self._attrs = []
self._optimize = optimize
@property
def attrs(self):
if not self._attrs: # parse an entry's attrs on demand for performance
data = self._data
j = self.attr_len
while j > 0:
attr = BgpAttribute(data, is32=True)
data = data[len(attr):]
j -= len(attr)
self._attrs.append(attr)
if attr.bgp_type == BgpAttribute.ATTR_AS_PATH and self._optimize:
break # not parsing other attributes after ASPATH shaves 30% time
assert (not j and not data) or self._optimize # make sure all data is used
return self._attrs
def __len__(self):
return 8 + self.attr_len
def __repr__(self):
return 'T2RibEntry (attr_len:%d, peer:%d, orig_ts:%d)' % (self.attr_len,
self.peer, self.orig_ts)
class BgpAttribute:
# BGP attributes are defined here:
# http://tools.ietf.org/html/rfc4271 (Section 5)
# https://www.iana.org/assignments/bgp-parameters/bgp-parameters.xhtml
# They are part of BGP UPDATE messages.
# We are mainly interested in parsing the AS_PATH attribute.
ATTR_AS_PATH = 2
ATTR_NAMES = ("TYPE-0", "ORIGIN", "AS_PATH", "NEXT_HOP", "MULTI_EXIT_DISC", "LOCAL_PREF",
"ATOMIC_AGGREGATE", "AGGREGATOR", "COMMUNITIES", "ORIGINATOR_ID",
"CLUSTER_LIST", "TYPE-11", "TYPE-12", "TYPE-13", "MP_REACH_NLRI",
"MP_UNREACH_NLRI", "EXTENDED COMMUNITIES", "AS4_PATH", "AS4_AGGREGATOR")
def _has_ext_len(self):
ext_len = (self.flags >> 4) & 0x1
return ext_len
def __init__(self, buf, is32):
self.flags = buf[0] if not IS_PYTHON2 else ord(buf[0])
self.bgp_type = buf[1] if not IS_PYTHON2 else ord(buf[1])
self._is32 = is32
self._detail = None
if self._has_ext_len():
_len = unpack('>H', buf[2:4])[0]
self.data = buf[4:4 + _len]
else:
_len = buf[2] if not IS_PYTHON2 else ord(buf[2])
self.data = buf[3:3 + _len]
def __len__(self):
return 2 + (2 if self._has_ext_len() else 1) + len(self.data)
def __repr__(self):
t = self.bgp_type
ret = "BGPAttribute({}): ".format((self.ATTR_NAMES[t] if 0 <= t <= 18 else "TYPE-%d" % t))
if t == self.ATTR_AS_PATH:
ret += str(self.path_detail())
elif 0 < len(self.data) <= 4:
l = len(self.data)
v = unpack('>'+'BHI'[l//2], self.data)[0]
ret += str(v)
else:
ret += "%d bytes" % len(self.data)
return ret
def path_detail(self):
assert self.bgp_type == self.ATTR_AS_PATH
if not self._detail: # lazy conversion on request; speeds up TD1 parse by 20%
self._detail = self.BgpAttrASPath(self.data, self._is32)
return self._detail
class BgpAttrASPath:
# An AS_PATH has routing path information represented as ordered AS_SEQUENCEs
# and unordered AS_SETs.
def __init__(self, buf, is32):
self.pathsegs = []
while buf:
seg = self.BgpPathSegment(buf, is32)
buf = buf[len(seg):]
self.pathsegs.append(seg)
def __repr__(self):
return "path-%s" % ", ".join(str(path) for path in self.pathsegs)
def get_origin_as(self):
"""Returns the originating AS for this prefix - an integer if clear,
a set of integers not fully unclear"""
# important change from pyasn_converter 1.2"
# in 1.2, we had a bug that ignored origins of as_paths ending in as_set,
# as well as origins of as_paths with more than three segments,
# and these prefixes (129 out of the total 513000 for 2014-05-23) weren't saved
# To identify the originating AS for a prefix, this is how path-segments work:
#
# RFC 4271 on how AS_PATH is created
# - when a BGP speaker advertises route to an internal peer, it shall not modify the
# AS_PATH
# - when a BGP speaker advertises the route to an external peer, it updates AS_PATH
# attribute as follows:
# - if first path segment of AS_PATH is AS_SEQUENCE, the local system prepends its
# own ASN (leftmost)
# if more than 255 ASes already, prepends a new AS_SEQUENCE segment
# - if first path segment is AS_SET, its prepends a new AS_SEQUENCE segment to the
# AS_PATH,
# including its own AS number in that segment.
# - if AS_PATH is empty, it creates a AS_SEQUENCE segment, places its own AS into it
# and it into AS_PATH
# - When a BGP speaker originates a route:
# - the speaker includes its own ASN in a path segment of type AS_SEQUENCE, in the
# AS_PATH attribute of
# UPDATE messages sent to external peers. (i.e., its ASN will be sole entry)
# - the originating speaker includes an empty AS_PATH attribute in UPDATE messages
# sent to internal peers.
#
# So none of the above uses AS_SET; AS_SET is used in aggregate messages.
# - When a speaker aggregates several routes for advertisement to a particular peer,
# the AS_PATH of the aggregated route normally includes an AS_SET from the set of
# ASes the was aggregate was formed.
# - Caveat: AS_SETs, used in route aggregation to reduce the size of the AS_PATH info
# by listing each ASN only once (regardless of times it appeared in multiple
# AS_PATHs), can cause some inaccuracies.
# The destinations listed can be reached through paths that traverse at least some
# constituent ASes.
# AS_SETs are sufficient to avoid routing loops; however, they may prune feasible
# paths. In practice, is not a problem because once an IP packet arrives at the edge
# of a group of ASes, the BGP speaker is likely to have more detailed path
# information.
# CONCLUSION:
# i- go to the last path segment, among the many.
# ii- if it's a sequence, return the last AS;
# if it's a set, return all ASes; callee can choose any
# updated 2014/11: changes so as not to return as bogus AS the origin
# sequence & sets can interleave; but at least one sequence will be a set
assert self.pathsegs[0].seg_type == self.BgpPathSegment.AS_SEQUENCE
origin = None
for last_seg in reversed(self.pathsegs):
if last_seg.seg_type == self.BgpPathSegment.AS_SEQUENCE:
# for sequence, return last AS as origin; if that's bogus, use preceding
for asn in reversed(last_seg.path):
if not is_asn_bogus(asn):
origin = int(asn)
break
elif last_seg.seg_type == self.BgpPathSegment.AS_SET:
# for sets: return all non-bogus routes; the callee can choose any
origin = set(asn for asn in last_seg.path if not is_asn_bogus(asn))
else:
raise Exception("Invalid/Legacy BGP Path Segment: %d" % last_seg.seg_type)
# will break here, except in rare cases where all of seq/set are bogus. then repeat
if origin:
break
assert origin # eventually, should not be 0 (no asn 0), or None, or an empty set
return origin
class BgpPathSegment:
AS_SET = 1 # unordered set of ASes a route in the UPDATE message has traversed
AS_SEQUENCE = 2 # ordered set of ASes a route in the UPDATE message has traversed
AS_CONFED_SEQUENCE = 3 # legacy, rare, harmelss, checked in .origin_as() (bug #13)
AS_CONFED_SET = 4
# stats on 100,000: {1: 1196, 2: 3677845}.
def __init__(self, data, is32):
self.seg_type = data[0] if not IS_PYTHON2 else ord(data[0])
cnt = data[1] if not IS_PYTHON2 else ord(data[1])
data = data[2:]
assert self.seg_type in (self.AS_SET,
self.AS_SEQUENCE,
self.AS_CONFED_SEQUENCE,
self.AS_CONFED_SET)
self.path = []
self.as_len = 4 if is32 else 2
for i in range(cnt):
asn = unpack('>I' if is32 else '>H', data[:self.as_len])[0]
# assert asn > 0
# moved to origin_as() method to ignore strange asns in the middle of as-path.
# e.g. in rib.20141014.0600.bz2, 193.104.137.128/25 has [20912, 0, 50112].
# won't effect the origin
data = data[self.as_len:]
self.path.append(asn)
def __len__(self):
return 2 + self.as_len * len(self.path)
def __str__(self):
# for path-sequences: sequence[as1, as2, as3], for set[as1, as2, as3]
assert self.seg_type in (self.AS_SET, self.AS_SEQUENCE)
s = 'sequence' if self.seg_type == self.AS_SEQUENCE else 'set'
s += str(self.path)
return s
def __repr__(self):
return "BgpPathSegment-" + str(self)
| 28,342 | 44.640902 | 99 | py |
pyasn | pyasn-master/pyasn/_version.py | __version__ = '1.6.2'
| 22 | 10.5 | 21 | py |
pyasn | pyasn-master/pyasn/__init__.py | # Copyright (c) 2014-2017 Hadi Asghari
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import print_function, division
import codecs
import gzip
import pickle
import re
from collections import defaultdict
from os import path
from ipaddress import collapse_addresses, ip_network
from ._version import __version__
from .pyasn_radix import Radix
try:
import ujson as json
except ImportError:
import json
class pyasn(object):
"""
Class to do fast offline & historical Autonomous-System-Number lookups for IPv4/IPv6 addresses.
"""
def __init__(self, ipasn_file, as_names_file=None, ipasn_string=None):
"""
Creates a new instance of pyasn.\n
:param ipasn_file:
Filename of the IP-ASN database to load
(The database can be a simple text file with lines of "NETWORK/BITS\tASN".
You can create database files from BGP MRT/RBI dumps using the pyasn-utils
scripts provided alongside the pyasn package. Alternatively, you can download
prebuilt database from the pyasn homepage.)
:param as_names_file:
if given, loads autonomous system names from this file (warning: not fully tested)
:param ipasn_string:
String containing an IP-ASN database to load.
Only used if ipasn_file is None.
(The database is in the same format as ipasn_file.)
"""
self.radix = Radix()
# we use functionality provided by the underlying RADIX class (implemented in C for speed)
# actions such as add/delete node can be run on the radix tree if needed -- why its exposed
self._ipasndb_file = ipasn_file
self._asnames_file = as_names_file
if ipasn_file is not None and ipasn_file.endswith(".gz"):
# Support for compressed IPASN files added 2017-01-05
f = gzip.open(ipasn_file, 'rt') # Py2.6 doesn't support 'with' for gzip
ipasn_str = f.read()
f.close()
# performance note: ipasn_str = subprocess.check_output(['gunzip', '-c', ip_asn_file])
# is faster, but less portable, hence our choice. we could do hybrid.
self._records = self.radix.load_ipasndb("", ipasn_str)
elif ipasn_file is not None:
self._records = self.radix.load_ipasndb(ipasn_file, "")
elif ipasn_string is not None:
self._records = self.radix.load_ipasndb("", ipasn_string)
else:
raise ValueError("No data given, all parameters are empty.")
self._asnames = self._read_asnames() if as_names_file else None
self._as_prefixes = None
def _read_asnames(self):
"""
Reads autonomous system names (warning: this method is not fully tested)
"""
# todo: test a variety of formats for fastest performance in loading & disc size
# - json or csv-file with ASN & AS-NAMES
# - gzip of above
# - "anydbm" or pickle (pickle gets a bit ugly with unicode)
if self._asnames_file.endswith('.gz'):
f = gzip.open(self._asnames_file, 'rt') # Py2.6 doesn't support 'with' for gzip
raw_data = f.read()
f.close()
asnames_file = self._asnames_file.strip('.gz')
ftype = asnames_file.split('.')[-1]
if ftype not in ['json']:
# Easy to add + validate new extension-checks
raise ValueError("Invalid filetype under the commpressed as-names file: {}; must be: "
"['.json']")
if ftype == 'json':
names = json.loads(raw_data)
elif self._asnames_file.endswith('.json'):
with codecs.open(self._asnames_file, 'r', encoding='utf-8') as fs:
names = json.load(fs)
else:
ext = path.splitext(self._asnames_file)[-1]
raise NotImplementedError('Autonomous system names parser does not support %s format.' % ext)
try:
formatted_names = dict([(int(k), v) for k, v in names.items()])
except ValueError:
raise Exception("Autonomous system names file contains non-nummeric ASNs")
return formatted_names
def lookup(self, ip_address):
"""
Returns the as number and best matching prefix for given ip address.\n
:param ip_address: String representation of ip address , for example "8.8.8.8".
:raises: ValueError if an invalid IP address is passed.
:return: (asn, prefix) of a given IP address.\n
'asn' is the 32-bit AS Number that holds this IP address, as advertised on BGP.\n
'prefix' is the best matching prefix in the BGP table for the given IP address.\n
Returns (None, None) if the IP address is not found (=not advertised, unreachable)
"""
rn = self.radix.search_best(ip_address)
return (rn.asn, rn.prefix) if rn else (None, None)
def get_as_prefixes(self, asn):
""" :return: All prefixes advertised by given ASN """
if not self._as_prefixes:
# build full dictionary of {asn: set(prefixes)}, and cache it for subsequent calls
self._as_prefixes = defaultdict(set)
for px in self.radix.prefixes():
ip, mask = px.split('/') # fine with IPv4/IPv6
rn = self.radix.search_exact(ip, masklen=int(mask))
# we walk the radix-tree by going through all prefixes. it is very important to
# use 'search-exact' in the process, with the correct mask (to avoid bug #10)
self._as_prefixes[rn.asn].add(px)
#
return self._as_prefixes[int(asn)] if int(asn) in self._as_prefixes else None
def get_as_prefixes_effective(self, asn):
"""
Returns the effective address space of given ASN by removing all overlaps among prefixes
:return: The effective prefixes resulting from removing overlaps of given ASN's prefixes
"""
prefixes = self.get_as_prefixes(asn)
if not prefixes: # issue 12
return None
non_overlapping_4 = collapse_addresses([ip_network(i) for i in prefixes if ':' not in i])
non_overlapping_6 = collapse_addresses([ip_network(i) for i in prefixes if ':' in i])
return [i.compressed for i in non_overlapping_4] + \
[i.compressed for i in non_overlapping_6]
def get_as_size(self, asn):
"""
Returns the size of an AS as the total count of IP addresses that the AS is responsible for
:param asn: The autonomous system number
:return: number of unique IP addresses routed by AS
"""
prefixes = self.get_as_prefixes_effective(asn)
if not prefixes:
return 0
size = sum([2 ** (32 - int(px.split('/')[1])) for px in prefixes])
return size
def get_as_name(self, asn):
"""
Under construction, do not use!\n
:param asn: 32-bit ASN
:return: the AS-Name associated with this ASN
"""
if not self._asnames:
raise Exception("Autonomous system names not loaded during initialization")
return self._asnames.get(asn, None)
def __repr__(self):
ret = "pyasn(ipasndb:'%s'; asnames:'%s') - %d prefixes" % (self._ipasndb_file,
self._asnames_file,
self._records)
return ret
# Persistence support, for use with pickle.dump(), pickle.load()
# todo: add a test also for persistence support
def __iter__(self):
for elt in self.radix:
yield elt
def __getstate__(self):
d = self.__dict__.copy()
del d['radix']
s = ""
for elt in self:
s += "{}\t{}\n".format(elt.prefix, elt.asn)
d["ipasn_str"] = s
return d
def __setstate__(self, state):
ipasn_str = state['ipasn_str']
del state['ipasn_str']
self.__dict__.update(state)
self.radix = Radix()
records = self.radix.load_ipasndb("", ipasn_str)
assert records == self._records # sanity
@staticmethod
def convert_32bit_to_asdot_asn_format(asn): # FIXME: simplify to 'convert_32bit_asn_to_asdot'
"""
Converts a 32bit AS number into the ASDOT format AS[Number].[Number] - see rfc5396.\n
:param asn: The number of an AS in numerical format.
:return: The AS number in AS[Number].[Number] format.
"""
div, mod = divmod(asn, 2**16)
return "AS%d.%d" % (div, mod) if div > 0 else "AS%d" % mod
@staticmethod
def convert_asdot_to_32bit_asn(asdot):
"""
Converts a asdot representation of an AS to a 32bit AS number - see rfc5396.\n
:param asdot: "AS[Number].[Number]" representation of an autonomous system
:return: 32bit AS number
"""
pattern = re.compile("^[AS]|[as]|[aS]|[As]][0-9]*(\.)?[0-9]+")
match = pattern.match(asdot)
if not match:
raise ValueError("Invalid asdot format for input. input format must be something like"
" AS<Number> or AS<Number>.<Number> ")
if asdot.find(".") > 0: # asdot input is of the format AS[d+].<d+> for example AS1.234
s1, s2 = asdot.split(".")
i1 = int(s1[2:])
i2 = int(s2)
asn = 2**16 * i1 + i2
else:
asn = int(asdot[2:]) # asdot input is of the format AS[d+] for example AS123
return asn
| 10,702 | 42.864754 | 105 | py |
pyasn | pyasn-master/tests/test_simple.py | # Copyright (c) 2014-2017 Hadi Asghari
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import codecs
import json
import logging
import os
import pickle
from unittest import TestCase
from pyasn import pyasn, pyasn_radix
FAKE_IPASN_DB_PATH = os.path.join(os.path.dirname(__file__), "../data/ipasn.fake")
IPASN_DB_PATH = os.path.join(os.path.dirname(__file__), "../data/ipasn_20140513.dat.gz")
IPASN6_DB_PATH = os.path.join(os.path.dirname(__file__), "../data/ipasn6_20151101.dat.gz")
AS_NAMES_FILE_PATH = os.path.join(os.path.dirname(__file__), "../data/asnames.json")
AS_NAMES_COMPRESSED_FILE_PATH = os.path.join(os.path.dirname(__file__), "../data/asnames.json.gz")
logger = logging.getLogger()
class TestSimple(TestCase):
# Tests loading radix file; a few IPs from TUD raneg; ASN32 (asdots) formats.
# TODO: write test cases for .get_as_prefixes_effective()
asndb = pyasn(IPASN_DB_PATH)
asndb_fake = pyasn(FAKE_IPASN_DB_PATH)
def test_consistency(self):
"""
Tests if pyasn is consistently loaded and that it returns a consistent answer
"""
db = pyasn(IPASN_DB_PATH)
asn, prefix = db.lookup('8.8.8.8')
for i in range(100):
tmp_asn, tmp_prefix = self.asndb.lookup('8.8.8.8')
self.assertEqual(asn, tmp_asn)
self.assertEqual(prefix, tmp_prefix)
def test_correctness(self):
"""
Tests if pyasn returns the correct AS number with simple data base
"""
for i in range(4):
asn, prefix = self.asndb_fake.lookup("1.0.0.%d" % i)
self.assertEqual(1, asn)
self.assertEqual("1.0.0.0/30", prefix)
for i in range(4, 256):
asn, prefix = self.asndb_fake.lookup("1.0.0.%d" % i)
self.assertEqual(2, asn)
self.assertEqual("1.0.0.0/24", prefix)
for i in range(256):
asn, prefix = self.asndb_fake.lookup("2.0.0.%d" % i)
self.assertEqual(3, asn)
self.assertEqual("2.0.0.0/24", prefix)
for i in range(128, 256):
asn, prefix = self.asndb_fake.lookup("3.%d.0.0" % i)
self.assertEqual(4, asn)
self.assertEqual("3.0.0.0/8", prefix)
for i in range(0, 128):
asn, prefix = self.asndb_fake.lookup("3.%d.0.0" % i)
self.assertEqual(5, asn)
self.assertEqual("3.0.0.0/9", prefix)
asn, prefix = self.asndb_fake.lookup("5.0.0.0")
self.assertEqual(None, asn)
self.assertEqual(None, prefix)
# todo: check that self.ipdb.lookup_asn('300.3.4.4') raises expcetion
def test_as_number_convert(self):
"""
Tests for correct conversion between 32-bit and ASDOT number formats for ASNs
"""
self.assertEqual("AS1.5698", pyasn.convert_32bit_to_asdot_asn_format(71234))
self.assertEqual("AS2.321", pyasn.convert_32bit_to_asdot_asn_format(131393))
self.assertEqual("AS65535.0", pyasn.convert_32bit_to_asdot_asn_format(4294901760))
self.assertEqual("AS65535.65535", pyasn.convert_32bit_to_asdot_asn_format(4294967295))
self.assertEqual("AS0", pyasn.convert_32bit_to_asdot_asn_format(0))
self.assertEqual(65536, pyasn.convert_asdot_to_32bit_asn("AS1.0"))
self.assertEqual(71234, pyasn.convert_asdot_to_32bit_asn("AS1.5698"))
self.assertEqual(4294967295, pyasn.convert_asdot_to_32bit_asn("AS65535.65535"))
self.assertEqual(0, pyasn.convert_asdot_to_32bit_asn("AS0"))
self.assertEqual(131393, pyasn.convert_asdot_to_32bit_asn("AS2.321"))
def test_get_tud_prefixes(self):
"""
Tests if correct prefixes are returned for a predetermined AS
"""
prefixes1 = self.asndb.get_as_prefixes(1128)
prefixes2 = self.asndb.get_as_prefixes(1128)
prefixes3 = self.asndb.get_as_prefixes('1128')
self.assertEqual(set(prefixes1),
set(['130.161.0.0/16', '131.180.0.0/16', '145.94.0.0/16']))
self.assertEqual(prefixes1, prefixes2) # should cache, and hence return same
self.assertEqual(prefixes1, prefixes3) # string & int for asn should return the same
def test_get_prefixes2(self):
"""
Tests get_as_prefixes() on a border case (bug report #10)
"""
# why this border-case is interesting:
# $ cat ipasn_20141028.dat | grep 13289$
# 82.212.192.0/18 13289
# $ cat ipasn_20141028.dat | grep 82.212.192.0
# 82.212.192.0/18 13289
# 82.212.192.0/19 29624
prefixes = self.asndb.get_as_prefixes(13289)
self.assertEqual(set(prefixes), set(['82.212.192.0/18']))
prefixes = self.asndb.get_as_prefixes(11018)
self.assertEqual(set(prefixes), set(['216.69.64.0/19']))
def test_get_tud_effective_prefixes(self):
prefixes1 = self.asndb.get_as_prefixes_effective(1128) # TUDelft AS
self.assertEqual(set(prefixes1),
set(['130.161.0.0/16', '131.180.0.0/16', '145.94.0.0/16']))
def test_address_family(self):
"""
Tests if pyasn can determine correct and incorrect IPv4/IPv6 addresses (bug #14)
"""
# the following should not raise
asn, prefix = self.asndb.lookup('8.8.8.8')
asn, prefix = self.asndb.lookup('2001:500:88:200::8')
# the following should raise
# note: assertRaisesRegexp doesn't exist on Py 2.6, so we're not checking the exp message
self.assertRaises(ValueError, self.asndb.lookup, '8.8.8.800')
self.assertRaises(ValueError, self.asndb.lookup, '2001:500g:88:200::8')
def test_ipv6(self):
"""
Tests if IPv6 addresseses are lookedup correctly
"""
db = pyasn(IPASN6_DB_PATH)
known_ips = [
# First three IPs sugested by sebix (bug #14). Confirmed AS on WHOIS
('2001:41d0:2:7a6::1', 16276), # OVH IPv6, AS16276
('2002:2d22:b585::2d22:b585', 6939), # WHOIS states: IPv4 endpoint(45.34.181.133) of
# a 6to4 address. AS6939 = Hurricane Electric
('2a02:2770:11:0:21a:4aff:fef0:e779', 196752), # TILAA, AS196752
('2607:f8b0:4006:80f::200e', 15169), # GOOGLE AAAA
('d::d', None), # Random unused IPv6
]
for ip, known_as in known_ips:
asn, prefix = db.lookup(ip)
self.assertEqual(asn, known_as)
def test_asnames(self):
"""
Test functionality of AS Name Lookup.
"""
db_with_names = pyasn(IPASN_DB_PATH, as_names_file=AS_NAMES_FILE_PATH)
asn, prefix = db_with_names.lookup('8.8.8.8')
name = db_with_names.get_as_name(asn)
self.assertTrue(name.lower().find("google") >= 0, "ASN Name Incorrect! Should be Google")
name = db_with_names.get_as_name(-1)
self.assertTrue(name is None, "ASN Name Incorrect! Should be None")
def test_asnames_compressed(self):
"""
Test functionality of AS Name Lookup with compressed files
"""
db_with_names = pyasn(IPASN_DB_PATH, as_names_file=AS_NAMES_COMPRESSED_FILE_PATH)
asn, prefix = db_with_names.lookup('8.8.8.8')
name = db_with_names.get_as_name(asn)
self.assertTrue(name.lower().find("google") >= 0, "ASN Name Incorrect! Should be Google")
name = db_with_names.get_as_name(-1)
self.assertTrue(name is None, "ASN Name Incorrect! Should be None")
def test_assize(self):
"""
Test AS Size calculation correctness
"""
size = sum([2 ** (32 - int(px.split('/')[1])) for px in []]) # Check empty prefix list
self.assertEqual(size, 0)
size = self.asndb.get_as_size(1133) # Uni Twente AS which has 1 /16 prefixes
self.assertEqual(size, 65536) # Manually Checked.
size = self.asndb.get_as_size(1128) # TU-Delft AS which has 3 non overlapping /16 prefixes
self.assertEqual(size, 196608) # Double checked with RIPE stat.
size = self.asndb.get_as_size(1124) # UVA AS has 3 non-overlapping prefixes (2 /16, 1 /17)
self.assertEqual(size, 163840) # Double checked with RIPE stat.
def test_radix_init_from_string(self):
"""
Test radix initialization from in memory string
"""
with open(FAKE_IPASN_DB_PATH, "rt") as f:
ipasn_str = f.read()
self.assertEqual(len(ipasn_str.splitlines()), 12) # fake data has 12 lines
radix = pyasn_radix.Radix() # note that pyasn_radix is *internal* & not directly used
n = radix.load_ipasndb("", ipasn_str)
self.assertEqual(n, 5) # and 5 prefixes
# now test the correctness
for i in range(4):
asn, prefix = self.asndb_fake.lookup("1.0.0.%d" % i)
self.assertEqual(1, asn)
self.assertEqual("1.0.0.0/30", prefix)
for i in range(4, 256):
asn, prefix = self.asndb_fake.lookup("1.0.0.%d" % i)
self.assertEqual(2, asn)
self.assertEqual("1.0.0.0/24", prefix)
for i in range(256):
asn, prefix = self.asndb_fake.lookup("2.0.0.%d" % i)
self.assertEqual(3, asn)
self.assertEqual("2.0.0.0/24", prefix)
for i in range(128, 256):
asn, prefix = self.asndb_fake.lookup("3.%d.0.0" % i)
self.assertEqual(4, asn)
self.assertEqual("3.0.0.0/8", prefix)
for i in range(0, 128):
asn, prefix = self.asndb_fake.lookup("3.%d.0.0" % i)
self.assertEqual(5, asn)
self.assertEqual("3.0.0.0/9", prefix)
asn, prefix = self.asndb_fake.lookup("5.0.0.0")
self.assertEqual(None, asn)
self.assertEqual(None, prefix)
def test_pyasn_from_string(self):
"""
Test pyasn initialization from in memory string
"""
with open(FAKE_IPASN_DB_PATH, "rt") as f:
ipasn_str = f.read()
self.assertEqual(len(ipasn_str.splitlines()), 12) # fake data has 12 lines
n = pyasn(None, ipasn_string=ipasn_str)
# now test the correctness
for i in range(4):
asn, prefix = n.lookup("1.0.0.%d" % i)
self.assertEqual(1, asn)
self.assertEqual("1.0.0.0/30", prefix)
for i in range(4, 256):
asn, prefix = self.asndb_fake.lookup("1.0.0.%d" % i)
self.assertEqual(2, asn)
self.assertEqual("1.0.0.0/24", prefix)
for i in range(256):
asn, prefix = self.asndb_fake.lookup("2.0.0.%d" % i)
self.assertEqual(3, asn)
self.assertEqual("2.0.0.0/24", prefix)
for i in range(128, 256):
asn, prefix = self.asndb_fake.lookup("3.%d.0.0" % i)
self.assertEqual(4, asn)
self.assertEqual("3.0.0.0/8", prefix)
for i in range(0, 128):
asn, prefix = self.asndb_fake.lookup("3.%d.0.0" % i)
self.assertEqual(5, asn)
self.assertEqual("3.0.0.0/9", prefix)
asn, prefix = self.asndb_fake.lookup("5.0.0.0")
self.assertEqual(None, asn)
self.assertEqual(None, prefix)
| 12,259 | 43.42029 | 99 | py |
pyasn | pyasn-master/tests/test_PyASN_1_2_aggressive.py | # Copyright (c) 2009-2014 Hadi Asghari
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import print_function
from unittest import TestCase
import pyasn
import logging
import sys
from glob import glob
import random
IPASN_DB_PATH = "/data/data/db.rviews/"
logger = logging.getLogger()
class TestPyASNAggresive(TestCase):
def test_all_ipasn_dbs(self):
"""
Checks compatibility of PyASN 1.2 results with current pyasn for all 2014 ipasn dbs .
"""
version = sys.version_info[0]
try:
import PyASN
assert version == 2
except:
print("SKIPPING - Python 2 or PyASN 1.2 not present ...", file=sys.stderr, end=' ')
return
dbs = glob(IPASN_DB_PATH + "ipasn_2014*.dat")
print("", file=sys.stderr)
for db in sorted(dbs):
random.seed(db) # for reproducibility
print("comparing %s" % db, file=sys.stderr)
newdb = pyasn.pyasn(db)
olddb = PyASN.new(db)
for i in range(1000000):
i1 = random.randint(1, 223)
i2 = random.randint(0, 255)
i3 = random.randint(0, 255)
i4 = random.randint(0, 255)
sip = "%d.%d.%d.%d" % (i1, i2, i3, i4)
newas, prefix = newdb.lookup(sip)
if newas:
self.assertTrue(newas > 0, msg="Negative AS for IP %s = %s" % (sip, newas))
oldas = olddb.Lookup(sip)
if oldas < 0:
# this is an overflow bug in the old version,
# e.g. 193.181.4.145 on 2014/10/07 returns -33785576
continue
self.assertEqual(oldas, newas, msg="Failed for IP %s" % sip)
| 2,810 | 37.506849 | 97 | py |
pyasn | pyasn-master/tests/test_comparative.py | # Copyright (c) 2014-2017 Hadi Asghari
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import print_function, division
import gzip
import pickle
from unittest import TestCase
import pyasn
from os import path
from struct import pack
from socket import inet_ntoa
import logging
from sys import stderr
IPASN_DB_PATH = path.join(path.dirname(__file__), "../data/ipasn_20140513.dat.gz")
STATIC_CYMRUWHOIS_PATH = path.join(path.dirname(__file__), "../data/cymru.map")
STATIC_PYASNv12_PATH = path.join(path.dirname(__file__),
"../data/pyasn_v1.2__ipasn_20140513__sample_10000.pickle.gz")
logger = logging.getLogger()
class TestCorrectness(TestCase):
asndb = pyasn.pyasn(IPASN_DB_PATH)
def test_against_cymru(self):
"""
Tests if pyasn returns similar ASNs to static lookups saved from Cymru-whois.
"""
with open(STATIC_CYMRUWHOIS_PATH, "r") as f:
cymru_map = eval(f.read())
self.assertTrue(len(cymru_map) > 0,
msg="Failed to Load cymru.map! Test resource not found or empty.")
print(file=stderr)
diff = 0
for ip in sorted(cymru_map.keys()): # For output consistency sort order of IPs
a, prefix = self.asndb.lookup(ip)
b = cymru_map[ip]
if a != b:
diff += 1
# print(" %-15s > cymru: %6s, pyasn: %6s" % (ip, b, a), file=stderr)
self.assertTrue(diff < 30, msg="Failed for >%d cases" % diff)
print(" Cymru-whois & pyasn differ in %d/%d cases; acceptable.. " % (diff, len(cymru_map)),
end='', file=stderr)
# Note, if we wish to extend this test, one could programatically accesses
# Cymru whois as fullows (- although we have our own function):
# https://github.com/csirtfoundry/BulkWhois
# https://github.com/trolldbois/python-cymru-services
# https://github.com/JustinAzoff/python-cymruwhois
# Also:
# whois -h whois.cymru.com " -f 216.90.108.31 2005-12-25 13:23:01 GMT"
def test_compatibility(self):
"""
Tests if pyasn returns the same AS number as the old version of pyasn.
"""
f = gzip.open(STATIC_PYASNv12_PATH, "rb")
logger.debug("Loading mapping file ...")
old_mapping = pickle.load(f)
self.assertTrue(len(old_mapping) > 0,
msg="Failed to Load pyasn_v1.2__ipasn_20140513__sample_10000.pickle.gz!"
" Test resource not found or empty.")
logger.debug("Mapping file loaded.")
same, diff = (0, 0)
for nip in sorted(old_mapping.keys()): # For output consistency sort the order of IPs
sip = inet_ntoa(pack('>I', nip))
asn, prefix = self.asndb.lookup(sip)
old_asn = old_mapping[nip]
if sip in ('128.189.32.228', '209.159.249.194'):
continue # skip these as pickle created from a bit older rib file.
if asn != old_asn:
logger.debug("AS Lookup inconsistent for %s pyasn = %s pyasn-v1.2 = %s" % (
sip, asn, old_asn))
diff += 1
else:
same += 1
self.assertEqual(diff, 0, msg="Too Many failures!")
logger.info("same: %d, diff: %d" % (same, diff))
f.close()
| 4,457 | 44.030303 | 99 | py |
pyasn | pyasn-master/tests/test_mrtx.py | # Copyright (c) 2014-2017 Hadi Asghari
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import print_function, division
from unittest import TestCase
from pyasn.mrtx import *
from bz2 import BZ2File
import gzip
from os import path
import logging
RIB_TD1_PARTDUMP = path.join(path.dirname(__file__), "../data/rib.20080501.0644_firstMB.bz2")
RIB_TD2_PARTDUMP = path.join(path.dirname(__file__), "../data/rib.20140523.0600_firstMB.bz2")
RIB6_TD2_PARTDUMP = path.join(path.dirname(__file__), "../data/rib6.20151101.0600_firstMB.bz2")
RIB_TD2_RECORD_FAIL_PARTDUMP = path.join(path.dirname(__file__),
"../data/bview.20140112.1600_3samples.bz2")
RIB_TD1_FULLDUMP = path.join(path.dirname(__file__), "../data/rib.20080501.0644.bz2")
RIB_TD2_FULLDUMP = path.join(path.dirname(__file__), "../data/rib.20140513.0600.bz2")
RIB_TD1_WIDE_FULLDUMP = path.join(path.dirname(__file__), "../data/rib_rvwide.20040701.0000.bz2")
RIB_TD2_REPEATED_FAIL_FULLDUMP = path.join(path.dirname(__file__), "../data/rib.20170102.1400.bz2")
RIB6_TD2_FULLDUMP = path.join(path.dirname(__file__), "../data/rib6.20151101.0600.bz2")
IPASN_TD1_DB = path.join(path.dirname(__file__), "../data/ipasn_20080501_v12.dat.gz")
IPASN_TD2_DB = path.join(path.dirname(__file__), "../data/ipasn_20140513_v12.dat.gz")
TEMP_IPASNDAT = path.join(path.dirname(__file__), "ipasn_test.tmp")
class TestMrtx(TestCase):
def test_mrt_table_dump_v2(self):
"""
Tests pyasn.mrtx internal classes by converting start of an RIB TD2 file
"""
f = BZ2File(RIB_TD2_PARTDUMP, 'rb')
# first record: TDV2 (13), PEERIX (1)
mrt = MrtRecord.next_dump_table_record(f)
self.assertEqual(mrt.type, MrtRecord.TYPE_TABLE_DUMP_V2)
self.assertEqual(mrt.sub_type, MrtRecord.T2_PEER_INDEX)
self.assertEqual(mrt.ts, 1400824800)
self.assertEqual(mrt.data_len, 619)
self.assertNotEqual(mrt.detail, None)
# second record - "0.0.0.0/0" to 16637
mrt = MrtRecord.next_dump_table_record(f)
self.assertEqual(mrt.type, MrtRecord.TYPE_TABLE_DUMP_V2)
self.assertEqual(mrt.sub_type, MrtRecord.T2_RIB_IPV4)
self.assertEqual(mrt.ts, 1400824800)
self.assertEqual(mrt.data_len, 51)
self.assertTrue(isinstance(mrt.detail, MrtTD2Record))
self.assertEqual(mrt.detail.seq, 0)
self.assertEqual(mrt.prefix, "0.0.0.0/0")
self.assertEqual(mrt.detail.entry_count, 1)
entry = mrt.detail.entries[0]
self.assertEqual(entry.attr_len, 36)
self.assertEqual(entry.peer, 32)
self.assertEqual(entry.orig_ts, 1399538361)
# self.assertEqual(len(entry.attrs), 4) -- due to optimization not reading other attributes
self.assertEqual(entry.attrs[0].bgp_type, 1)
self.assertEqual(entry.attrs[1].bgp_type, BgpAttribute.ATTR_AS_PATH)
attr = entry.attrs[1]
self.assertEqual(attr.flags, 80)
self.assertEqual(len(attr.data), 14)
self.assertTrue(isinstance(attr.path_detail(), BgpAttribute.BgpAttrASPath))
aspath = attr.path_detail()
self.assertEqual(len(aspath.pathsegs), 1)
self.assertEqual(str(aspath.pathsegs[0]), "sequence[2905, 65023, 16637]")
self.assertEqual(aspath.get_origin_as(), 16637)
# third record -
mrt = MrtRecord.next_dump_table_record(f)
self.assertTrue(isinstance(mrt.detail, MrtTD2Record))
self.assertEqual(mrt.data_len, 1415)
self.assertEqual(mrt.detail.seq, 1)
self.assertEqual(mrt.prefix, "1.0.0.0/24")
self.assertEqual(mrt.detail.entry_count, 32) # wow!
entry = mrt.detail.entries[0]
self.assertEqual(entry.attr_len, 29)
self.assertEqual(entry.peer, 23)
self.assertEqual(entry.attrs[0].bgp_type, 1)
self.assertEqual(entry.attrs[1].bgp_type, BgpAttribute.ATTR_AS_PATH)
attr = entry.attrs[1]
self.assertEqual(attr.flags, 80)
self.assertEqual(len(attr.data), 14)
self.assertTrue(isinstance(attr.path_detail(), BgpAttribute.BgpAttrASPath))
aspath = attr.path_detail()
self.assertEqual(len(aspath.pathsegs), 1)
self.assertEqual(str(aspath.pathsegs[0]), "sequence[701, 6453, 15169]")
self.assertEqual(aspath.get_origin_as(), 15169)
assert_results = {'1.0.4.0/24': 56203,
'1.0.5.0/24': 56203,
'1.0.20.0/23': 2519,
'1.0.38.0/24': 24155,
'1.0.128.0/17': 9737,
'1.1.57.0/24': 132537,
'1.38.0.0/17': set([38266]),
'1.116.0.0/16': 131334,
'5.128.0.0/14': set([50923]),
'5.128.0.0/16': 31200}
for seq in range(2, 9000):
mrt = MrtRecord.next_dump_table_record(f)
self.assertTrue(isinstance(mrt.detail, MrtTD2Record))
self.assertEqual(mrt.detail.seq, seq)
# self.assertTrue(mrt.as_path is not None)
prefix = mrt.prefix
origin = mrt.get_first_origin_as()
self.assertTrue(origin) # an integer or set!
if prefix in assert_results:
self.assertEqual(assert_results[prefix],
origin,
"error in origin for prefix: %s" % prefix)
def test_mrt_table_dump_v1(self):
"""
Tests pyasn.mrtx internal classes by converting start of an RIB TD1 file
"""
f = BZ2File(RIB_TD1_PARTDUMP, 'rb')
# first record: TDV1 (10). prefix "0.0.0.0/0"
mrt = MrtRecord.next_dump_table_record(f)
self.assertEqual(mrt.type, MrtRecord.TYPE_TABLE_DUMP)
self.assertEqual(mrt.sub_type, MrtRecord.T1_AFI_IPv4)
self.assertEqual(mrt.ts, 1209624298)
self.assertEqual(mrt.data_len, 42)
self.assertTrue(isinstance(mrt.detail, MrtTD1Record))
self.assertEqual(mrt.detail.seq, 0)
self.assertEqual(mrt.prefix, "0.0.0.0/0")
self.assertEqual(mrt.detail.attr_len, 20)
self.assertEqual(mrt.detail.peer_as, 11686)
self.assertEqual(mrt.detail.orig_ts, 1209453195)
# self.assertEqual(len(mrt.detail.attrs), 3) 2 if optimization is on!
self.assertEqual(mrt.detail.attrs[0].bgp_type, 1)
self.assertEqual(mrt.detail.attrs[1].bgp_type, BgpAttribute.ATTR_AS_PATH)
attr = mrt.detail.attrs[1]
self.assertEqual(attr.flags, 64)
self.assertEqual(len(attr.data), 6)
self.assertTrue(isinstance(attr.path_detail(), BgpAttribute.BgpAttrASPath))
aspath = attr.path_detail()
self.assertEqual(len(aspath.pathsegs), 1)
self.assertEqual(str(aspath.pathsegs[0]), "sequence[11686, 3561]")
self.assertEqual(aspath.get_origin_as(), 3561)
# second, then third record -
mrt = MrtRecord.next_dump_table_record(f)
self.assertTrue(isinstance(mrt.detail, MrtTD1Record))
self.assertEqual(mrt.detail.seq, 1)
self.assertEqual(mrt.prefix, "0.0.0.0/0")
mrt = MrtRecord.next_dump_table_record(f)
self.assertTrue(isinstance(mrt.detail, MrtTD1Record))
self.assertEqual(mrt.detail.seq, 2)
self.assertEqual(mrt.prefix, "3.0.0.0/8")
self.assertEqual(mrt.detail.attr_len, 67)
self.assertEqual(mrt.detail.peer_as, 13237)
self.assertEqual(mrt.detail.attrs[0].bgp_type, 1)
self.assertEqual(mrt.detail.attrs[1].bgp_type, BgpAttribute.ATTR_AS_PATH)
attr = mrt.detail.attrs[1]
self.assertEqual(attr.flags, 64)
self.assertEqual(len(attr.data), 14)
self.assertTrue(isinstance(attr.path_detail(), BgpAttribute.BgpAttrASPath))
aspath = attr.path_detail()
self.assertEqual(len(aspath.pathsegs), 1)
self.assertEqual(str(aspath.pathsegs[0]), "sequence[13237, 3320, 1239, 701, 703, 80]")
self.assertEqual(aspath.get_origin_as(), 80)
assert_results = {
'3.0.0.0/8': 80,
'4.79.181.0/24': 14780,
'6.9.0.0/20': 668,
'8.2.118.0/23': 13909,
'8.3.52.0/23': 26759,
'8.4.96.0/20': 15162,
'8.6.48.0/21': 36492,
'8.7.81.0/24': 25741,
'8.7.232.0/24': 13909,
}
for seq in range(3, 9000):
mrt = MrtRecord.next_dump_table_record(f)
self.assertTrue(isinstance(mrt.detail, MrtTD1Record))
self.assertEqual(mrt.detail.seq, seq)
# self.assertTrue(mrt.as_path is not None)
prefix = mrt.prefix
origin = mrt.get_first_origin_as()
self.assertTrue(origin) # an integer or set!
if prefix in assert_results:
self.assertEqual(assert_results[prefix],
origin,
"error in origin for prefix: %s" % prefix)
def test_converter_full_v2(self):
"""
Tests pyasn.mrtx.parse_mrt_file() - converts a full (TD2) RIB file, and compares
results with pyasn v1.2
"""
self.dotest_converter_full(RIB_TD2_FULLDUMP, IPASN_TD2_DB)
def test_converter_full_v1(self):
"""
Tests pyasn.mrtx.parse_mrt_file() - converts a full (TD1) RIB file, and compares
results with pyasn v1.2
"""
self.dotest_converter_full(RIB_TD1_FULLDUMP, IPASN_TD1_DB)
def dotest_converter_full(self, full_ribdump_path, ipasn_db_path=None):
# internal method called by both test_converter_full_v1 & test_converter_full_v2
if not path.isfile(full_ribdump_path):
print("SKIPPING - full dump doesn't exist.", file=stderr, end='')
return
print("starting conversion of", full_ribdump_path.split('/')[-1], file=stderr)
converted = parse_mrt_file(full_ribdump_path, print_progress=True)
v6 = sum(1 for x in converted if ':' in x)
print(" Converted %d IPV4 + %d IPV6 prefixes." % (len(converted) - v6, v6), file=stderr)
if not ipasn_db_path:
return # nothing more to compare!
# test of write-output
dump_prefixes_to_text_file(converted,
TEMP_IPASNDAT,
full_ribdump_path,
debug_write_sets=True)
# tests of comparing with v 1.2 (existing conversion): load it, then compare
# an alternative option is to run a linux DIFF comppand between TMEP_IPASNDAT & IPASN_DB
ipasndat_v12 = {}
f = gzip.open(ipasn_db_path, "rt") if ipasn_db_path.endswith(".gz") else \
open(ipasn_db_path, "rt")
for s in f:
if s[0] == '#' or s[0] == '\n' or s[0] == ';':
continue
prefix, asn = s[:-1].split()
ipasndat_v12[prefix] = int(asn)
f.close() # Py2.6 doesn't support 'with' for gzip files
print("Comparing %d new vs %d old conversions" % (len(converted), len(ipasndat_v12)),
file=stderr)
bogus_count = 0
for prefix in converted:
if prefix in ipasndat_v12:
# first, let's check prefixes in both. won't work if not run fully
origin = converted[prefix]
old = ipasndat_v12[prefix]
# changes 2014/11/02, now we don't return bogus origin ASNs
if not is_asn_bogus(old):
msg = "Converter results differ: %s => %d (was %d)" % (prefix, origin, old)
self.assertEqual(origin, old, msg=msg)
else:
bogus_count += 1
msg = "Converter returned bogus route: %s => %d" % (prefix, origin)
self.assertTrue(not is_asn_bogus(origin), msg=msg)
self.assertTrue(bogus_count < 214,
msg="Many unexplained updated bogus prefixes: %d" % bogus_count)
# 98 for 20140523; 213 for 20080501
print("Updated bogus prefixes in new converter: %d" % bogus_count, file=stderr)
skipped_count = 0
for prefix in converted:
# check if prefixes in converted are in baseline.
# most should be -- (a few, 129 out of 513k, were returned NONE in pyasn 1.2)
if prefix not in ipasndat_v12:
skipped_count += 1
origin = converted[prefix]
if prefix in ("162.212.40.0/24",
"192.88.192.0/24",
"199.193.100.0/22",
"207.35.39.0/24"):
# These prefix are new & checked to be ok in 2014/05/13.
# They aren't "set" because the set items are all bogus, so previous
# segment/sequence was returned
continue
self.assertTrue(isinstance(origin, set),
msg="Unexplained non-set prefix %s in output" % prefix)
self.assertTrue(skipped_count < 132,
msg="Many unexplained new prefixes: %d" % skipped_count)
# 131 for 20140523; 52 for 20080501
print("Prefixes in new converter (skipped before): %d" % skipped_count, file=stderr)
# we should have all in baseline, if run fully
for prefix in ipasndat_v12:
self.assertTrue(prefix in converted,
msg="Prefix %s missing from new converter output" % prefix)
def test_mrt6_table_dump_v2(self):
"""
Tests pyasn.mrtx internal classes by converting start of an RIB6 TD2 file (IPv6)
"""
f = BZ2File(RIB6_TD2_PARTDUMP, 'rb')
# first record
mrt = MrtRecord.next_dump_table_record(f)
self.assertEqual(mrt.type, MrtRecord.TYPE_TABLE_DUMP_V2)
self.assertEqual(mrt.sub_type, MrtRecord.T2_PEER_INDEX)
self.assertEqual(mrt.ts, 1446357600)
self.assertEqual(mrt.data_len, 733)
self.assertNotEqual(mrt.detail, None)
# second record
mrt = MrtRecord.next_dump_table_record(f)
self.assertEqual(mrt.type, MrtRecord.TYPE_TABLE_DUMP_V2)
self.assertEqual(mrt.sub_type, MrtRecord.T2_RIB_IPV6)
self.assertEqual(mrt.ts, 1446357600)
self.assertEqual(mrt.data_len, 1741)
self.assertTrue(isinstance(mrt.detail, MrtTD2Record))
self.assertEqual(mrt.detail.seq, 0)
self.assertEqual(mrt.prefix, "2001::/32")
self.assertEqual(mrt.detail.entry_count, 24)
entry = mrt.detail.entries[0]
self.assertEqual(entry.attr_len, 85)
self.assertEqual(entry.peer, 10)
self.assertEqual(entry.orig_ts, 1446348241)
self.assertEqual(entry.attrs[0].bgp_type, 1)
self.assertEqual(entry.attrs[1].bgp_type, BgpAttribute.ATTR_AS_PATH)
attr = entry.attrs[1]
self.assertEqual(attr.flags, 80)
self.assertEqual(len(attr.data), 14)
self.assertTrue(isinstance(attr.path_detail(), BgpAttribute.BgpAttrASPath))
aspath = attr.path_detail()
self.assertEqual(len(aspath.pathsegs), 1)
self.assertEqual(str(aspath.pathsegs[0]), "sequence[3257, 1103, 1101]")
# Note: can't figure out if 1101 or this path sequence is correct
self.assertEqual(aspath.get_origin_as(), 1101)
# third record -
mrt = MrtRecord.next_dump_table_record(f)
self.assertTrue(isinstance(mrt.detail, MrtTD2Record))
self.assertEqual(mrt.data_len, 1724)
self.assertEqual(mrt.detail.seq, 1)
self.assertEqual(mrt.prefix, "2001:4:112::/48")
self.assertEqual(mrt.detail.entry_count, 23)
entry = mrt.detail.entries[0]
self.assertEqual(entry.attr_len, 87)
self.assertEqual(entry.peer, 10)
self.assertEqual(entry.attrs[0].bgp_type, 1)
self.assertEqual(entry.attrs[1].bgp_type, BgpAttribute.ATTR_AS_PATH)
attr = entry.attrs[1]
self.assertEqual(attr.flags, 80)
self.assertEqual(len(attr.data), 14)
self.assertTrue(isinstance(attr.path_detail(), BgpAttribute.BgpAttrASPath))
aspath = attr.path_detail()
self.assertEqual(len(aspath.pathsegs), 1)
self.assertEqual(str(aspath.pathsegs[0]), "sequence[3257, 1103, 112]")
self.assertEqual(aspath.get_origin_as(), 112)
# follow list chosen from the file; randomly did WHOIS lookups on prefixes; correct
assert_results = {"2001:504:2e::/48": 10578,
"2001:57a:e030::/45": 22773,
"2001:590:1800::/38": 4436,
"2001:67c:368::/48": 12509,
"2001:67c:14d8::/48": 61413,
"2001:67c:22f4::/48": 200490,
"2001:67c:2c90::/48": 60092,
"2001:978:1801::/48": 174,
"2001:dc5:0:55::/64": 9700,
"2001:df2:f000::/48": 55319,
"2001:12c4::/32": 28262,
"2001:1838:5000::/40": 23352,
"2001:1a88::/32": 15600,
"2001:4478:1900::/40": 4802, # part of a /30? IINET-SIXNET. AS: IINET.
"2001:4888:4:fe00::/64": 22394,
"2001:49f0:a015::/48": 174,
"2001:b032:1b::/48": 3462,
"2400:bc00:1800::/48": 10115,
"2401:4800::/32": 38457,
"2402:a00:111::/48": 45916,
"2402:db00::/32": 132142,
"2403:bc00:1::/48": 45668,
"2404:8000:9::/48": 17451,
"2405:1e00:8::/48": 17771,
"2406:3000:11:1026::/64": 4657, # part of /48. StarHub-Ltd. AS: StarHub
"2406:5600:6a::/48": 131222,
"2407:3100::/48": 10118,
"2600:1:a154::/46": 3651,
"2600:380:5c00::/38": 20057,
"2600:1006:8020::/44": 22394,
"2600:1404:23::/48": 20940,
"2600:3004::/32": 13649,
"2600:8801:2900::/41": 22773,
"2604:200::/32": 33132,
"2604:a680:2::/48": 55079,
"2605:2a80::/32": 62489,
"2605:dc80::/48": 31985,
"2606:2800:4a6c::/48": 15133,
"2606:b400:8018::/48": 792,
"2607:cf03::/34": 40583,
"2607:f2c8::/32": 13730,
"2607:f748::/32": 32613,
"2607:fcc0::/32": 36483,
"2610:f8::/32": 26398,
"2620:3a:400d::/48": 36711,
"2620:100:6000::/44": 19679,
"2620:10a:9047::/48": 11133,
"2620:11b:400e::/47": 47870,
"2800:68:15::/48": 52343,
"2800:e00::/24": 27665, # PREFIX: ROM16-COLUMBUSTRINIDAD.COM. AS: same
"2803:a200:4::/48": 263240,
"2804:14c:bf40::/42": 28573,
"2804:214:8241::/48": 26615,
"2804:7f5:8000::/33": 18881,
"2804:1270:a2::/48": 262851,
"2804:2554::/32": 264274,
"2a00:10ef::/32": 5413,
"2a00:18c0::/32": 8402,
"2a00:4140::/32": 34766,
"2a00:7ac0::/32": 196742,
"2a00:aa80::/32": 51474,
"2a00:e8c0::/32": 34797,
"2a01:528::/32": 6775, # correct in whois
"2a01:6c60:1000::/36": 62217,
"2a01:8840:c0::/48": 12041,
"2a01:c9c0:a5::/48": 8891,
"2a02:690::/32": 41960,
"2a02:fb0::/32": 5503,
"2a02:2698:1800::/38": 51604,
"2a02:2928::/32": 39288,
"2a02:7820::/32": 201873,
"2a02:e980:43::/48": 19551,
"2a03:2c80::/32": 31084,
"2a03:7380:1f80::/42": 13188, # correct in WHOIS
"2a03:cd00::/32": 1668,
"2a04:4940::/29": 60278,
"2a04:e4c0:14::/48": 36692,
"2a05:d880:1::/48": 43066,
"2a06:9800::/29": 6908,
}
for seq in range(2, 2000):
mrt = MrtRecord.next_dump_table_record(f)
self.assertTrue(isinstance(mrt.detail, MrtTD2Record))
self.assertEqual(mrt.detail.seq, seq)
# self.assertTrue(mrt.as_path is not None)
prefix = mrt.prefix
origin = mrt.get_first_origin_as()
self.assertTrue(origin) # an integer or set!
if prefix in assert_results:
self.assertEqual(assert_results[prefix],
origin,
"error in origin for prefix: %s" % prefix)
def test_converter_full_v2_ip6(self):
"""
Tests pyasn.mrtx.parse_mrt_file() - converts a full (TD2) RIB file with IPv6;
discards output
"""
self.dotest_converter_full(RIB6_TD2_FULLDUMP)
def test_skip_all_line_on_single_error_with_boolean_false(self):
"""
Tests pyasn.mrtx.parse_mrt_file() with skip_record_on_error set to default(False);
"""
self.assertRaises(IndexError, parse_mrt_file, RIB_TD2_RECORD_FAIL_PARTDUMP)
def test_read_all_line_on_single_error_with_boolean_true(self):
"""
Tests pyasn.mrtx.parse_mrt_file() with skip_record_on_error set to True
"""
res = parse_mrt_file(RIB_TD2_RECORD_FAIL_PARTDUMP, skip_record_on_error=True)
self.assertEqual(len(res), 2)
def test_parsing_repeated_prefixes_tabledump(self):
"""
Tests pyasn.mrtx.parse_mrt_file() with repeated prefixes causing errros (bug #39)
"""
self.dotest_converter_full(RIB_TD2_REPEATED_FAIL_FULLDUMP)
def test_parsing_rviews_wide_td1(self):
"""
Tests pyasn.mrtx.parse_mrt_file() with routeviews WIDE archive TD1 (bug #42)
"""
self.dotest_converter_full(RIB_TD1_WIDE_FULLDUMP)
| 23,833 | 47.443089 | 99 | py |
pyasn | pyasn-master/tests/utilities/gen_pyasn_v1_2_mapping.py | # Copyright (c) 2009-2014 Hadi Asghari
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
IMPORTANT: This script has to be run using python 2.
Because the old PyASN is not python 3 compatible
"""
import sys
version = sys.version_info[0]
try:
assert version == 2
except Exception:
print("This script must be run using python version 2!")
print("Make sure that PyASN v1.2 is installed as well.")
exit()
import PyASN
import random
from sys import argv, exit
from struct import pack, unpack
from socket import inet_aton, inet_ntoa
import cPickle as pickle
import gzip
import os
def generate_pyasn_v1_2_ip_to_asn_mapping(pyasn_db, size):
mapping = {}
asndb = PyASN.new(pyasn_db)
filename = os.path.basename(pyasn_db).split('.')[0]
size = int(size)
while len(mapping) < size:
i1 = random.randint(1, 223)
i2 = random.randint(0, 255)
i3 = random.randint(0, 255)
i4 = random.randint(0, 255)
sip = "%d.%d.%d.%d" % (i1, i2, i3, i4)
ip = unpack('>I', inet_aton(sip))[0] # for efficient, store ip as 32-bit-int
mapping[ip] = asndb.Lookup(sip)
f = gzip.open("pyasn_v1.2__%s__sample_%d.pickle.gz" % (filename, size), "wb")
pickle.dump(mapping, f)
f.close()
if len(argv) != 3:
print("Usage: python generate_old_pyasn_mapping.py <PYASN_DB_FILE> <number_records_to_generate>")
print(" generates a static list of random IPs to AS mappings based on PyASN-1.2")
print(" The output file can be copied to the data folder to be used by the unit tests.")
exit()
generate_pyasn_v1_2_ip_to_asn_mapping(argv[1], argv[2]) | 2,652 | 36.9 | 101 | py |
pyasn | pyasn-master/tests/utilities/gen_cymru_mapping.py | # Copyright (c) 2009-2014 Hadi Asghari
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import subprocess
import random
import os
from datetime import datetime
from sys import argv, exit
TEST_RESOURCES_PATH = os.path.dirname(__file__, "../data")
def as_loopkup_teamcymru(ip, date):
datetime_string = date.strftime("%Y-%m-%d %H:%M:%S GMT")
# note: route-views uses UTC, and we normally download files of 06:00; thus 6:00:00 GMT should be passed to cymru
result = subprocess.check_output(["whois", '-h', ('%s' % 'whois.cymru.com'), ' -f %s %s' % (ip, datetime_string)])
result = result.decode().split("|")[0].strip()
return result if result != "NA" else None
def generate_cymru_whois_ip_to_asn_mapping(s_date):
date = datetime.strptime(s_date, "%Y%m%d")
mapping = {}
for count in range(1000):
i1 = random.randint(1, 223)
i2 = random.randint(0, 255)
i3 = random.randint(0, 255)
i4 = random.randint(0, 255)
ip = "%d.%d.%d.%d" % (i1, i2, i3, i4)
asn = as_loopkup_teamcymru(ip, date)
mapping[ip] = asn
with open("cymru.map", "w") as f:
print("saving output to: %s" % f.name)
f.write("#Mapping based on %s" % date)
f.write("{\n")
for ip in mapping:
f.write("'%s' : %s, \n" % (ip, mapping[ip]))
f.write("}")
if len(argv) != 2:
print("Usage: python generate_test_resources.py YYYYMMDD ")
print(" generates a static list of random IPs to AS mappings based on team-cymru WHOIS service")
print(" The output file can be copied to the data folder to be used by the unit tests.")
exit()
generate_cymru_whois_ip_to_asn_mapping(argv[1])
| 2,712 | 39.492537 | 119 | py |
pyasn | pyasn-master/pyasn-utils/pyasn_util_convert.py | #!/usr/bin/python
# Copyright (c) 2009-2017 Hadi Asghari
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# MRT RIB log import [to convert to a text IP-ASN lookup table]
# file to use per day should be of the RouteViews or RIPE RIS series, e.g.:
# http://archive.routeviews.org/bgpdata/2009.11/RIBS/rib.20091125.0600.bz2
from __future__ import print_function, division
from pyasn import mrtx, __version__
from time import time
from sys import argv, exit, stdout
from glob import glob
from datetime import datetime, timedelta
from subprocess import call
from argparse import ArgumentParser
# Parse command line options
parser = ArgumentParser(description="Script to convert MRT/RIB archives to IPASN databases.",
epilog="MRT/RIB archives can be downloaded using "
"'pyasn_util_download.py', or directly from RouteViews (or RIPE RIS).")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--single", nargs=2, metavar=("RIBFILE", "IPASN.DAT"), action="store",
help="convert single file (use bz2 or gz suffix)")
group.add_argument("--dump-screen", nargs=1, metavar="RIBFILE", action="store",
help="parse and dump archive to screen")
group.add_argument("--bulk", nargs=2, metavar=("START-DATE", "END-DATE"), action="store",
help="bulk conversion (dates are Y-M-D, files need to be "
"named rib.xxxxxxxx.bz2 and in current directory)")
group.add_argument("--version", action="store_true")
# FIXME: tie --no-progress/--compress/--skip and --record-xx to respective options above
parser.add_argument("--compress", action="store_true", # in place of --binary (20160105)
help="gzip the IPASN output files (with --single)")
parser.add_argument("--no-progress", action="store_true",
help="don't show conversion progress (with --single)")
parser.add_argument("--skip-on-error", action="store_true",
help="skip records which fail conversion, instead of stopping (with --single)")
parser.add_argument("--record-from", type=int, metavar="N", action="store",
help="start dump from record N (with --dump-screen)")
parser.add_argument("--record-to", type=int, metavar="N", action="store",
help="end dump at record N (with --dump-screen)")
args = parser.parse_args()
if args.version:
print("MRT/RIB converter version %s." % __version__)
if args.single:
prefixes = mrtx.parse_mrt_file(args.single[0],
print_progress=not args.no_progress,
skip_record_on_error=args.skip_on_error)
mrtx.dump_prefixes_to_file(prefixes, args.single[1], args.single[0])
if not args.no_progress:
v6 = sum(1 for x in prefixes if ':' in x)
v4 = len(prefixes) - v6
print('IPASN database saved (%d IPV4 + %d IPV6 prefixes)' % (v4, v6))
if args.compress:
call(['gzip', args.single[1]])
if args.dump_screen:
mrtx.dump_screen_mrt_file(args.dump_screen[0],
record_to=args.record_to,
record_from=args.record_from,
screen=stdout)
if args.bulk:
try:
dt = datetime.strptime(args.bulk[0], '%Y-%m-%d').date() # TODO:
dt_end = datetime.strptime(args.bulk[1], '%Y-%m-%d').date()
except ValueError:
print("ERROR: malformed date, try YYYY-MM-DD")
exit()
print("Starting bulk RIB conversion, from %s to %s..." % (dt, dt_end))
stdout.flush()
while dt <= dt_end:
# for each day, process first file named "rib.YYYYMMDD.xxxx.bz2". (what about .gz?)
# this is default filename used by routeviews and downloaded by pyasn_wget_rib.py
files = glob("rib.%4d%02d%02d.????.bz2" % (dt.year, dt.month, dt.day))
if not files:
dt += timedelta(1)
continue
if len(files) > 1:
print("warning: multiple files on %s, only converting first." % dt)
dump_file = files[0]
print("%s... " % dump_file[4:-4])
stdout.flush()
dat = mrtx.parse_mrt_file(dump_file)
out_file = "ipasn_%d%02d%02d.dat" % (dt.year, dt.month, dt.day)
mrtx.dump_prefixes_to_file(dat, out_file, dump_file)
if args.compress:
call(['gzip', out_file])
dt += timedelta(1)
#
print('Finished!')
| 5,474 | 45.794872 | 99 | py |
pyasn | pyasn-master/pyasn-utils/pyasn_util_download.py | #!/usr/bin/python
# Copyright (c) 2009-2017 Hadi Asghari
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# Script to download the latest routeview bgpdata, or for a certain period
# Thanks to Vitaly Khamin (https://github.com/khamin) for the FTP code
from __future__ import print_function, division
from datetime import date, datetime
from time import time
from ftplib import FTP
from argparse import ArgumentParser
from subprocess import call
from sys import argv, exit, stdout, version_info
try:
from pyasn import __version__
except:
pass # not fatal if we can't get version
if version_info[0] < 3:
from urllib2 import urlopen
else:
from urllib.request import urlopen
# Parse command line options
# Note: --latest might be changes to --46, instead of --4, in the future
parser = ArgumentParser(description="Script to download MRT/RIB BGP archives (from RouteViews).")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--latestv4', '-4', '--latest', action='store_true',
help='Grab lastest IPV4 data')
group.add_argument('--latestv6', '-6', action='store_true', help='Grab lastest IPV6 data')
group.add_argument('--latestv46', '-46', action='store_true', help='Grab lastest IPV4/V6 data')
group.add_argument('--version', action='store_true')
group.add_argument('--dates-from-file', '-f', action='store',
help='Grab IPV4 archives for specifc dates (one date, YYYYMMDD, per line)')
parser.add_argument('--filename', action='store', help="Specify name with which the file will be saved")
args = parser.parse_args()
def ftp_download(server, remote_dir, remote_file, local_file, print_progress=True):
"""Downloads a file from an FTP server and stores it locally"""
ftp = FTP(server)
ftp.login()
ftp.cwd(remote_dir)
if print_progress:
print('Downloading ftp://%s/%s/%s' % (server, remote_dir, remote_file))
filesize = ftp.size(remote_file)
filename = args.filename if args.filename is not None else local_file
# perhaps warn before overwriting file?
with open(filename, 'wb') as fp:
def recv(s):
fp.write(s)
recv.chunk += 1
recv.bytes += len(s)
if recv.chunk % 100 == 0 and print_progress:
print('\r %.f%%, %.fKB/s' % (recv.bytes*100 / filesize,
recv.bytes / (1000*(time()-recv.start))), end='')
stdout.flush()
recv.chunk, recv.bytes, recv.start = 0, 0, time()
ftp.retrbinary('RETR %s' % remote_file, recv)
ftp.close()
if print_progress:
print('\nDownload complete.')
def find_latest_in_ftp(server, archive_root, sub_dir, print_progress=True):
"""Returns (server, filepath, filename) for the most recent file in an FTP archive"""
if print_progress:
print('Connecting to ftp://' + server)
ftp = FTP(server)
ftp.login()
months = sorted(ftp.nlst(archive_root), reverse=True) # e.g. 'route-views6/bgpdata/2016.12'
filepath = '/%s/%s' % (months[0], sub_dir)
if print_progress:
print("Finding most recent archive in %s ..." % filepath)
ftp.cwd(filepath)
fls = ftp.nlst()
if not fls:
filepath = '/%s/%s' % (months[1], sub_dir)
if print_progress:
print("Finding most recent archive in %s ..." % filepath)
ftp.cwd(filepath)
fls = ftp.nlst()
if not fls:
raise LookupError("Cannot find file to download. Please report a bug on github?")
filename = max(fls)
ftp.close()
return (server, filepath, filename)
def find_latest_routeviews(archive_ipv):
# RouteViews archives are as follows:
# ftp://archive.routeviews.org/datapath/YYYYMM/ribs/XXXX
archive_ipv = str(archive_ipv)
assert archive_ipv in ('4', '6', '46', '64')
return find_latest_in_ftp(server='archive.routeviews.org',
archive_root='bgpdata' if archive_ipv == '4' else
'route-views6/bgpdata' if archive_ipv == '6' else
'route-views4/bgpdata', # 4+6
sub_dir='RIBS')
if args.version:
print("MRT/RIB downloader version %s." % __version__)
if args.latestv4 or args.latestv6 or args.latestv46:
# Download latest RouteViews MRT/RIB archive
srvr, rp, fn = find_latest_routeviews(4 if args.latestv4 else 6 if args.latestv6 else '46')
ftp_download(srvr, rp, fn, fn)
if args.dates_from_file:
# read dates from a local file and use wget to download range
dates_to_get = []
f = open(args.dates_from_file)
if not f:
print("can't open %s" % args.dates_from_file)
exit()
for s in f:
if not s.strip() or s[0] == '#':
continue
dt = date(int(s[:4]), int(s[4:6]), int(s[6:8])) # Dates are strangely YYYYMMDD :)
dates_to_get.append(dt)
for dt in dates_to_get:
# FIXME: currently v4 only. should understand v4/v6 options, and possibly use FTP method
url_dir = 'http://archive.routeviews.org/bgpdata/%d.%02d/RIBS/' % (dt.year, dt.month)
print('Searching %s for %d-%02d-%02d...' % (url_dir, dt.year, dt.month, dt.day), end=' ')
stdout.flush()
html = str(urlopen(url_dir).read())
str_find = 'rib.%d%02d%02d' % (dt.year, dt.month, dt.day)
ix = html.find(str_find + '.06') # get the file saved at 6 AM for consistency
if ix == -1:
ix = html.find(str_find + '.05') # if not, try 5 AM
if ix == -1:
ix = html.find(str_find + '.00') # last resort, try the one saved at midnight
if ix == -1:
print('=> ERROR - NOT FOUND.')
continue
fname = html[ix:ix+21]
s = html[ix+80:ix+150]
ix = s.find('"right"')
assert ix != -1
s = s[ix+8:]
ix = s.find("</td>")
assert ix != -1
size = s[:ix]
url_full = url_dir + fname
print('downloading...', end=' ')
stdout.flush()
# FIXME: Why using urllib AND wget? Can urllib do listing AND downloading? (OR ftp...)
ret = call(['wget', '-q', url_full]) # wget in quiet mode
print()
ret = "" if ret == 0 else "[FAIL:%d]" % ret
print('%s\t%s\t%s\t%s' % (dt, size, url_full, ret))
stdout.flush()
| 7,426 | 39.807692 | 104 | py |
pyasn | pyasn-master/pyasn-utils/pyasn_util_asnames.py | #!/usr/bin/python
# Copyright (c) 2016 Italo Maia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import re
import codecs
import argparse
import logging
from sys import version_info
try:
import ujson as json
except ImportError:
import json
if version_info[0] < 3:
from urllib2 import urlopen
else:
from urllib.request import urlopen
logger = logging.getLogger(__name__)
ASNAMES_URL = 'http://www.cidr-report.org/as2.0/autnums.html'
HTML_FILENAME = "autnums.html"
EXTRACT_ASNAME_C = re.compile(r"<a .+>AS(?P<code>.+?)\s*</a>\s*(?P<name>.*)", re.U)
def get_parser():
parser = argparse.ArgumentParser(description='pyasn asnames downloader')
parser.add_argument(
'-i', '--html-input',
dest='input', help='input html file with asnames')
parser.add_argument(
'-o', '--output', dest='output',
help='output file name (defaults to console)')
parser.add_argument(
'-p', '--persist-html',
dest='persist_html', action='store_true',
help='persist intermediary html file? (autnums.html)', default=False)
return parser
def main(args):
data = None
# html source available?
if args.input:
logger.debug("using %s as html source" % args.input)
with codecs.open(args.input, encoding="utf-8") as fs:
data = fs.read()
# data is not available yet? Let's download it!
if data is None:
logger.debug("fetching asn names from remote")
data = download_asnames()
# only works if fetching from remote
if args.persist_html:
with codecs.open(HTML_FILENAME, "w", encoding='utf-8') as fs:
fs.write(data)
# parse it to json
data_dict = _html_to_dict(data)
data_json = json.dumps(data_dict)
# output to file?
if args.output:
with codecs.open(args.output, 'w', encoding="utf-8") as fs:
fs.write(data_json)
else:
# defaults to console
print(data_json)
def __parse_asname_line(line):
match = EXTRACT_ASNAME_C.match(line)
return match.groups()
def _html_to_dict(data):
"""
Translates an HTML string available at `ASNAMES_URL` into a dict
:param data:
:type data: str
:return:
:rtype: dict
"""
split = data.split("\n")
split = filter(lambda line: line.startswith("<a"), split)
fn = __parse_asname_line
return dict(map(fn, split))
def download_asnames():
"""
Downloads and parses to utf-8 asnames html file
"""
http = urlopen(ASNAMES_URL)
data = http.read()
http.close()
raw_data = data.decode('latin-1')
raw_data = raw_data.encode('utf-8')
return raw_data.decode("utf-8")
if __name__ == '__main__':
parser = get_parser()
args = parser.parse_args()
main(args)
| 3,814 | 27.901515 | 83 | py |
AutoPruner | AutoPruner-master/ResNet50/50/fine_tune_compressed_model.py | import argparse
import os
import shutil
import time
import sys
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
from torchvision import datasets, transforms
from src_code.lmdbdataset import lmdbDataset
from compress_model.new_model import NetworkNew_test
parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
'''parser.add_argument('data', metavar='DIR',
help='path to dataset')
'''
parser.add_argument('-j', '--workers', default=8, type=int, metavar='N',
help='number of data loading workers (default: 8)')
parser.add_argument('--epochs', default=30, type=int, metavar='N',
help='number of total epochs to run')
parser.add_argument('--start-epoch', default=0, type=int, metavar='N',
help='manual epoch number (useful on restarts)')
parser.add_argument('-b', '--batch-size', default=256, type=int,
metavar='N', help='mini-batch size (default: 128)')
parser.add_argument('--lr', '--learning-rate', default=0.001, type=float,
metavar='LR', help='initial learning rate')
parser.add_argument('--momentum', default=0.9, type=float, metavar='M',
help='momentum')
parser.add_argument('--weight-decay', '--wd', default=1e-4, type=float,
metavar='W', help='weight decay (default: 1e-4)')
parser.add_argument('--print-freq', '-p', default=10, type=int,
metavar='N', help='print frequency (default: 10)')
parser.add_argument('--resume', default='', type=str, metavar='PATH',
help='path to latest checkpoint (default: none)')
parser.add_argument('--evaluate', default=False, type=bool,
help='evaluate model on validation set')
parser.add_argument('--pretrained', dest='pretrained', action='store_true',
help='use pre-trained model')
parser.add_argument('--world-size', default=1, type=int,
help='number of distributed processes')
parser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str,
help='url used to set up distributed training')
parser.add_argument('--dist-backend', default='gloo', type=str,
help='distributed backend')
parser.add_argument('--gpu_id', default='7', type=str,
help='id(s) for CUDA_VISIBLE_DEVICES')
parser.add_argument('--data_base', default='/data/zhangcl/ImageNet', type=str, help='the path of dataset')
parser.add_argument('--load_from_lmdb', default=True, type=bool, help='load image data from lmdb or not')
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
best_prec1 = 0
print(args)
def main():
global args, best_prec1
args = parser.parse_args()
args.distributed = args.world_size > 1
if args.distributed:
dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url,
world_size=args.world_size)
# create model
# model = models.vgg16(pretrained=True)
model = NetworkNew_test('checkpoint/model.pth')
print(model)
model = torch.nn.DataParallel(model.cuda(), device_ids=range(torch.cuda.device_count()))
cudnn.benchmark = True
# define loss function (criterion) and optimizer
criterion = nn.CrossEntropyLoss().cuda()
optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), args.lr,
momentum=args.momentum,
weight_decay=args.weight_decay)
# Data loading code from lmdb
if args.load_from_lmdb:
train_loader = torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-train.lmdb'), True),
batch_size=args.batch_size,
shuffle=True,
num_workers=8,
pin_memory=True
)
print('train_loader_success!')
val_loader = torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-val.lmdb'), False),
batch_size=args.batch_size,
num_workers=8,
pin_memory=True
)
else:
traindir = os.path.join('/opt/luojh/Dataset/ImageNet/images', 'train')
valdir = os.path.join('/opt/luojh/Dataset/ImageNet/images', 'val')
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
train_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(traindir, transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])),
batch_size=args.batch_size, shuffle=True,
num_workers=args.workers, pin_memory=True)
val_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(valdir, transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])),
batch_size=args.batch_size, shuffle=False,
num_workers=args.workers, pin_memory=True)
# evaluate and train
if args.evaluate:
validate(val_loader, model, criterion)
return
for epoch in range(args.start_epoch, args.epochs):
adjust_learning_rate(optimizer, epoch, int(args.epochs/3.0))
# train for one epoch
train(train_loader, model, criterion, optimizer, epoch)
# evaluate on validation set
prec1 = validate(val_loader, model, criterion)
# remember best prec@1 and save checkpoint
is_best = prec1 > best_prec1
best_prec1 = max(prec1, best_prec1)
if is_best:
folder_path = 'checkpoint/fine_tune'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
torch.save(model.state_dict(), folder_path + '/model.pth')
print('best acc is %.3f' % best_prec1)
def train(train_loader, model, criterion, optimizer, epoch):
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to train mode
model.train()
end = time.time()
for i, (input, target) in enumerate(train_loader):
# measure data loading time
data_time.update(time.time() - end)
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input).cuda()
target_var = torch.autograd.Variable(target).cuda()
# compute output
output = model(input_var)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Epoch: [{0}][{1}/{2}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Data {data_time.val:.3f} ({data_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
epoch, i, len(train_loader), batch_time=batch_time,
data_time=data_time, loss=losses, top1=top1, top5=top5))
sys.stdout.flush()
def validate(val_loader, model, criterion):
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
for i, (input, target) in enumerate(val_loader):
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input, volatile=True)
target_var = torch.autograd.Variable(target, volatile=True)
# compute output
output = model(input_var)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
i, len(val_loader), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
sys.stdout.flush()
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
return top1.avg
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, 'model_best.pth.tar')
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def adjust_learning_rate(optimizer, epoch, epoch_num):
"""Sets the learning rate to the initial LR decayed by 10 every 4 epochs"""
lr = args.lr * (0.1 ** (epoch // epoch_num))
print('| Learning Rate = %f' % lr)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == '__main__':
main()
| 10,872 | 35.733108 | 106 | py |
AutoPruner | AutoPruner-master/ResNet50/50/main.py | # ************************************************************
# Author : Bumsoo Kim, 2017
# Github : https://github.com/meliketoy/fine-tuning.pytorch
#
# Korea University, Data-Mining Lab
# Deep Convolutional Network Fine tuning Implementation
#
# Description : main.py
# The main code for training classification networks.
# ***********************************************************
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import time
import os
import sys
import argparse
import numpy as np
import shutil
import math
from torchvision import models
from src_code import Network_FT
from src_code.lmdbdataset import lmdbDataset
parser = argparse.ArgumentParser(description='PyTorch Digital Mammography Training')
parser.add_argument('--lr', default=1e-3, type=float, help='learning rate')
parser.add_argument('--weight_decay', default=5e-4, type=float, help='weight decay')
parser.add_argument('--batch_size', default=256, type=int, help='batch size')
parser.add_argument('--num_epochs', default=8, type=int, help='number of training epochs')
parser.add_argument('--lr_decay_epoch', default=10, type=int, help='learning rate decay epoch')
parser.add_argument('--data_base', default='/data/zhangcl/ImageNet', type=str, help='the path of dataset')
parser.add_argument('--ft_model_path', default='/home/luojh2/.torch/models/resnet50-19c8e357.pth',
type=str, help='the path of fine tuned model')
parser.add_argument('--gpu_id', default='0,1,2,3', type=str,
help='id(s) for CUDA_VISIBLE_DEVICES')
parser.add_argument('--group_id', default=0, type=int, help='the id of compressed group, starting from 0')
parser.add_argument('--start_epoch', default=0, type=int, metavar='N',
help='manual epoch number (useful on restarts)')
parser.add_argument('--compression_rate', default=0.5, type=float, help='the percentage of 1 in compressed model')
parser.add_argument('--channel_index_range', default=20, type=int, help='the range to calculate channel index')
parser.add_argument('--print-freq', '-p', default=20, type=int,
metavar='N', help='print frequency (default: 10)')
parser.add_argument('--alpha_range', default=100, type=int, help='the range to calculate channel index')
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
best_prec1 = -1
print(args)
resnet_channel_number = [6, 8, 12, 4]
scale_factor_list = None
alpha_index = 0
threshold = 95 * np.ones(resnet_channel_number[args.group_id])
def main():
global args, best_prec1, scale_factor_list, resnet_channel_number
# Phase 1 : Data Upload
print('\n[Phase 1] : Data Preperation')
train_loader = torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-train.lmdb'), True),
batch_size=args.batch_size,
shuffle=True,
num_workers=8,
pin_memory=True)
val_loader = torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-val.lmdb'), False),
batch_size=args.batch_size,
num_workers=8,
pin_memory=True)
print('data_loader_success!')
# Phase 2 : Model setup
print('\n[Phase 2] : Model setup')
if args.group_id == 0:
model_ft = models.resnet50(True).cuda()
model_ft = torch.nn.DataParallel(model_ft)
model_param = model_ft.state_dict()
torch.save(model_param, 'checkpoint/model.pth')
model_ft = Network_FT.NetworkNew(args.group_id).cuda()
model_ft = torch.nn.DataParallel(model_ft)
cudnn.benchmark = True
print("model setup success!")
# Phase 3: fine_tune model
print('\n[Phase 3] : Model fine tune')
# define loss function (criterion) and optimizer
criterion = nn.CrossEntropyLoss().cuda()
optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model_ft.parameters()), args.lr,
momentum=0.9,
weight_decay=args.weight_decay)
tmp = np.linspace(1, 100, int(args.num_epochs * len(train_loader) / args.alpha_range))
scale_factor_list = np.ones([resnet_channel_number[args.group_id], len(tmp)])
for tmp_i in range(resnet_channel_number[args.group_id]):
scale_factor_list[tmp_i, :] = tmp.copy()
reg_lambda = 10.0 * np.ones(resnet_channel_number[args.group_id])
for epoch in range(args.start_epoch, args.num_epochs):
adjust_learning_rate(optimizer, epoch, int(args.num_epochs/2.0))
# train for one epoch
channel_index, reg_lambda = train(train_loader, model_ft, criterion, optimizer, epoch, reg_lambda)
# evaluate on validation set
prec1 = validate(val_loader, model_ft, criterion, channel_index)
# remember best prec@1 and save checkpoint
is_best = prec1 > best_prec1
if is_best:
best_prec1 = prec1
folder_path = 'checkpoint/group_' + str(args.group_id)
if not os.path.exists(folder_path):
os.makedirs(folder_path)
torch.save(model_ft.state_dict(), folder_path+'/model.pth')
if args.group_id == 3:
tmp = channel_index[0].copy()
tmp[:] = 1.0
channel_index.append(tmp.copy())
channel_index.append(tmp.copy())
torch.save(channel_index, folder_path+'/channel_index.pth')
def train(train_loader, model, criterion, optimizer, epoch, reg_lambda):
global resnet_channel_number, scale_factor_list, alpha_index, threshold
gpu_num = torch.cuda.device_count()
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to train mode
model.train()
channel_index_list = list()
channel_index_binary = list()
end = time.time()
for i, (input, target) in enumerate(train_loader):
if i % args.alpha_range == 0:
if alpha_index == scale_factor_list.shape[1]:
alpha_index = alpha_index - 1
scale_factor = scale_factor_list[:, alpha_index]
alpha_index = alpha_index + 1
model.module.set_scale_factor(scale_factor)
# measure data loading time
data_time.update(time.time() - end)
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input).cuda()
target_var = torch.autograd.Variable(target).cuda()
# compute output
output, scale_vec = model(input_var)
loss = criterion(output, target_var)
for vec_i in range(len(scale_vec)):
loss = loss + float(reg_lambda[vec_i]) * (
scale_vec[vec_i].norm(1) / float(scale_vec[vec_i].size(0)) - args.compression_rate) ** 2
# compute channel index
channel_index_sublist = list()
for vec_i in range(len(scale_vec)):
tmp = scale_vec[vec_i].data.cpu().numpy().reshape(gpu_num, -1).mean(0)
channel_index_sublist.append(tmp.copy())
if i == 0:
print('first 5 values in layer {0}: [{1:.6f}, {2:.6f}, {3:.6f}, {4:.6f}, {5:.6f}]'.format(int(vec_i),
tmp[0],
tmp[1],
tmp[2],
tmp[3],
tmp[4]))
channel_index_list.append(channel_index_sublist.copy())
if len(channel_index_list) == args.channel_index_range:
channel_index_binary = list()
for vec_i in range(len(scale_vec)):
tmp = list()
for tmp_i in range(len(channel_index_list)):
tmp_a = channel_index_list[tmp_i][vec_i]
tmp_a = (np.sign(tmp_a - 0.5) + 1) / 2.0 # to 0-1 binary
tmp.append(tmp_a)
tmp = np.array(tmp).sum(axis=0)
tmp = tmp / args.channel_index_range
tmp_value = channel_index_list[0][vec_i]
print(
'first 5 values in layer {0}: [{1:.6f}, {2:.6f}, {3:.6f}, {4:.6f}, {5:.6f}]'.format(int(vec_i),
tmp_value[0],
tmp_value[1],
tmp_value[2],
tmp_value[3],
tmp_value[4]))
channel_index = (np.sign(tmp - 0.5) + 1) / 2.0 # to 0-1 binary
channel_index_binary.append(channel_index.copy())
binary_pruning_rate = 100.0 * np.sum(channel_index == 0) / len(channel_index)
if binary_pruning_rate >= threshold[vec_i]:
scale_factor_list[vec_i, :] = scale_factor_list[vec_i, :] + 1
threshold[vec_i] = threshold[vec_i] - 5
if threshold[vec_i] < 100 - 100 * args.compression_rate:
threshold[vec_i] = 100 - 100 * args.compression_rate
print('threshold in layer %d is %d' % (int(vec_i), int(threshold[vec_i])))
two_side_rate = (np.sum(tmp_value > 0.8) + np.sum(tmp_value < 0.2)) / len(tmp_value)
if two_side_rate < 0.9 and alpha_index >= int(scale_factor_list.shape[1] / args.num_epochs):
scale_factor_list[vec_i, :] = scale_factor_list[vec_i, :] + 1
reg_lambda[vec_i] = 100.0 * np.abs(binary_pruning_rate/100.0 - 1 + args.compression_rate)
tmp[tmp == 0] = 1
channel_inconsistency = 100.0 * np.sum(tmp != 1) / len(tmp)
print(
"[{0}] pruning rate: {1:.4f}%, inconsistency: {2:.4f}%, reg_lambda: {3:.4f}, scale_factor: {4:.4f}, two_side: {5:.4f}".format(
int(vec_i), binary_pruning_rate, channel_inconsistency, reg_lambda[vec_i], scale_factor[vec_i], two_side_rate))
sys.stdout.flush()
channel_index_list = list()
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Epoch[{0}]: [{1}/{2}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
epoch, i, len(train_loader), batch_time=batch_time,
top1=top1, top5=top5))
print('+--------------------------------------------------------------------------------------------------+')
sys.stdout.flush()
return channel_index_binary, reg_lambda
def validate(val_loader, model, criterion, channel_index):
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
for i, (input, target) in enumerate(val_loader):
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input, volatile=True)
target_var = torch.autograd.Variable(target, volatile=True)
# compute output
output, _ = model(input_var, channel_index)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
i, len(val_loader), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
sys.stdout.flush()
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
return top1.avg
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, 'model_best.pth.tar')
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def adjust_learning_rate(optimizer, epoch, epoch_num):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = args.lr * (0.1 ** (epoch // epoch_num))
print('| Learning Rate = %f' % lr)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == "__main__":
main()
| 14,783 | 42.354839 | 146 | py |
AutoPruner | AutoPruner-master/ResNet50/50/evaluate_network.py | import torch
import torch.backends.cudnn as cudnn
import os
import sys
import argparse
import time
from src_code.lmdbdataset import lmdbDataset
from src_code import Network_FT
parser = argparse.ArgumentParser(description='PyTorch Digital Mammography Training')
parser.add_argument('--batch_size', default=100, type=int, help='batch size')
parser.add_argument('--data_base', default='/data/zhangcl/ImageNet', type=str, help='the path of dataset')
parser.add_argument('--gpu_id', default='1', type=str,
help='id(s) for CUDA_VISIBLE_DEVICES')
parser.add_argument('--ft_model_path', default='/home/luojh2/.torch/models/resnet50-19c8e357.pth',
type=str, help='the path of fine tuned model')
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
print(args)
# Phase 1 : Data Upload
print('\n[Phase 1] : Data Preperation')
dset_loaders = {
'train': torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-train.lmdb'), True),
batch_size=args.batch_size,
shuffle=True,
num_workers=8,
pin_memory=True),
'val': torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-val.lmdb'), False),
batch_size=args.batch_size,
num_workers=8,
pin_memory=True)
}
print('data_loader_success!')
# Phase 2 : Model setup
print('\n[Phase 2] : Model setup')
model = Network_FT.NetworkNew(0).cuda()
model = torch.nn.DataParallel(model, device_ids=range(torch.cuda.device_count()))
model.module.set_scale_factor(2.0)
cudnn.benchmark = True
# Phase 3: evaluation
def evaluate_net():
print("\n[Phase 3 : Inference on val")
criterion = torch.nn.CrossEntropyLoss().cuda()
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
for batch_idx, (input, target) in enumerate(dset_loaders['val']): # dset_loaders['val']):
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input, volatile=True)
target_var = torch.autograd.Variable(target, volatile=True)
# compute output
output = model(input_var)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
batch_idx, len(dset_loaders['val']), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
sys.stdout.flush()
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == '__main__':
evaluate_net()
| 4,037 | 31.564516 | 106 | py |
AutoPruner | AutoPruner-master/ResNet50/50/fine_tune_again.py | import argparse
import os
import shutil
import time
import sys
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
from torchvision import datasets, transforms
from src_code.lmdbdataset import lmdbDataset
from compress_model.new_model import NetworkNew_test
parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
'''parser.add_argument('data', metavar='DIR',
help='path to dataset')
'''
parser.add_argument('-j', '--workers', default=8, type=int, metavar='N',
help='number of data loading workers (default: 8)')
parser.add_argument('--epochs', default=12, type=int, metavar='N',
help='number of total epochs to run')
parser.add_argument('--start-epoch', default=0, type=int, metavar='N',
help='manual epoch number (useful on restarts)')
parser.add_argument('-b', '--batch-size', default=256, type=int,
metavar='N', help='mini-batch size (default: 128)')
parser.add_argument('--lr', '--learning-rate', default=0.001, type=float,
metavar='LR', help='initial learning rate')
parser.add_argument('--momentum', default=0.9, type=float, metavar='M',
help='momentum')
parser.add_argument('--weight-decay', '--wd', default=1e-4, type=float,
metavar='W', help='weight decay (default: 1e-4)')
parser.add_argument('--print-freq', '-p', default=10, type=int,
metavar='N', help='print frequency (default: 10)')
parser.add_argument('--resume', default='', type=str, metavar='PATH',
help='path to latest checkpoint (default: none)')
parser.add_argument('--evaluate', default=False, type=bool,
help='evaluate model on validation set')
parser.add_argument('--pretrained', dest='pretrained', action='store_true',
help='use pre-trained model')
parser.add_argument('--world-size', default=1, type=int,
help='number of distributed processes')
parser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str,
help='url used to set up distributed training')
parser.add_argument('--dist-backend', default='gloo', type=str,
help='distributed backend')
parser.add_argument('--gpu_id', default='7', type=str,
help='id(s) for CUDA_VISIBLE_DEVICES')
parser.add_argument('--data_base', default='/data/zhangcl/ImageNet', type=str, help='the path of dataset')
parser.add_argument('--load_from_lmdb', default=True, type=bool, help='load image data from lmdb or not')
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
best_prec1 = 0
print(args)
def main():
global args, best_prec1
args = parser.parse_args()
args.distributed = args.world_size > 1
if args.distributed:
dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url,
world_size=args.world_size)
# create model
# model = models.vgg16(pretrained=True)
model = NetworkNew_test('checkpoint/model.pth')
print(model)
model = torch.nn.DataParallel(model.cuda(), device_ids=range(torch.cuda.device_count()))
cudnn.benchmark = True
# define loss function (criterion) and optimizer
criterion = nn.CrossEntropyLoss().cuda()
optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), args.lr,
momentum=args.momentum,
weight_decay=args.weight_decay)
# Data loading code from lmdb
if args.load_from_lmdb:
train_loader = torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-train.lmdb'), True),
batch_size=args.batch_size,
num_workers=16,
pin_memory=True
)
print('train_loader_success!')
val_loader = torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-val.lmdb'), False),
batch_size=args.batch_size,
num_workers=8,
pin_memory=True
)
else:
traindir = os.path.join('/opt/luojh/Dataset/ImageNet/images', 'train')
valdir = os.path.join('/opt/luojh/Dataset/ImageNet/images', 'val')
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
train_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(traindir, transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])),
batch_size=args.batch_size, shuffle=True,
num_workers=args.workers, pin_memory=True)
val_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(valdir, transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])),
batch_size=args.batch_size, shuffle=False,
num_workers=args.workers, pin_memory=True)
# evaluate and train
if args.evaluate:
validate(val_loader, model, criterion)
return
for epoch in range(args.start_epoch, args.epochs):
adjust_learning_rate(optimizer, epoch)
# train for one epoch
train(train_loader, model, criterion, optimizer, epoch)
# evaluate on validation set
prec1 = validate(val_loader, model, criterion)
# remember best prec@1 and save checkpoint
is_best = prec1 > best_prec1
if is_best:
folder_path = 'checkpoint/fine_again'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
best_prec1 = max(prec1, best_prec1)
torch.save(model.state_dict(), folder_path + '/model.pth')
print('best accuracy is %.3f' % best_prec1)
def train(train_loader, model, criterion, optimizer, epoch):
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to train mode
model.train()
end = time.time()
for i, (input, target) in enumerate(train_loader):
# measure data loading time
data_time.update(time.time() - end)
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input).cuda()
target_var = torch.autograd.Variable(target).cuda()
# compute output
output = model(input_var)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Epoch: [{0}][{1}/{2}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Data {data_time.val:.3f} ({data_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
epoch, i, len(train_loader), batch_time=batch_time,
data_time=data_time, loss=losses, top1=top1, top5=top5))
sys.stdout.flush()
def validate(val_loader, model, criterion):
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
for i, (input, target) in enumerate(val_loader):
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input, volatile=True)
target_var = torch.autograd.Variable(target, volatile=True)
# compute output
output = model(input_var)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
i, len(val_loader), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
sys.stdout.flush()
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
return top1.avg
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, 'model_best.pth.tar')
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def adjust_learning_rate(optimizer, epoch):
"""Sets the learning rate to the initial LR decayed by 10 every 4 epochs"""
lr = args.lr * (0.1 ** (epoch // 4))
print('| Learning Rate = %f' % lr)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == '__main__':
main()
| 10,815 | 35.789116 | 106 | py |
AutoPruner | AutoPruner-master/ResNet50/50/tools/create_lmdb.py | # loads imagenet and writes it into one massive binary file
import os
import numpy as np
from tensorpack.dataflow import *
import sys
if __name__ == '__main__':
if len(sys.argv) < 4 :
print("Usage: python create_lmdb.py gt_file.txt root_folder target_lmdb_name")
print("gt_file.txt split by \"\t\"")
sys.exit(1)
class BinaryDataSet(RNGDataFlow):
def __init__(self,text_name,root_folder):
self.text_name = text_name
self.length = 0
self.root_folder = root_folder
with open(self.text_name,'r') as f:
self.length = len(f.readlines())
self.gt_list = []
with open(self.text_name,'r') as f:
for line in f:
now_list = line.split('\t')
fname = now_list[0]
label = int(now_list[1].strip())
self.gt_list.append((fname,label))
def size(self):
return self.length
def get_data(self):
for fname, label in self.gt_list:
with open(os.path.join(self.root_folder,fname), 'rb') as f:
jpeg = f.read()
jpeg = np.asarray(bytearray(jpeg), dtype='uint8')
yield [jpeg, label]
gt_filename = sys.argv[1]
root_folder = sys.argv[2]
name = sys.argv[3]
ds0 = BinaryDataSet(gt_filename,root_folder)
ds1 = PrefetchDataZMQ(ds0, nr_proc=1)
dftools.dump_dataflow_to_lmdb(ds1, '%s.lmdb'%name)
| 1,514 | 35.95122 | 86 | py |
AutoPruner | AutoPruner-master/ResNet50/50/tools/organize_dataset.py | """
this script is used for organize CUB200 dataset:
-- images
-- train
-- [:class 0]
-- [:class 1]
...
-- [:class n]
-- val
-- [:class 0]
-- [:class 1]
...
-- [:class n]
"""
import os
import PIL.Image
import numpy as np
import shutil
original_dataset_path = '/data/luojh/CUB_200_2011/CUB_200_2011'
dest_path = '/opt/luojh/Dataset/CUB/images'
def main():
image_path = os.path.join(original_dataset_path, 'images/')
# Format of images.txt: <image_id> <image_name>
id2name = np.genfromtxt(os.path.join(
original_dataset_path, 'images.txt'), dtype=str)
# Format of train_test_split.txt: <image_id> <is_training_image>
id2train = np.genfromtxt(os.path.join(
original_dataset_path, 'train_test_split.txt'), dtype=int)
for id_ in range(id2name.shape[0]):
image = PIL.Image.open(os.path.join(image_path, id2name[id_, 1]))
folder_name = id2name[id_, 1].split('/')[0]
if id2train[id_, 1] == 1:
# train
save_path = os.path.join(dest_path, 'train', folder_name)
if not os.path.isdir(save_path):
os.makedirs(save_path)
# Convert gray scale image to RGB image.
if image.getbands()[0] == 'L':
image = image.convert('RGB')
image.save(os.path.join(dest_path, 'train', id2name[id_, 1]))
else:
shutil.copyfile(os.path.join(image_path, id2name[id_, 1]),
os.path.join(dest_path, 'train', id2name[id_, 1]))
image.close()
else:
# test
save_path = os.path.join(dest_path, 'val', folder_name)
if not os.path.isdir(save_path):
os.makedirs(save_path)
# Convert gray scale image to RGB image.
if image.getbands()[0] == 'L':
image = image.convert('RGB')
image.save(os.path.join(dest_path, 'val', id2name[id_, 1]))
else:
shutil.copyfile(os.path.join(image_path, id2name[id_, 1]),
os.path.join(dest_path, 'val', id2name[id_, 1]))
image.close()
if __name__ == '__main__':
main()
print('finished')
| 2,295 | 31.8 | 82 | py |
AutoPruner | AutoPruner-master/ResNet50/50/src_code/my_op_fc.py | import torch
from torch.autograd import Variable
import torch.nn as nn
from torch.autograd import gradcheck
import numpy as np
class MyGAP_fc(torch.autograd.Function):
'''
Global Average Pooling with batchsize: N*4096 -> 1*4096
'''
@staticmethod
def forward(ctx, input):
ctx.save_for_backward(input)
input = torch.mean(input, dim=0, keepdim=True)
return input
@staticmethod
def backward(ctx, grad_output):
input = ctx.saved_tensors
grad_input = input[0].clone()
for i in range(grad_input.shape[0]):
grad_input[i, :] = grad_output.data / grad_input.shape[0]
return Variable(grad_input)
class MyScale_fc(torch.autograd.Function):
'''
input: x: 64*4096, scale:4096 ==> x[:, i]*scale[i]
'''
@staticmethod
def forward(self, input_data, scale_vec):
self.save_for_backward(input_data, scale_vec)
input_data2 = input_data.clone()
for i in range(scale_vec.shape[0]):
input_data2[:, i] = input_data[:, i] * scale_vec[i]
return input_data2
@staticmethod
def backward(self, grad_output):
input_data, scale_vec = self.saved_tensors
grad_input = input_data.clone()
for i in range(scale_vec.shape[0]):
grad_input[:, i] = grad_output.data[:, i] * scale_vec[i]
grad_vec = scale_vec.clone()
for i in range(scale_vec.shape[0]):
grad_vec[i] = torch.sum(grad_output.data[:, i]*input_data[:, i])
return Variable(grad_input), Variable(grad_vec)
class MyCS_fc(nn.Module):
def __init__(self, channels_num):
super(MyCS_fc, self).__init__()
self.layer_type = 'MyCS_fc'
self.fc = nn.Linear(channels_num, channels_num)
self.sigmoid = nn.Sigmoid()
def forward(self, x, scale_factor):
x_scale = MyGAP_fc.apply(x) # apply my GAP: N*4096 => 1*4096
x_scale = self.fc(x_scale) # 1*4096
x_scale = torch.squeeze(x_scale) # 4096
x_scale = x_scale * scale_factor # apply scale sigmoid
x_scale = self.sigmoid(x_scale)
if not self.training:
index = (np.sign(x_scale.data.cpu().numpy() - 0.5) + 1) / 2.0
x_scale.data = torch.FloatTensor(index).cuda()
x = MyScale_fc.apply(x, x_scale)
return x, x_scale
if __name__ == '__main__':
in_ = (Variable(torch.randn(3, 4).double(), requires_grad=True),
Variable(torch.randn(4).double(), requires_grad=True))
res = gradcheck(MyScale_fc.apply, in_, eps=1e-6, atol=1e-4)
# in_ = (Variable(torch.randn(4, 64).double(), requires_grad=True),)
# res = gradcheck(MyGAP_fc.apply, in_, eps=1e-6, atol=1e-4)
print(res)
| 2,729 | 31.117647 | 76 | py |
AutoPruner | AutoPruner-master/ResNet50/50/src_code/my_op.py | import torch
from torch.autograd import Variable
import torch.nn as nn
from torch.autograd import gradcheck
import numpy as np
import math
class MyGAP(torch.autograd.Function):
'''
Global Average Pooling with batchsize: N*512*14*14 -> 1*512*14*14
'''
@staticmethod
def forward(ctx, input):
ctx.save_for_backward(input)
input = torch.mean(input, dim=0, keepdim=True)
return input
@staticmethod
def backward(ctx, grad_output):
input = ctx.saved_tensors
grad_input = input[0].clone()
for i in range(grad_input.shape[0]):
grad_input[i, :, :, :] = grad_output.data / grad_input.shape[0]
return Variable(grad_input)
class MyScale(torch.autograd.Function):
'''
input: x: 64*512*7*7, scale:512 ==> x[:, i, :, :]*scale[i]
'''
@staticmethod
def forward(self, input_data, scale_vec):
self.save_for_backward(input_data, scale_vec)
input_data2 = input_data.clone()
for i in range(scale_vec.shape[0]):
input_data2[:, i, :, :] = input_data[:, i, :, :] * scale_vec[i]
return input_data2
@staticmethod
def backward(self, grad_output):
input_data, scale_vec = self.saved_tensors
grad_input = input_data.clone()
for i in range(scale_vec.shape[0]):
grad_input[:, i, :, :] = grad_output.data[:, i, :, :] * scale_vec[i]
grad_vec = scale_vec.clone()
for i in range(scale_vec.shape[0]):
grad_vec[i] = torch.sum(grad_output.data[:, i, :, :]*input_data[:, i, :, :])
return Variable(grad_input), Variable(grad_vec)
class MyCS(nn.Module):
def __init__(self, channels_num, activation_size=14, max_ks=2):
super(MyCS, self).__init__()
self.layer_type = 'MyCS'
self.conv = nn.Conv2d(channels_num, channels_num,
kernel_size=int(activation_size / max_ks), stride=1, padding=0)
self.map = nn.MaxPool2d(kernel_size=max_ks, stride=max_ks)
self.sigmoid = nn.Sigmoid()
n = int(activation_size / max_ks) * int(activation_size / max_ks) * channels_num
self.conv.weight.data.normal_(0, 10 * math.sqrt(2.0 / n))
def forward(self, x, scale_factor, channel_index=None):
x_scale = MyGAP.apply(x) # apply my GAP: N*512*14*14 => 1*512*14*14
x_scale = self.map(x_scale) # apply MAP: 1*512*14*14 => 1*512*7*7
x_scale = self.conv(x_scale) # 1*512*1*1
x_scale = torch.squeeze(x_scale) # 512
x_scale = x_scale * scale_factor # apply scale sigmoid
x_scale = self.sigmoid(x_scale)
if not self.training:
x_scale.data = torch.FloatTensor(channel_index).cuda()
x = MyScale.apply(x, x_scale)
return x, x_scale
if __name__ == '__main__':
# in_ = (Variable(torch.randn(1, 1, 3, 3).double(), requires_grad=True),
# Variable(torch.randn(1).double(), requires_grad=True))
# res = gradcheck(MyScale.apply, in_, eps=1e-6, atol=1e-4)
in_ = (Variable(torch.randn(2, 64, 3, 3).double(), requires_grad=True),)
res = gradcheck(MyGAP.apply, in_, eps=1e-6, atol=1e-4)
print(res)
| 3,182 | 33.225806 | 93 | py |
AutoPruner | AutoPruner-master/ResNet50/50/src_code/Network_FT.py | import torch.nn as nn
import math
import torch
from . import my_op
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, number_list, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(number_list[1], number_list[0], kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(number_list[0])
self.conv2 = nn.Conv2d(number_list[3], number_list[2], kernel_size=3, stride=stride,
padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(number_list[2])
self.conv3 = nn.Conv2d(number_list[5], number_list[4], kernel_size=1, bias=False)
self.bn3 = nn.BatchNorm2d(number_list[4])
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class Bottleneck_with_CS(nn.Module):
expansion = 4
def __init__(self, number_list, stride=1, downsample=None, ks=1, CS_id=0):
super(Bottleneck_with_CS, self).__init__()
self.conv1 = nn.Conv2d(number_list[1], number_list[0], kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(number_list[0])
self.conv2 = nn.Conv2d(number_list[3], number_list[2], kernel_size=3, stride=stride,
padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(number_list[2])
self.conv3 = nn.Conv2d(number_list[5], number_list[4], kernel_size=1, bias=False)
self.bn3 = nn.BatchNorm2d(number_list[4])
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
self.CS_id = CS_id
self.channel_index = list()
if ks == 7:
mks = 1
else:
mks = 2
self.cs1 = my_op.MyCS(number_list[0], activation_size=ks * stride, max_ks=mks)
self.cs2 = my_op.MyCS(number_list[2], activation_size=ks, max_ks=mks)
self.vec1 = None
self.vec2 = None
self.scale_factor1 = 1.0
self.scale_factor2 = 1.0
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
if self.training:
out, self.vec1 = self.cs1(out, self.scale_factor1)
else:
out, self.vec1 = self.cs1(out, self.scale_factor1, self.channel_index[2 * self.CS_id])
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
if self.training:
out, self.vec2 = self.cs2(out, self.scale_factor2)
else:
out, self.vec2 = self.cs2(out, self.scale_factor2, self.channel_index[2 * self.CS_id + 1])
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, group_id, block, layers, num_classes=1000):
old_weight = torch.load('checkpoint/model.pth')
channel_number_list = analyse_number(old_weight)
self.kernel_size = int(56 / (2**group_id))
self.inplanes = 64
self.g_id = group_id
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(channel_number_list[0], 0, block, 64, layers[0])
self.layer2 = self._make_layer(channel_number_list[1], 1, block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(channel_number_list[2], 2, block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(channel_number_list[3], 3, block, 512, layers[3], stride=2)
self.avgpool = nn.AvgPool2d(7, stride=1)
self.fc = nn.Linear(512 * block.expansion, num_classes)
# for m in self.modules():
# if isinstance(m, nn.Conv2d):
# # n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
# # m.weight.data.normal_(0, math.sqrt(2. / n))
# m.weight.data.normal_(0, math.sqrt(1.))
# # torch.nn.init.xavier_uniform(m.weight)
# elif isinstance(m, nn.BatchNorm2d):
# m.weight.data.fill_(1)
# m.bias.data.zero_()
old_weight = torch.load('checkpoint/model.pth')
my_weight = self.state_dict()
my_keys = list(my_weight.keys())
for k, v in old_weight.items():
name = ''.join(list(k)[7:])
if name in my_keys:
my_weight[name] = v
self.load_state_dict(my_weight)
def _make_layer(self, number_list, group_id, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion),
)
layers = []
if group_id == self.g_id:
layers.append(Bottleneck_with_CS(number_list[0], stride, downsample, ks=self.kernel_size, CS_id=0))
else:
layers.append(block(number_list[0], stride, downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
if group_id == self.g_id:
if self.g_id == 3 and i == blocks-1:
layers.append(block(number_list[i]))
else:
layers.append(Bottleneck_with_CS(number_list[i], ks=self.kernel_size, CS_id=i))
else:
layers.append(block(number_list[i]))
return nn.Sequential(*layers)
def forward(self, x, channel_index=None):
if not self.training:
self.set_channel_index(channel_index)
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x) # 128, 64, 56, 56
x = self.layer1(x) # 128, 64, 56, 56
x = self.layer2(x) # 128, 512, 28, 28
x = self.layer3(x) # 128, 1024, 14, 14
x = self.layer4(x) # 128, 2048, 7, 7
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
scale_vector = self.get_scale_vector()
return x, scale_vector
def set_channel_index(self, channel_index):
if self.g_id == 0:
self.layer1[0].channel_index = channel_index
self.layer1[1].channel_index = channel_index
self.layer1[2].channel_index = channel_index
elif self.g_id == 1:
self.layer2[0].channel_index = channel_index
self.layer2[1].channel_index = channel_index
self.layer2[2].channel_index = channel_index
self.layer2[3].channel_index = channel_index
elif self.g_id == 2:
self.layer3[0].channel_index = channel_index
self.layer3[1].channel_index = channel_index
self.layer3[2].channel_index = channel_index
self.layer3[3].channel_index = channel_index
self.layer3[4].channel_index = channel_index
self.layer3[5].channel_index = channel_index
else:
self.layer4[0].channel_index = channel_index
self.layer4[1].channel_index = channel_index
# self.layer4[2].channel_index = channel_index
def get_scale_vector(self):
vector_list = list()
if self.g_id == 0:
vector_list.append(self.layer1[0].vec1)
vector_list.append(self.layer1[0].vec2)
vector_list.append(self.layer1[1].vec1)
vector_list.append(self.layer1[1].vec2)
vector_list.append(self.layer1[2].vec1)
vector_list.append(self.layer1[2].vec2)
elif self.g_id == 1:
vector_list.append(self.layer2[0].vec1)
vector_list.append(self.layer2[0].vec2)
vector_list.append(self.layer2[1].vec1)
vector_list.append(self.layer2[1].vec2)
vector_list.append(self.layer2[2].vec1)
vector_list.append(self.layer2[2].vec2)
vector_list.append(self.layer2[3].vec1)
vector_list.append(self.layer2[3].vec2)
elif self.g_id == 2:
vector_list.append(self.layer3[0].vec1)
vector_list.append(self.layer3[0].vec2)
vector_list.append(self.layer3[1].vec1)
vector_list.append(self.layer3[1].vec2)
vector_list.append(self.layer3[2].vec1)
vector_list.append(self.layer3[2].vec2)
vector_list.append(self.layer3[3].vec1)
vector_list.append(self.layer3[3].vec2)
vector_list.append(self.layer3[4].vec1)
vector_list.append(self.layer3[4].vec2)
vector_list.append(self.layer3[5].vec1)
vector_list.append(self.layer3[5].vec2)
else:
vector_list.append(self.layer4[0].vec1)
vector_list.append(self.layer4[0].vec2)
vector_list.append(self.layer4[1].vec1)
vector_list.append(self.layer4[1].vec2)
# vector_list.append(self.layer4[2].vec1)
# vector_list.append(self.layer4[2].vec2)
return vector_list
def set_scale_factor(self, sf):
if self.g_id == 0:
self.layer1[0].scale_factor1 = sf[0]
self.layer1[0].scale_factor2 = sf[1]
self.layer1[1].scale_factor1 = sf[2]
self.layer1[1].scale_factor2 = sf[3]
self.layer1[2].scale_factor1 = sf[4]
self.layer1[2].scale_factor2 = sf[5]
elif self.g_id == 1:
self.layer2[0].scale_factor1 = sf[0]
self.layer2[0].scale_factor2 = sf[1]
self.layer2[1].scale_factor1 = sf[2]
self.layer2[1].scale_factor2 = sf[3]
self.layer2[2].scale_factor1 = sf[4]
self.layer2[2].scale_factor2 = sf[5]
self.layer2[3].scale_factor1 = sf[6]
self.layer2[3].scale_factor2 = sf[7]
elif self.g_id == 2:
self.layer3[0].scale_factor1 = sf[0]
self.layer3[0].scale_factor2 = sf[1]
self.layer3[1].scale_factor1 = sf[2]
self.layer3[1].scale_factor2 = sf[3]
self.layer3[2].scale_factor1 = sf[4]
self.layer3[2].scale_factor2 = sf[5]
self.layer3[3].scale_factor1 = sf[6]
self.layer3[3].scale_factor2 = sf[7]
self.layer3[4].scale_factor1 = sf[8]
self.layer3[4].scale_factor2 = sf[9]
self.layer3[5].scale_factor1 = sf[10]
self.layer3[5].scale_factor2 = sf[11]
else:
self.layer4[0].scale_factor1 = sf[0]
self.layer4[0].scale_factor2 = sf[1]
self.layer4[1].scale_factor1 = sf[2]
self.layer4[1].scale_factor2 = sf[3]
# self.layer4[2].scale_factor = sf
def analyse_number(weight):
number_list = list()
group_list = list()
layer_list = list()
old_name = '1.0.'
old_group = '1'
for k, v in weight.items():
if 'layer' in k and'conv' in k:
current_name = k.split('layer')[1].split('conv')[0]
current_group = current_name.split('.')[0]
if current_name != old_name:
old_name = current_name
group_list.append(layer_list.copy())
layer_list = list()
if current_group != old_group:
old_group = current_group
number_list.append(group_list.copy())
group_list = list()
layer_list.append(v.size()[0])
layer_list.append(v.size()[1])
group_list.append(layer_list.copy())
number_list.append(group_list.copy())
return number_list
def NetworkNew(group_id):
model = ResNet(group_id, Bottleneck, [3, 4, 6, 3])
return model
| 12,489 | 37.549383 | 111 | py |
AutoPruner | AutoPruner-master/ResNet50/50/src_code/lmdbdataset.py | import cv2
import numpy as np
import torchvision.transforms as transforms
import lmdb
import msgpack
from torch.utils.data import Dataset
from PIL import Image
class lmdbDataset(Dataset):
def __init__(self, location, is_train):
self.env = lmdb.open(location, subdir=False, max_readers=1, readonly=True, lock=False, readahead=False,
meminit=False)
self.txn = self.env.begin(write=False)
self.length = self.txn.stat()['entries']
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
# train data augment
if is_train:
self.transform = transforms.Compose([
transforms.Resize(256),
transforms.RandomCrop((224, 224)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])
# test data augment
else:
self.transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])
'''
for key,data in self.txn.cursor():
now_data = msgpack.loads(data,raw=False)
data_img = now_data[0]
label = now_data[1]
now_arr = np.frombuffer(data_img[b'data'],dtype=np.uint8)
print(now_arr)
image_content = cv2.imdecode(now_arr, cv2.IMREAD_COLOR)
print(image_content.shape)
#print(type(_))
break
'''
def __len__(self):
return self.length - 1
def __getitem__(self, index):
new_index = str(index).encode()
data = self.txn.get(new_index)
now_data = msgpack.loads(data, raw=False)
data_img = now_data[0]
label = now_data[1]
now_arr = np.frombuffer(data_img[b'data'], dtype=np.uint8)
image_content = cv2.imdecode(now_arr, cv2.IMREAD_COLOR)
image_content = cv2.cvtColor(image_content, cv2.COLOR_BGR2RGB)
image_content = Image.fromarray(image_content)
image_content = self.transform(image_content)
return image_content, label
if __name__ == '__main__':
temp_dataset = lmdbDataset('indoor67.lmdb', True)
print(temp_dataset[0])
#print(i)
#assert temp_dataset[i][0] is not None | 2,431 | 34.246377 | 111 | py |
AutoPruner | AutoPruner-master/ResNet50/50/compress_model/new_model.py | import torch.nn as nn
import torch
import numpy as np
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, number_list, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(number_list[1], number_list[0], kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(number_list[0])
self.conv2 = nn.Conv2d(number_list[3], number_list[2], kernel_size=3, stride=stride,
padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(number_list[2])
self.conv3 = nn.Conv2d(number_list[5], number_list[4], kernel_size=1, bias=False)
self.bn3 = nn.BatchNorm2d(number_list[4])
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, group_id, block, layers, num_classes=1000):
folder_path = '../checkpoint/group_' + str(group_id)
old_weight = torch.load(folder_path+'/model.pth')
channel_index = torch.load(folder_path+'/channel_index.pth')
channel_number_list = analyse_number(old_weight)
for i in range(int(len(channel_index)/2)):
new_num = np.where(channel_index[2 * i] != 0)[0]
new_num_1 = int(new_num.shape[0])
new_num = np.where(channel_index[2 * i + 1] != 0)[0]
new_num_2 = int(new_num.shape[0])
channel_number_list[group_id][i][0] = new_num_1
channel_number_list[group_id][i][2] = new_num_2
channel_number_list[group_id][i][3] = new_num_1
channel_number_list[group_id][i][5] = new_num_2
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(channel_number_list[0], block, 64, layers[0])
self.layer2 = self._make_layer(channel_number_list[1], block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(channel_number_list[2], block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(channel_number_list[3], block, 512, layers[3], stride=2)
self.avgpool = nn.AvgPool2d(7, stride=1)
self.fc = nn.Linear(512 * block.expansion, num_classes)
my_weight = self.state_dict()
ci_count = 0
ci_1 = 0
ci_2 = 0
for k, v in my_weight.items():
name = 'module.' + k
if 'layer'+str(group_id+1) in name and 'downsample' not in name:
name_tmp = name.split('.')
if '1' in name_tmp[3]:
if 'conv' in name:
ci_1 = torch.cuda.LongTensor(np.where(channel_index[ci_count] != 0)[0])
ci_count += 1
my_weight[k] = old_weight[name][ci_1, :, :, :]
else:
my_weight[k] = old_weight[name][ci_1]
elif '2' in name_tmp[3]:
if 'conv' in name:
ci_2 = torch.cuda.LongTensor(np.where(channel_index[ci_count] != 0)[0])
ci_count += 1
my_weight[k] = old_weight[name][ci_2, :, :, :]
my_weight[k] = my_weight[k][:, ci_1, :, :]
else:
my_weight[k] = old_weight[name][ci_2]
elif '3' in name_tmp[3]:
if 'conv' in name:
my_weight[k] = old_weight[name][:, ci_2, :, :]
else:
my_weight[k] = old_weight[name]
else:
print('error!')
else:
my_weight[k] = old_weight[name]
self.load_state_dict(my_weight)
def _make_layer(self, number_list, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(number_list[0], stride, downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(number_list[i]))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
def analyse_number(weight):
number_list = list()
group_list = list()
layer_list = list()
old_name = '1.0.'
old_group = '1'
for k, v in weight.items():
if 'layer' in k and'conv' in k and 'cs' not in k:
current_name = k.split('layer')[1].split('conv')[0]
current_group = current_name.split('.')[0]
if current_name != old_name:
old_name = current_name
group_list.append(layer_list.copy())
layer_list = list()
if current_group != old_group:
old_group = current_group
number_list.append(group_list.copy())
group_list = list()
layer_list.append(v.size()[0])
layer_list.append(v.size()[1])
group_list.append(layer_list.copy())
number_list.append(group_list.copy())
return number_list
def NetworkNew(group_id):
model = ResNet(group_id, Bottleneck, [3, 4, 6, 3])
return model
class ResNet_test(nn.Module):
def __init__(self, model_path, block, layers, num_classes=1000):
old_weight = torch.load(model_path)
channel_number_list = analyse_number(old_weight)
self.inplanes = 64
super(ResNet_test, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(channel_number_list[0], block, 64, layers[0])
self.layer2 = self._make_layer(channel_number_list[1], block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(channel_number_list[2], block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(channel_number_list[3], block, 512, layers[3], stride=2)
self.avgpool = nn.AvgPool2d(7, stride=1)
self.fc = nn.Linear(512 * block.expansion, num_classes)
my_weight = self.state_dict()
for k, v in my_weight.items():
name = 'module.' + k
my_weight[k] = old_weight[name]
self.load_state_dict(my_weight)
def _make_layer(self, number_list, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(number_list[0], stride, downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(number_list[i]))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
def NetworkNew_test(model_path):
model = ResNet_test(model_path, Bottleneck, [3, 4, 6, 3])
return model
| 8,768 | 35.235537 | 95 | py |
AutoPruner | AutoPruner-master/ResNet50/50/compress_model/compress_model.py | import torch
from new_model import NetworkNew
import argparse
import torch.backends.cudnn as cudnn
parser = argparse.ArgumentParser(description='PyTorch Digital Mammography Training')
parser.add_argument('--group_id', default=0, type=int, help='the id of compressed layer, starting from 0')
args = parser.parse_args()
print(args)
def main():
# 1. create compressed model
vgg16_new = NetworkNew(group_id=args.group_id)
# Phase 2 : Model setup
vgg16_new = vgg16_new.cuda()
vgg16_new = torch.nn.DataParallel(vgg16_new.cuda(), device_ids=range(torch.cuda.device_count()))
cudnn.benchmark = True
new_model_param = vgg16_new.state_dict()
torch.save(new_model_param, '../checkpoint/model.pth')
print('Finished!')
if __name__ == '__main__':
main()
| 786 | 28.148148 | 106 | py |
AutoPruner | AutoPruner-master/ResNet50/50/compress_model/evaluate_net.py | import torch
from new_model import NetworkNew_test
import argparse
import torch.backends.cudnn as cudnn
import os
import sys
import time
sys.path.append('../')
from src_code.lmdbdataset import lmdbDataset
parser = argparse.ArgumentParser(description='PyTorch Digital Mammography Training')
parser.add_argument('--batch_size', default=100, type=int, help='batch size')
parser.add_argument('--data_base', default='/data/zhangcl/ImageNet', type=str, help='the path of dataset')
parser.add_argument('--gpu_id', default='1', type=str,
help='id(s) for CUDA_VISIBLE_DEVICES')
args = parser.parse_args()
print(args)
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
def evaluate():
# Phase 1: load model
model = NetworkNew_test('../checkpoint/model.pth')
# Phase 2 : Model setup
model = model.cuda()
model = torch.nn.DataParallel(model.cuda(), device_ids=range(torch.cuda.device_count()))
cudnn.benchmark = True
# Phase 2 : Data Upload
print('\n[Phase 2] : Data Preperation')
dset_loaders = {
'train': torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-train.lmdb'), True),
batch_size=args.batch_size,
shuffle=True,
num_workers=8,
pin_memory=True),
'val': torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-val.lmdb'), False),
batch_size=args.batch_size,
num_workers=8,
pin_memory=True)
}
print('data_loader_success!')
# Phase 3: Validation
print("\n[Phase 3 : Inference on val")
criterion = torch.nn.CrossEntropyLoss().cuda()
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
for batch_idx, (input, target) in enumerate(dset_loaders['val']): # dset_loaders['val']):
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input, volatile=True)
target_var = torch.autograd.Variable(target, volatile=True)
# compute output
output = model(input_var)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
batch_idx, len(dset_loaders['val']), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
sys.stdout.flush()
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == '__main__':
evaluate()
| 3,966 | 31.516393 | 106 | py |
AutoPruner | AutoPruner-master/ResNet50/30/fine_tune_compressed_model.py | import argparse
import os
import shutil
import time
import sys
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
from torchvision import datasets, transforms
from src_code.lmdbdataset import lmdbDataset
from compress_model.new_model import NetworkNew_test
parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
'''parser.add_argument('data', metavar='DIR',
help='path to dataset')
'''
parser.add_argument('-j', '--workers', default=8, type=int, metavar='N',
help='number of data loading workers (default: 8)')
parser.add_argument('--epochs', default=30, type=int, metavar='N',
help='number of total epochs to run')
parser.add_argument('--start-epoch', default=0, type=int, metavar='N',
help='manual epoch number (useful on restarts)')
parser.add_argument('-b', '--batch-size', default=256, type=int,
metavar='N', help='mini-batch size (default: 128)')
parser.add_argument('--lr', '--learning-rate', default=0.001, type=float,
metavar='LR', help='initial learning rate')
parser.add_argument('--momentum', default=0.9, type=float, metavar='M',
help='momentum')
parser.add_argument('--weight-decay', '--wd', default=1e-4, type=float,
metavar='W', help='weight decay (default: 1e-4)')
parser.add_argument('--print-freq', '-p', default=10, type=int,
metavar='N', help='print frequency (default: 10)')
parser.add_argument('--resume', default='', type=str, metavar='PATH',
help='path to latest checkpoint (default: none)')
parser.add_argument('--evaluate', default=False, type=bool,
help='evaluate model on validation set')
parser.add_argument('--pretrained', dest='pretrained', action='store_true',
help='use pre-trained model')
parser.add_argument('--world-size', default=1, type=int,
help='number of distributed processes')
parser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str,
help='url used to set up distributed training')
parser.add_argument('--dist-backend', default='gloo', type=str,
help='distributed backend')
parser.add_argument('--gpu_id', default='7', type=str,
help='id(s) for CUDA_VISIBLE_DEVICES')
parser.add_argument('--data_base', default='/data/zhangcl/ImageNet', type=str, help='the path of dataset')
parser.add_argument('--load_from_lmdb', default=True, type=bool, help='load image data from lmdb or not')
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
best_prec1 = 0
print(args)
def main():
global args, best_prec1
args = parser.parse_args()
args.distributed = args.world_size > 1
if args.distributed:
dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url,
world_size=args.world_size)
# create model
# model = models.vgg16(pretrained=True)
model = NetworkNew_test('checkpoint/model.pth')
print(model)
model = torch.nn.DataParallel(model.cuda(), device_ids=range(torch.cuda.device_count()))
cudnn.benchmark = True
# define loss function (criterion) and optimizer
criterion = nn.CrossEntropyLoss().cuda()
optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), args.lr,
momentum=args.momentum,
weight_decay=args.weight_decay)
# Data loading code from lmdb
if args.load_from_lmdb:
train_loader = torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-train.lmdb'), True),
batch_size=args.batch_size,
shuffle=True,
num_workers=8,
pin_memory=True
)
print('train_loader_success!')
val_loader = torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-val.lmdb'), False),
batch_size=args.batch_size,
num_workers=8,
pin_memory=True
)
else:
traindir = os.path.join('/opt/luojh/Dataset/ImageNet/images', 'train')
valdir = os.path.join('/opt/luojh/Dataset/ImageNet/images', 'val')
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
train_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(traindir, transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])),
batch_size=args.batch_size, shuffle=True,
num_workers=args.workers, pin_memory=True)
val_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(valdir, transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])),
batch_size=args.batch_size, shuffle=False,
num_workers=args.workers, pin_memory=True)
# evaluate and train
if args.evaluate:
validate(val_loader, model, criterion)
return
for epoch in range(args.start_epoch, args.epochs):
adjust_learning_rate(optimizer, epoch, int(args.epochs/3.0))
# train for one epoch
train(train_loader, model, criterion, optimizer, epoch)
# evaluate on validation set
prec1 = validate(val_loader, model, criterion)
# remember best prec@1 and save checkpoint
is_best = prec1 > best_prec1
best_prec1 = max(prec1, best_prec1)
if is_best:
folder_path = 'checkpoint/fine_tune'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
torch.save(model.state_dict(), folder_path + '/model.pth')
print('best acc is %.3f' % best_prec1)
def train(train_loader, model, criterion, optimizer, epoch):
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to train mode
model.train()
end = time.time()
for i, (input, target) in enumerate(train_loader):
# measure data loading time
data_time.update(time.time() - end)
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input).cuda()
target_var = torch.autograd.Variable(target).cuda()
# compute output
output = model(input_var)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Epoch: [{0}][{1}/{2}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Data {data_time.val:.3f} ({data_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
epoch, i, len(train_loader), batch_time=batch_time,
data_time=data_time, loss=losses, top1=top1, top5=top5))
sys.stdout.flush()
def validate(val_loader, model, criterion):
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
for i, (input, target) in enumerate(val_loader):
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input, volatile=True)
target_var = torch.autograd.Variable(target, volatile=True)
# compute output
output = model(input_var)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
i, len(val_loader), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
sys.stdout.flush()
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
return top1.avg
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, 'model_best.pth.tar')
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def adjust_learning_rate(optimizer, epoch, epoch_num):
"""Sets the learning rate to the initial LR decayed by 10 every 4 epochs"""
lr = args.lr * (0.1 ** (epoch // epoch_num))
print('| Learning Rate = %f' % lr)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == '__main__':
main()
| 10,872 | 35.733108 | 106 | py |
AutoPruner | AutoPruner-master/ResNet50/30/main.py | # ************************************************************
# Author : Bumsoo Kim, 2017
# Github : https://github.com/meliketoy/fine-tuning.pytorch
#
# Korea University, Data-Mining Lab
# Deep Convolutional Network Fine tuning Implementation
#
# Description : main.py
# The main code for training classification networks.
# ***********************************************************
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import time
import os
import sys
import argparse
import numpy as np
import shutil
import math
from torchvision import models
from src_code import Network_FT
from src_code.lmdbdataset import lmdbDataset
parser = argparse.ArgumentParser(description='PyTorch Digital Mammography Training')
parser.add_argument('--lr', default=1e-3, type=float, help='learning rate')
parser.add_argument('--weight_decay', default=5e-4, type=float, help='weight decay')
parser.add_argument('--batch_size', default=256, type=int, help='batch size')
parser.add_argument('--num_epochs', default=8, type=int, help='number of training epochs')
parser.add_argument('--lr_decay_epoch', default=10, type=int, help='learning rate decay epoch')
parser.add_argument('--data_base', default='/data/zhangcl/ImageNet', type=str, help='the path of dataset')
parser.add_argument('--ft_model_path', default='/home/luojh2/.torch/models/resnet50-19c8e357.pth',
type=str, help='the path of fine tuned model')
parser.add_argument('--gpu_id', default='0,1,2,3', type=str,
help='id(s) for CUDA_VISIBLE_DEVICES')
parser.add_argument('--group_id', default=0, type=int, help='the id of compressed group, starting from 0')
parser.add_argument('--start_epoch', default=0, type=int, metavar='N',
help='manual epoch number (useful on restarts)')
parser.add_argument('--compression_rate', default=0.3, type=float, help='the percentage of 1 in compressed model')
parser.add_argument('--channel_index_range', default=20, type=int, help='the range to calculate channel index')
parser.add_argument('--print-freq', '-p', default=20, type=int,
metavar='N', help='print frequency (default: 10)')
parser.add_argument('--alpha_range', default=100, type=int, help='the range to calculate channel index')
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
best_prec1 = -1
print(args)
resnet_channel_number = [6, 8, 12, 4]
scale_factor_list = None
alpha_index = 0
threshold = 95 * np.ones(resnet_channel_number[args.group_id])
def main():
global args, best_prec1, scale_factor_list, resnet_channel_number
# Phase 1 : Data Upload
print('\n[Phase 1] : Data Preperation')
train_loader = torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-train.lmdb'), True),
batch_size=args.batch_size,
shuffle=True,
num_workers=8,
pin_memory=True)
val_loader = torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-val.lmdb'), False),
batch_size=args.batch_size,
num_workers=8,
pin_memory=True)
print('data_loader_success!')
# Phase 2 : Model setup
print('\n[Phase 2] : Model setup')
if args.group_id == 0:
model_ft = models.resnet50(True).cuda()
model_ft = torch.nn.DataParallel(model_ft)
model_param = model_ft.state_dict()
torch.save(model_param, 'checkpoint/model.pth')
model_ft = Network_FT.NetworkNew(args.group_id).cuda()
model_ft = torch.nn.DataParallel(model_ft)
cudnn.benchmark = True
print("model setup success!")
# Phase 3: fine_tune model
print('\n[Phase 3] : Model fine tune')
# define loss function (criterion) and optimizer
criterion = nn.CrossEntropyLoss().cuda()
optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model_ft.parameters()), args.lr,
momentum=0.9,
weight_decay=args.weight_decay)
tmp = np.linspace(1, 100, int(args.num_epochs * len(train_loader) / args.alpha_range))
scale_factor_list = np.ones([resnet_channel_number[args.group_id], len(tmp)])
for tmp_i in range(resnet_channel_number[args.group_id]):
scale_factor_list[tmp_i, :] = tmp.copy()
reg_lambda = 10.0 * np.ones(resnet_channel_number[args.group_id])
for epoch in range(args.start_epoch, args.num_epochs):
adjust_learning_rate(optimizer, epoch, int(args.num_epochs/2.0))
# train for one epoch
channel_index, reg_lambda = train(train_loader, model_ft, criterion, optimizer, epoch, reg_lambda)
# evaluate on validation set
prec1 = validate(val_loader, model_ft, criterion, channel_index)
# remember best prec@1 and save checkpoint
is_best = prec1 > best_prec1
if is_best:
best_prec1 = prec1
folder_path = 'checkpoint/group_' + str(args.group_id)
if not os.path.exists(folder_path):
os.makedirs(folder_path)
torch.save(model_ft.state_dict(), folder_path+'/model.pth')
if args.group_id == 3:
tmp = channel_index[0].copy()
tmp[:] = 1.0
channel_index.append(tmp.copy())
channel_index.append(tmp.copy())
torch.save(channel_index, folder_path+'/channel_index.pth')
def train(train_loader, model, criterion, optimizer, epoch, reg_lambda):
global resnet_channel_number, scale_factor_list, alpha_index, threshold
gpu_num = torch.cuda.device_count()
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to train mode
model.train()
channel_index_list = list()
channel_index_binary = list()
end = time.time()
for i, (input, target) in enumerate(train_loader):
if i % args.alpha_range == 0:
if alpha_index == scale_factor_list.shape[1]:
alpha_index = alpha_index - 1
scale_factor = scale_factor_list[:, alpha_index]
alpha_index = alpha_index + 1
model.module.set_scale_factor(scale_factor)
# measure data loading time
data_time.update(time.time() - end)
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input).cuda()
target_var = torch.autograd.Variable(target).cuda()
# compute output
output, scale_vec = model(input_var)
loss = criterion(output, target_var)
for vec_i in range(len(scale_vec)):
loss = loss + float(reg_lambda[vec_i]) * (
scale_vec[vec_i].norm(1) / float(scale_vec[vec_i].size(0)) - args.compression_rate) ** 2
# compute channel index
channel_index_sublist = list()
for vec_i in range(len(scale_vec)):
tmp = scale_vec[vec_i].data.cpu().numpy().reshape(gpu_num, -1).mean(0)
channel_index_sublist.append(tmp.copy())
if i == 0:
print('first 5 values in layer {0}: [{1:.6f}, {2:.6f}, {3:.6f}, {4:.6f}, {5:.6f}]'.format(int(vec_i),
tmp[0],
tmp[1],
tmp[2],
tmp[3],
tmp[4]))
channel_index_list.append(channel_index_sublist.copy())
if len(channel_index_list) == args.channel_index_range:
channel_index_binary = list()
for vec_i in range(len(scale_vec)):
tmp = list()
for tmp_i in range(len(channel_index_list)):
tmp_a = channel_index_list[tmp_i][vec_i]
tmp_a = (np.sign(tmp_a - 0.5) + 1) / 2.0 # to 0-1 binary
tmp.append(tmp_a)
tmp = np.array(tmp).sum(axis=0)
tmp = tmp / args.channel_index_range
tmp_value = channel_index_list[0][vec_i]
print(
'first 5 values in layer {0}: [{1:.6f}, {2:.6f}, {3:.6f}, {4:.6f}, {5:.6f}]'.format(int(vec_i),
tmp_value[0],
tmp_value[1],
tmp_value[2],
tmp_value[3],
tmp_value[4]))
channel_index = (np.sign(tmp - 0.5) + 1) / 2.0 # to 0-1 binary
channel_index_binary.append(channel_index.copy())
binary_pruning_rate = 100.0 * np.sum(channel_index == 0) / len(channel_index)
if binary_pruning_rate >= threshold[vec_i]:
scale_factor_list[vec_i, :] = scale_factor_list[vec_i, :] + 1
threshold[vec_i] = threshold[vec_i] - 5
if threshold[vec_i] < 100 - 100 * args.compression_rate:
threshold[vec_i] = 100 - 100 * args.compression_rate
print('threshold in layer %d is %d' % (int(vec_i), int(threshold[vec_i])))
two_side_rate = (np.sum(tmp_value > 0.8) + np.sum(tmp_value < 0.2)) / len(tmp_value)
if two_side_rate < 0.9 and alpha_index >= 50:
scale_factor_list[vec_i, :] = scale_factor_list[vec_i, :] + 1
reg_lambda[vec_i] = 100.0 * np.abs(binary_pruning_rate/100.0 - 1 + args.compression_rate)
tmp[tmp == 0] = 1
channel_inconsistency = 100.0 * np.sum(tmp != 1) / len(tmp)
print(
"[{0}] pruning rate: {1:.4f}%, inconsistency: {2:.4f}%, reg_lambda: {3:.4f}, scale_factor: {4:.4f}, two_side: {5:.4f}".format(
int(vec_i), binary_pruning_rate, channel_inconsistency, reg_lambda[vec_i], scale_factor[vec_i],
two_side_rate))
sys.stdout.flush()
channel_index_list = list()
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Epoch[{0}]: [{1}/{2}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
epoch, i, len(train_loader), batch_time=batch_time,
top1=top1, top5=top5))
print('+--------------------------------------------------------------------------------------------------+')
sys.stdout.flush()
return channel_index_binary, reg_lambda
def validate(val_loader, model, criterion, channel_index):
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
for i, (input, target) in enumerate(val_loader):
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input, volatile=True)
target_var = torch.autograd.Variable(target, volatile=True)
# compute output
output, _ = model(input_var, channel_index)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
i, len(val_loader), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
sys.stdout.flush()
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
return top1.avg
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, 'model_best.pth.tar')
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def adjust_learning_rate(optimizer, epoch, epoch_num):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = args.lr * (0.1 ** (epoch // epoch_num))
print('| Learning Rate = %f' % lr)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == "__main__":
main()
| 14,760 | 42.160819 | 146 | py |
AutoPruner | AutoPruner-master/ResNet50/30/evaluate_network.py | import torch
import torch.backends.cudnn as cudnn
import os
import sys
import argparse
import time
from src_code.lmdbdataset import lmdbDataset
from src_code import Network_FT
parser = argparse.ArgumentParser(description='PyTorch Digital Mammography Training')
parser.add_argument('--batch_size', default=100, type=int, help='batch size')
parser.add_argument('--data_base', default='/data/zhangcl/ImageNet', type=str, help='the path of dataset')
parser.add_argument('--gpu_id', default='1', type=str,
help='id(s) for CUDA_VISIBLE_DEVICES')
parser.add_argument('--ft_model_path', default='/home/luojh2/.torch/models/resnet50-19c8e357.pth',
type=str, help='the path of fine tuned model')
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
print(args)
# Phase 1 : Data Upload
print('\n[Phase 1] : Data Preperation')
dset_loaders = {
'train': torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-train.lmdb'), True),
batch_size=args.batch_size,
shuffle=True,
num_workers=8,
pin_memory=True),
'val': torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-val.lmdb'), False),
batch_size=args.batch_size,
num_workers=8,
pin_memory=True)
}
print('data_loader_success!')
# Phase 2 : Model setup
print('\n[Phase 2] : Model setup')
model = Network_FT.NetworkNew(0).cuda()
model = torch.nn.DataParallel(model, device_ids=range(torch.cuda.device_count()))
model.module.set_scale_factor(2.0)
cudnn.benchmark = True
# Phase 3: evaluation
def evaluate_net():
print("\n[Phase 3 : Inference on val")
criterion = torch.nn.CrossEntropyLoss().cuda()
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
for batch_idx, (input, target) in enumerate(dset_loaders['val']): # dset_loaders['val']):
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input, volatile=True)
target_var = torch.autograd.Variable(target, volatile=True)
# compute output
output = model(input_var)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
batch_idx, len(dset_loaders['val']), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
sys.stdout.flush()
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == '__main__':
evaluate_net()
| 4,037 | 31.564516 | 106 | py |
AutoPruner | AutoPruner-master/ResNet50/30/fine_tune_again.py | import argparse
import os
import shutil
import time
import sys
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
from torchvision import datasets, transforms
from src_code.lmdbdataset import lmdbDataset
from compress_model.new_model import NetworkNew_test
parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
'''parser.add_argument('data', metavar='DIR',
help='path to dataset')
'''
parser.add_argument('-j', '--workers', default=8, type=int, metavar='N',
help='number of data loading workers (default: 8)')
parser.add_argument('--epochs', default=12, type=int, metavar='N',
help='number of total epochs to run')
parser.add_argument('--start-epoch', default=0, type=int, metavar='N',
help='manual epoch number (useful on restarts)')
parser.add_argument('-b', '--batch-size', default=256, type=int,
metavar='N', help='mini-batch size (default: 128)')
parser.add_argument('--lr', '--learning-rate', default=0.001, type=float,
metavar='LR', help='initial learning rate')
parser.add_argument('--momentum', default=0.9, type=float, metavar='M',
help='momentum')
parser.add_argument('--weight-decay', '--wd', default=1e-4, type=float,
metavar='W', help='weight decay (default: 1e-4)')
parser.add_argument('--print-freq', '-p', default=10, type=int,
metavar='N', help='print frequency (default: 10)')
parser.add_argument('--resume', default='', type=str, metavar='PATH',
help='path to latest checkpoint (default: none)')
parser.add_argument('--evaluate', default=False, type=bool,
help='evaluate model on validation set')
parser.add_argument('--pretrained', dest='pretrained', action='store_true',
help='use pre-trained model')
parser.add_argument('--world-size', default=1, type=int,
help='number of distributed processes')
parser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str,
help='url used to set up distributed training')
parser.add_argument('--dist-backend', default='gloo', type=str,
help='distributed backend')
parser.add_argument('--gpu_id', default='7', type=str,
help='id(s) for CUDA_VISIBLE_DEVICES')
parser.add_argument('--data_base', default='/data/zhangcl/ImageNet', type=str, help='the path of dataset')
parser.add_argument('--load_from_lmdb', default=True, type=bool, help='load image data from lmdb or not')
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
best_prec1 = 0
print(args)
def main():
global args, best_prec1
args = parser.parse_args()
args.distributed = args.world_size > 1
if args.distributed:
dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url,
world_size=args.world_size)
# create model
# model = models.vgg16(pretrained=True)
model = NetworkNew_test('checkpoint/model.pth')
print(model)
model = torch.nn.DataParallel(model.cuda(), device_ids=range(torch.cuda.device_count()))
cudnn.benchmark = True
# define loss function (criterion) and optimizer
criterion = nn.CrossEntropyLoss().cuda()
optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), args.lr,
momentum=args.momentum,
weight_decay=args.weight_decay)
# Data loading code from lmdb
if args.load_from_lmdb:
train_loader = torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-train.lmdb'), True),
batch_size=args.batch_size,
num_workers=8,
pin_memory=True
)
print('train_loader_success!')
val_loader = torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-val.lmdb'), False),
batch_size=args.batch_size,
num_workers=8,
pin_memory=True
)
else:
traindir = os.path.join('/opt/luojh/Dataset/ImageNet/images', 'train')
valdir = os.path.join('/opt/luojh/Dataset/ImageNet/images', 'val')
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
train_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(traindir, transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])),
batch_size=args.batch_size, shuffle=True,
num_workers=args.workers, pin_memory=True)
val_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(valdir, transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])),
batch_size=args.batch_size, shuffle=False,
num_workers=args.workers, pin_memory=True)
# evaluate and train
if args.evaluate:
validate(val_loader, model, criterion)
return
for epoch in range(args.start_epoch, args.epochs):
adjust_learning_rate(optimizer, epoch)
# train for one epoch
train(train_loader, model, criterion, optimizer, epoch)
# evaluate on validation set
prec1 = validate(val_loader, model, criterion)
# remember best prec@1 and save checkpoint
is_best = prec1 > best_prec1
if is_best:
folder_path = 'checkpoint/fine_again'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
best_prec1 = max(prec1, best_prec1)
torch.save(model.state_dict(), folder_path + '/model.pth')
print('best accuracy is %.3f' % best_prec1)
def train(train_loader, model, criterion, optimizer, epoch):
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to train mode
model.train()
end = time.time()
for i, (input, target) in enumerate(train_loader):
# measure data loading time
data_time.update(time.time() - end)
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input).cuda()
target_var = torch.autograd.Variable(target).cuda()
# compute output
output = model(input_var)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Epoch: [{0}][{1}/{2}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Data {data_time.val:.3f} ({data_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
epoch, i, len(train_loader), batch_time=batch_time,
data_time=data_time, loss=losses, top1=top1, top5=top5))
sys.stdout.flush()
def validate(val_loader, model, criterion):
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
for i, (input, target) in enumerate(val_loader):
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input, volatile=True)
target_var = torch.autograd.Variable(target, volatile=True)
# compute output
output = model(input_var)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
i, len(val_loader), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
sys.stdout.flush()
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
return top1.avg
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, 'model_best.pth.tar')
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def adjust_learning_rate(optimizer, epoch):
"""Sets the learning rate to the initial LR decayed by 10 every 4 epochs"""
lr = args.lr * (0.1 ** (epoch // 4))
print('| Learning Rate = %f' % lr)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == '__main__':
main()
| 10,814 | 35.785714 | 106 | py |
AutoPruner | AutoPruner-master/ResNet50/30/tools/create_lmdb.py | # loads imagenet and writes it into one massive binary file
import os
import numpy as np
from tensorpack.dataflow import *
import sys
if __name__ == '__main__':
if len(sys.argv) < 4 :
print("Usage: python create_lmdb.py gt_file.txt root_folder target_lmdb_name")
print("gt_file.txt split by \"\t\"")
sys.exit(1)
class BinaryDataSet(RNGDataFlow):
def __init__(self,text_name,root_folder):
self.text_name = text_name
self.length = 0
self.root_folder = root_folder
with open(self.text_name,'r') as f:
self.length = len(f.readlines())
self.gt_list = []
with open(self.text_name,'r') as f:
for line in f:
now_list = line.split('\t')
fname = now_list[0]
label = int(now_list[1].strip())
self.gt_list.append((fname,label))
def size(self):
return self.length
def get_data(self):
for fname, label in self.gt_list:
with open(os.path.join(self.root_folder,fname), 'rb') as f:
jpeg = f.read()
jpeg = np.asarray(bytearray(jpeg), dtype='uint8')
yield [jpeg, label]
gt_filename = sys.argv[1]
root_folder = sys.argv[2]
name = sys.argv[3]
ds0 = BinaryDataSet(gt_filename,root_folder)
ds1 = PrefetchDataZMQ(ds0, nr_proc=1)
dftools.dump_dataflow_to_lmdb(ds1, '%s.lmdb'%name)
| 1,514 | 35.95122 | 86 | py |
AutoPruner | AutoPruner-master/ResNet50/30/tools/organize_dataset.py | """
this script is used for organize CUB200 dataset:
-- images
-- train
-- [:class 0]
-- [:class 1]
...
-- [:class n]
-- val
-- [:class 0]
-- [:class 1]
...
-- [:class n]
"""
import os
import PIL.Image
import numpy as np
import shutil
original_dataset_path = '/data/luojh/CUB_200_2011/CUB_200_2011'
dest_path = '/opt/luojh/Dataset/CUB/images'
def main():
image_path = os.path.join(original_dataset_path, 'images/')
# Format of images.txt: <image_id> <image_name>
id2name = np.genfromtxt(os.path.join(
original_dataset_path, 'images.txt'), dtype=str)
# Format of train_test_split.txt: <image_id> <is_training_image>
id2train = np.genfromtxt(os.path.join(
original_dataset_path, 'train_test_split.txt'), dtype=int)
for id_ in range(id2name.shape[0]):
image = PIL.Image.open(os.path.join(image_path, id2name[id_, 1]))
folder_name = id2name[id_, 1].split('/')[0]
if id2train[id_, 1] == 1:
# train
save_path = os.path.join(dest_path, 'train', folder_name)
if not os.path.isdir(save_path):
os.makedirs(save_path)
# Convert gray scale image to RGB image.
if image.getbands()[0] == 'L':
image = image.convert('RGB')
image.save(os.path.join(dest_path, 'train', id2name[id_, 1]))
else:
shutil.copyfile(os.path.join(image_path, id2name[id_, 1]),
os.path.join(dest_path, 'train', id2name[id_, 1]))
image.close()
else:
# test
save_path = os.path.join(dest_path, 'val', folder_name)
if not os.path.isdir(save_path):
os.makedirs(save_path)
# Convert gray scale image to RGB image.
if image.getbands()[0] == 'L':
image = image.convert('RGB')
image.save(os.path.join(dest_path, 'val', id2name[id_, 1]))
else:
shutil.copyfile(os.path.join(image_path, id2name[id_, 1]),
os.path.join(dest_path, 'val', id2name[id_, 1]))
image.close()
if __name__ == '__main__':
main()
print('finished')
| 2,295 | 31.8 | 82 | py |
AutoPruner | AutoPruner-master/ResNet50/30/src_code/my_op_fc.py | import torch
from torch.autograd import Variable
import torch.nn as nn
from torch.autograd import gradcheck
import numpy as np
class MyGAP_fc(torch.autograd.Function):
'''
Global Average Pooling with batchsize: N*4096 -> 1*4096
'''
@staticmethod
def forward(ctx, input):
ctx.save_for_backward(input)
input = torch.mean(input, dim=0, keepdim=True)
return input
@staticmethod
def backward(ctx, grad_output):
input = ctx.saved_tensors
grad_input = input[0].clone()
for i in range(grad_input.shape[0]):
grad_input[i, :] = grad_output.data / grad_input.shape[0]
return Variable(grad_input)
class MyScale_fc(torch.autograd.Function):
'''
input: x: 64*4096, scale:4096 ==> x[:, i]*scale[i]
'''
@staticmethod
def forward(self, input_data, scale_vec):
self.save_for_backward(input_data, scale_vec)
input_data2 = input_data.clone()
for i in range(scale_vec.shape[0]):
input_data2[:, i] = input_data[:, i] * scale_vec[i]
return input_data2
@staticmethod
def backward(self, grad_output):
input_data, scale_vec = self.saved_tensors
grad_input = input_data.clone()
for i in range(scale_vec.shape[0]):
grad_input[:, i] = grad_output.data[:, i] * scale_vec[i]
grad_vec = scale_vec.clone()
for i in range(scale_vec.shape[0]):
grad_vec[i] = torch.sum(grad_output.data[:, i]*input_data[:, i])
return Variable(grad_input), Variable(grad_vec)
class MyCS_fc(nn.Module):
def __init__(self, channels_num):
super(MyCS_fc, self).__init__()
self.layer_type = 'MyCS_fc'
self.fc = nn.Linear(channels_num, channels_num)
self.sigmoid = nn.Sigmoid()
def forward(self, x, scale_factor):
x_scale = MyGAP_fc.apply(x) # apply my GAP: N*4096 => 1*4096
x_scale = self.fc(x_scale) # 1*4096
x_scale = torch.squeeze(x_scale) # 4096
x_scale = x_scale * scale_factor # apply scale sigmoid
x_scale = self.sigmoid(x_scale)
if not self.training:
index = (np.sign(x_scale.data.cpu().numpy() - 0.5) + 1) / 2.0
x_scale.data = torch.FloatTensor(index).cuda()
x = MyScale_fc.apply(x, x_scale)
return x, x_scale
if __name__ == '__main__':
in_ = (Variable(torch.randn(3, 4).double(), requires_grad=True),
Variable(torch.randn(4).double(), requires_grad=True))
res = gradcheck(MyScale_fc.apply, in_, eps=1e-6, atol=1e-4)
# in_ = (Variable(torch.randn(4, 64).double(), requires_grad=True),)
# res = gradcheck(MyGAP_fc.apply, in_, eps=1e-6, atol=1e-4)
print(res)
| 2,729 | 31.117647 | 76 | py |
AutoPruner | AutoPruner-master/ResNet50/30/src_code/my_op.py | import torch
from torch.autograd import Variable
import torch.nn as nn
from torch.autograd import gradcheck
import numpy as np
import math
class MyGAP(torch.autograd.Function):
'''
Global Average Pooling with batchsize: N*512*14*14 -> 1*512*14*14
'''
@staticmethod
def forward(ctx, input):
ctx.save_for_backward(input)
input = torch.mean(input, dim=0, keepdim=True)
return input
@staticmethod
def backward(ctx, grad_output):
input = ctx.saved_tensors
grad_input = input[0].clone()
for i in range(grad_input.shape[0]):
grad_input[i, :, :, :] = grad_output.data / grad_input.shape[0]
return Variable(grad_input)
class MyScale(torch.autograd.Function):
'''
input: x: 64*512*7*7, scale:512 ==> x[:, i, :, :]*scale[i]
'''
@staticmethod
def forward(self, input_data, scale_vec):
self.save_for_backward(input_data, scale_vec)
input_data2 = input_data.clone()
for i in range(scale_vec.shape[0]):
input_data2[:, i, :, :] = input_data[:, i, :, :] * scale_vec[i]
return input_data2
@staticmethod
def backward(self, grad_output):
input_data, scale_vec = self.saved_tensors
grad_input = input_data.clone()
for i in range(scale_vec.shape[0]):
grad_input[:, i, :, :] = grad_output.data[:, i, :, :] * scale_vec[i]
grad_vec = scale_vec.clone()
for i in range(scale_vec.shape[0]):
grad_vec[i] = torch.sum(grad_output.data[:, i, :, :]*input_data[:, i, :, :])
return Variable(grad_input), Variable(grad_vec)
class MyCS(nn.Module):
def __init__(self, channels_num, activation_size=14, max_ks=2):
super(MyCS, self).__init__()
self.layer_type = 'MyCS'
self.conv = nn.Conv2d(channels_num, channels_num,
kernel_size=int(activation_size / max_ks), stride=1, padding=0)
self.map = nn.MaxPool2d(kernel_size=max_ks, stride=max_ks)
self.sigmoid = nn.Sigmoid()
n = int(activation_size / max_ks) * int(activation_size / max_ks) * channels_num
self.conv.weight.data.normal_(0, 10 * math.sqrt(2.0 / n))
def forward(self, x, scale_factor, channel_index=None):
x_scale = MyGAP.apply(x) # apply my GAP: N*512*14*14 => 1*512*14*14
x_scale = self.map(x_scale) # apply MAP: 1*512*14*14 => 1*512*7*7
x_scale = self.conv(x_scale) # 1*512*1*1
x_scale = torch.squeeze(x_scale) # 512
x_scale = x_scale * scale_factor # apply scale sigmoid
x_scale = self.sigmoid(x_scale)
if not self.training:
x_scale.data = torch.FloatTensor(channel_index).cuda()
x = MyScale.apply(x, x_scale)
return x, x_scale
if __name__ == '__main__':
# in_ = (Variable(torch.randn(1, 1, 3, 3).double(), requires_grad=True),
# Variable(torch.randn(1).double(), requires_grad=True))
# res = gradcheck(MyScale.apply, in_, eps=1e-6, atol=1e-4)
in_ = (Variable(torch.randn(2, 64, 3, 3).double(), requires_grad=True),)
res = gradcheck(MyGAP.apply, in_, eps=1e-6, atol=1e-4)
print(res)
| 3,182 | 33.225806 | 93 | py |
AutoPruner | AutoPruner-master/ResNet50/30/src_code/Network_FT.py | import torch.nn as nn
import math
import torch
from . import my_op
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, number_list, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(number_list[1], number_list[0], kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(number_list[0])
self.conv2 = nn.Conv2d(number_list[3], number_list[2], kernel_size=3, stride=stride,
padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(number_list[2])
self.conv3 = nn.Conv2d(number_list[5], number_list[4], kernel_size=1, bias=False)
self.bn3 = nn.BatchNorm2d(number_list[4])
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class Bottleneck_with_CS(nn.Module):
expansion = 4
def __init__(self, number_list, stride=1, downsample=None, ks=1, CS_id=0):
super(Bottleneck_with_CS, self).__init__()
self.conv1 = nn.Conv2d(number_list[1], number_list[0], kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(number_list[0])
self.conv2 = nn.Conv2d(number_list[3], number_list[2], kernel_size=3, stride=stride,
padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(number_list[2])
self.conv3 = nn.Conv2d(number_list[5], number_list[4], kernel_size=1, bias=False)
self.bn3 = nn.BatchNorm2d(number_list[4])
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
self.CS_id = CS_id
self.channel_index = list()
if ks == 7:
mks = 1
else:
mks = 2
self.cs1 = my_op.MyCS(number_list[0], activation_size=ks * stride, max_ks=mks)
self.cs2 = my_op.MyCS(number_list[2], activation_size=ks, max_ks=mks)
self.vec1 = None
self.vec2 = None
self.scale_factor1 = 1.0
self.scale_factor2 = 1.0
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
if self.training:
out, self.vec1 = self.cs1(out, self.scale_factor1)
else:
out, self.vec1 = self.cs1(out, self.scale_factor1, self.channel_index[2 * self.CS_id])
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
if self.training:
out, self.vec2 = self.cs2(out, self.scale_factor2)
else:
out, self.vec2 = self.cs2(out, self.scale_factor2, self.channel_index[2 * self.CS_id + 1])
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, group_id, block, layers, num_classes=1000):
old_weight = torch.load('checkpoint/model.pth')
channel_number_list = analyse_number(old_weight)
self.kernel_size = int(56 / (2**group_id))
self.inplanes = 64
self.g_id = group_id
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(channel_number_list[0], 0, block, 64, layers[0])
self.layer2 = self._make_layer(channel_number_list[1], 1, block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(channel_number_list[2], 2, block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(channel_number_list[3], 3, block, 512, layers[3], stride=2)
self.avgpool = nn.AvgPool2d(7, stride=1)
self.fc = nn.Linear(512 * block.expansion, num_classes)
# for m in self.modules():
# if isinstance(m, nn.Conv2d):
# # n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
# # m.weight.data.normal_(0, math.sqrt(2. / n))
# m.weight.data.normal_(0, math.sqrt(1.))
# # torch.nn.init.xavier_uniform(m.weight)
# elif isinstance(m, nn.BatchNorm2d):
# m.weight.data.fill_(1)
# m.bias.data.zero_()
old_weight = torch.load('checkpoint/model.pth')
my_weight = self.state_dict()
my_keys = list(my_weight.keys())
for k, v in old_weight.items():
name = ''.join(list(k)[7:])
if name in my_keys:
my_weight[name] = v
self.load_state_dict(my_weight)
def _make_layer(self, number_list, group_id, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion),
)
layers = []
if group_id == self.g_id:
layers.append(Bottleneck_with_CS(number_list[0], stride, downsample, ks=self.kernel_size, CS_id=0))
else:
layers.append(block(number_list[0], stride, downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
if group_id == self.g_id:
if self.g_id == 3 and i == blocks-1:
layers.append(block(number_list[i]))
else:
layers.append(Bottleneck_with_CS(number_list[i], ks=self.kernel_size, CS_id=i))
else:
layers.append(block(number_list[i]))
return nn.Sequential(*layers)
def forward(self, x, channel_index=None):
if not self.training:
self.set_channel_index(channel_index)
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x) # 128, 64, 56, 56
x = self.layer1(x) # 128, 64, 56, 56
x = self.layer2(x) # 128, 512, 28, 28
x = self.layer3(x) # 128, 1024, 14, 14
x = self.layer4(x) # 128, 2048, 7, 7
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
scale_vector = self.get_scale_vector()
return x, scale_vector
def set_channel_index(self, channel_index):
if self.g_id == 0:
self.layer1[0].channel_index = channel_index
self.layer1[1].channel_index = channel_index
self.layer1[2].channel_index = channel_index
elif self.g_id == 1:
self.layer2[0].channel_index = channel_index
self.layer2[1].channel_index = channel_index
self.layer2[2].channel_index = channel_index
self.layer2[3].channel_index = channel_index
elif self.g_id == 2:
self.layer3[0].channel_index = channel_index
self.layer3[1].channel_index = channel_index
self.layer3[2].channel_index = channel_index
self.layer3[3].channel_index = channel_index
self.layer3[4].channel_index = channel_index
self.layer3[5].channel_index = channel_index
else:
self.layer4[0].channel_index = channel_index
self.layer4[1].channel_index = channel_index
# self.layer4[2].channel_index = channel_index
def get_scale_vector(self):
vector_list = list()
if self.g_id == 0:
vector_list.append(self.layer1[0].vec1)
vector_list.append(self.layer1[0].vec2)
vector_list.append(self.layer1[1].vec1)
vector_list.append(self.layer1[1].vec2)
vector_list.append(self.layer1[2].vec1)
vector_list.append(self.layer1[2].vec2)
elif self.g_id == 1:
vector_list.append(self.layer2[0].vec1)
vector_list.append(self.layer2[0].vec2)
vector_list.append(self.layer2[1].vec1)
vector_list.append(self.layer2[1].vec2)
vector_list.append(self.layer2[2].vec1)
vector_list.append(self.layer2[2].vec2)
vector_list.append(self.layer2[3].vec1)
vector_list.append(self.layer2[3].vec2)
elif self.g_id == 2:
vector_list.append(self.layer3[0].vec1)
vector_list.append(self.layer3[0].vec2)
vector_list.append(self.layer3[1].vec1)
vector_list.append(self.layer3[1].vec2)
vector_list.append(self.layer3[2].vec1)
vector_list.append(self.layer3[2].vec2)
vector_list.append(self.layer3[3].vec1)
vector_list.append(self.layer3[3].vec2)
vector_list.append(self.layer3[4].vec1)
vector_list.append(self.layer3[4].vec2)
vector_list.append(self.layer3[5].vec1)
vector_list.append(self.layer3[5].vec2)
else:
vector_list.append(self.layer4[0].vec1)
vector_list.append(self.layer4[0].vec2)
vector_list.append(self.layer4[1].vec1)
vector_list.append(self.layer4[1].vec2)
# vector_list.append(self.layer4[2].vec1)
# vector_list.append(self.layer4[2].vec2)
return vector_list
def set_scale_factor(self, sf):
if self.g_id == 0:
self.layer1[0].scale_factor1 = sf[0]
self.layer1[0].scale_factor2 = sf[1]
self.layer1[1].scale_factor1 = sf[2]
self.layer1[1].scale_factor2 = sf[3]
self.layer1[2].scale_factor1 = sf[4]
self.layer1[2].scale_factor2 = sf[5]
elif self.g_id == 1:
self.layer2[0].scale_factor1 = sf[0]
self.layer2[0].scale_factor2 = sf[1]
self.layer2[1].scale_factor1 = sf[2]
self.layer2[1].scale_factor2 = sf[3]
self.layer2[2].scale_factor1 = sf[4]
self.layer2[2].scale_factor2 = sf[5]
self.layer2[3].scale_factor1 = sf[6]
self.layer2[3].scale_factor2 = sf[7]
elif self.g_id == 2:
self.layer3[0].scale_factor1 = sf[0]
self.layer3[0].scale_factor2 = sf[1]
self.layer3[1].scale_factor1 = sf[2]
self.layer3[1].scale_factor2 = sf[3]
self.layer3[2].scale_factor1 = sf[4]
self.layer3[2].scale_factor2 = sf[5]
self.layer3[3].scale_factor1 = sf[6]
self.layer3[3].scale_factor2 = sf[7]
self.layer3[4].scale_factor1 = sf[8]
self.layer3[4].scale_factor2 = sf[9]
self.layer3[5].scale_factor1 = sf[10]
self.layer3[5].scale_factor2 = sf[11]
else:
self.layer4[0].scale_factor1 = sf[0]
self.layer4[0].scale_factor2 = sf[1]
self.layer4[1].scale_factor1 = sf[2]
self.layer4[1].scale_factor2 = sf[3]
# self.layer4[2].scale_factor = sf
def analyse_number(weight):
number_list = list()
group_list = list()
layer_list = list()
old_name = '1.0.'
old_group = '1'
for k, v in weight.items():
if 'layer' in k and'conv' in k:
current_name = k.split('layer')[1].split('conv')[0]
current_group = current_name.split('.')[0]
if current_name != old_name:
old_name = current_name
group_list.append(layer_list.copy())
layer_list = list()
if current_group != old_group:
old_group = current_group
number_list.append(group_list.copy())
group_list = list()
layer_list.append(v.size()[0])
layer_list.append(v.size()[1])
group_list.append(layer_list.copy())
number_list.append(group_list.copy())
return number_list
def NetworkNew(group_id):
model = ResNet(group_id, Bottleneck, [3, 4, 6, 3])
return model
| 12,489 | 37.549383 | 111 | py |
AutoPruner | AutoPruner-master/ResNet50/30/src_code/lmdbdataset.py | import cv2
import numpy as np
import torchvision.transforms as transforms
import lmdb
import msgpack
from torch.utils.data import Dataset
from PIL import Image
class lmdbDataset(Dataset):
def __init__(self, location, is_train):
self.env = lmdb.open(location, subdir=False, max_readers=1, readonly=True, lock=False, readahead=False,
meminit=False)
self.txn = self.env.begin(write=False)
self.length = self.txn.stat()['entries']
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
# train data augment
if is_train:
self.transform = transforms.Compose([
transforms.Resize(256),
transforms.RandomCrop((224, 224)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])
# test data augment
else:
self.transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])
'''
for key,data in self.txn.cursor():
now_data = msgpack.loads(data,raw=False)
data_img = now_data[0]
label = now_data[1]
now_arr = np.frombuffer(data_img[b'data'],dtype=np.uint8)
print(now_arr)
image_content = cv2.imdecode(now_arr, cv2.IMREAD_COLOR)
print(image_content.shape)
#print(type(_))
break
'''
def __len__(self):
return self.length - 1
def __getitem__(self, index):
new_index = str(index).encode()
data = self.txn.get(new_index)
now_data = msgpack.loads(data, raw=False)
data_img = now_data[0]
label = now_data[1]
now_arr = np.frombuffer(data_img[b'data'], dtype=np.uint8)
image_content = cv2.imdecode(now_arr, cv2.IMREAD_COLOR)
image_content = cv2.cvtColor(image_content, cv2.COLOR_BGR2RGB)
image_content = Image.fromarray(image_content)
image_content = self.transform(image_content)
return image_content, label
if __name__ == '__main__':
temp_dataset = lmdbDataset('indoor67.lmdb', True)
print(temp_dataset[0])
#print(i)
#assert temp_dataset[i][0] is not None | 2,431 | 34.246377 | 111 | py |
AutoPruner | AutoPruner-master/ResNet50/30/compress_model/new_model.py | import torch.nn as nn
import torch
import numpy as np
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, number_list, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(number_list[1], number_list[0], kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(number_list[0])
self.conv2 = nn.Conv2d(number_list[3], number_list[2], kernel_size=3, stride=stride,
padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(number_list[2])
self.conv3 = nn.Conv2d(number_list[5], number_list[4], kernel_size=1, bias=False)
self.bn3 = nn.BatchNorm2d(number_list[4])
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, group_id, block, layers, num_classes=1000):
folder_path = '../checkpoint/group_' + str(group_id)
old_weight = torch.load(folder_path+'/model.pth')
channel_index = torch.load(folder_path+'/channel_index.pth')
channel_number_list = analyse_number(old_weight)
for i in range(int(len(channel_index)/2)):
new_num = np.where(channel_index[2 * i] != 0)[0]
new_num_1 = int(new_num.shape[0])
new_num = np.where(channel_index[2 * i + 1] != 0)[0]
new_num_2 = int(new_num.shape[0])
channel_number_list[group_id][i][0] = new_num_1
channel_number_list[group_id][i][2] = new_num_2
channel_number_list[group_id][i][3] = new_num_1
channel_number_list[group_id][i][5] = new_num_2
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(channel_number_list[0], block, 64, layers[0])
self.layer2 = self._make_layer(channel_number_list[1], block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(channel_number_list[2], block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(channel_number_list[3], block, 512, layers[3], stride=2)
self.avgpool = nn.AvgPool2d(7, stride=1)
self.fc = nn.Linear(512 * block.expansion, num_classes)
my_weight = self.state_dict()
ci_count = 0
ci_1 = 0
ci_2 = 0
for k, v in my_weight.items():
name = 'module.' + k
if 'layer'+str(group_id+1) in name and 'downsample' not in name:
name_tmp = name.split('.')
if '1' in name_tmp[3]:
if 'conv' in name:
ci_1 = torch.cuda.LongTensor(np.where(channel_index[ci_count] != 0)[0])
ci_count += 1
my_weight[k] = old_weight[name][ci_1, :, :, :]
else:
my_weight[k] = old_weight[name][ci_1]
elif '2' in name_tmp[3]:
if 'conv' in name:
ci_2 = torch.cuda.LongTensor(np.where(channel_index[ci_count] != 0)[0])
ci_count += 1
my_weight[k] = old_weight[name][ci_2, :, :, :]
my_weight[k] = my_weight[k][:, ci_1, :, :]
else:
my_weight[k] = old_weight[name][ci_2]
elif '3' in name_tmp[3]:
if 'conv' in name:
my_weight[k] = old_weight[name][:, ci_2, :, :]
else:
my_weight[k] = old_weight[name]
else:
print('error!')
else:
my_weight[k] = old_weight[name]
self.load_state_dict(my_weight)
def _make_layer(self, number_list, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(number_list[0], stride, downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(number_list[i]))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
def analyse_number(weight):
number_list = list()
group_list = list()
layer_list = list()
old_name = '1.0.'
old_group = '1'
for k, v in weight.items():
if 'layer' in k and'conv' in k and 'cs' not in k:
current_name = k.split('layer')[1].split('conv')[0]
current_group = current_name.split('.')[0]
if current_name != old_name:
old_name = current_name
group_list.append(layer_list.copy())
layer_list = list()
if current_group != old_group:
old_group = current_group
number_list.append(group_list.copy())
group_list = list()
layer_list.append(v.size()[0])
layer_list.append(v.size()[1])
group_list.append(layer_list.copy())
number_list.append(group_list.copy())
return number_list
def NetworkNew(group_id):
model = ResNet(group_id, Bottleneck, [3, 4, 6, 3])
return model
class ResNet_test(nn.Module):
def __init__(self, model_path, block, layers, num_classes=1000):
old_weight = torch.load(model_path)
channel_number_list = analyse_number(old_weight)
self.inplanes = 64
super(ResNet_test, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(channel_number_list[0], block, 64, layers[0])
self.layer2 = self._make_layer(channel_number_list[1], block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(channel_number_list[2], block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(channel_number_list[3], block, 512, layers[3], stride=2)
self.avgpool = nn.AvgPool2d(7, stride=1)
self.fc = nn.Linear(512 * block.expansion, num_classes)
my_weight = self.state_dict()
for k, v in my_weight.items():
name = 'module.' + k
my_weight[k] = old_weight[name]
self.load_state_dict(my_weight)
def _make_layer(self, number_list, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(number_list[0], stride, downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(number_list[i]))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
def NetworkNew_test(model_path):
model = ResNet_test(model_path, Bottleneck, [3, 4, 6, 3])
return model
| 8,767 | 35.381743 | 95 | py |
AutoPruner | AutoPruner-master/ResNet50/30/compress_model/compress_model.py | import torch
from new_model import NetworkNew
import argparse
import torch.backends.cudnn as cudnn
parser = argparse.ArgumentParser(description='PyTorch Digital Mammography Training')
parser.add_argument('--group_id', default=3, type=int, help='the id of compressed layer, starting from 0')
args = parser.parse_args()
print(args)
def main():
# 1. create compressed model
vgg16_new = NetworkNew(group_id=args.group_id)
# Phase 2 : Model setup
vgg16_new = vgg16_new.cuda()
vgg16_new = torch.nn.DataParallel(vgg16_new.cuda(), device_ids=range(torch.cuda.device_count()))
cudnn.benchmark = True
new_model_param = vgg16_new.state_dict()
torch.save(new_model_param, '../checkpoint/model.pth')
print('Finished!')
if __name__ == '__main__':
main()
| 786 | 28.148148 | 106 | py |
AutoPruner | AutoPruner-master/ResNet50/30/compress_model/evaluate_net.py | import torch
from new_model import NetworkNew_test
import argparse
import torch.backends.cudnn as cudnn
import os
import sys
import time
sys.path.append('../')
from src_code.lmdbdataset import lmdbDataset
parser = argparse.ArgumentParser(description='PyTorch Digital Mammography Training')
parser.add_argument('--batch_size', default=100, type=int, help='batch size')
parser.add_argument('--data_base', default='/data/zhangcl/ImageNet', type=str, help='the path of dataset')
parser.add_argument('--gpu_id', default='4,5', type=str,
help='id(s) for CUDA_VISIBLE_DEVICES')
args = parser.parse_args()
print(args)
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
def evaluate():
# Phase 1: load model
model = NetworkNew_test('../checkpoint/model.pth')
# Phase 2 : Model setup
model = model.cuda()
model = torch.nn.DataParallel(model.cuda(), device_ids=range(torch.cuda.device_count()))
cudnn.benchmark = True
# Phase 2 : Data Upload
print('\n[Phase 2] : Data Preperation')
dset_loaders = {
'train': torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-train.lmdb'), True),
batch_size=args.batch_size,
shuffle=True,
num_workers=8,
pin_memory=True),
'val': torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-val.lmdb'), False),
batch_size=args.batch_size,
num_workers=8,
pin_memory=True)
}
print('data_loader_success!')
# Phase 3: Validation
print("\n[Phase 3 : Inference on val")
criterion = torch.nn.CrossEntropyLoss().cuda()
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
for batch_idx, (input, target) in enumerate(dset_loaders['val']): # dset_loaders['val']):
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input, volatile=True)
target_var = torch.autograd.Variable(target, volatile=True)
# compute output
output = model(input_var)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
batch_idx, len(dset_loaders['val']), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
sys.stdout.flush()
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == '__main__':
evaluate()
| 3,968 | 31.532787 | 106 | py |
AutoPruner | AutoPruner-master/vgg16/50/fine_tune_compressed_model.py | import argparse
import os
import shutil
import time
import sys
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
from torchvision import datasets, transforms
from src_code.lmdbdataset import lmdbDataset
from compress_model.new_model import vgg16_test
parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
'''parser.add_argument('data', metavar='DIR',
help='path to dataset')
'''
parser.add_argument('-j', '--workers', default=8, type=int, metavar='N',
help='number of data loading workers (default: 8)')
parser.add_argument('--epochs', default=30, type=int, metavar='N',
help='number of total epochs to run')
parser.add_argument('--start-epoch', default=0, type=int, metavar='N',
help='manual epoch number (useful on restarts)')
parser.add_argument('-b', '--batch-size', default=256, type=int,
metavar='N', help='mini-batch size (default: 128)')
parser.add_argument('--lr', '--learning-rate', default=0.001, type=float,
metavar='LR', help='initial learning rate')
parser.add_argument('--momentum', default=0.9, type=float, metavar='M',
help='momentum')
parser.add_argument('--weight-decay', '--wd', default=1e-4, type=float,
metavar='W', help='weight decay (default: 1e-4)')
parser.add_argument('--print-freq', '-p', default=10, type=int,
metavar='N', help='print frequency (default: 10)')
parser.add_argument('--resume', default='', type=str, metavar='PATH',
help='path to latest checkpoint (default: none)')
parser.add_argument('--evaluate', default=False, type=bool,
help='evaluate model on validation set')
parser.add_argument('--pretrained', dest='pretrained', action='store_true',
help='use pre-trained model')
parser.add_argument('--world-size', default=1, type=int,
help='number of distributed processes')
parser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str,
help='url used to set up distributed training')
parser.add_argument('--dist-backend', default='gloo', type=str,
help='distributed backend')
parser.add_argument('--gpu_id', default='4,5,6,7', type=str,
help='id(s) for CUDA_VISIBLE_DEVICES')
parser.add_argument('--data_base', default='/data/zhangcl/ImageNet', type=str, help='the path of dataset')
parser.add_argument('--load_from_lmdb', default=True, type=bool, help='load image data from lmdb or not')
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
best_prec1 = 0
print(args)
def main():
global args, best_prec1
args = parser.parse_args()
args.distributed = args.world_size > 1
if args.distributed:
dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url,
world_size=args.world_size)
# create model
# model = models.vgg16(pretrained=True)
model = vgg16_test('checkpoint/model.pth')
print(model)
model = torch.nn.DataParallel(model.cuda(), device_ids=range(torch.cuda.device_count()))
cudnn.benchmark = True
# define loss function (criterion) and optimizer
criterion = nn.CrossEntropyLoss().cuda()
optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), args.lr,
momentum=args.momentum,
weight_decay=args.weight_decay)
cudnn.benchmark = True
# Data loading code from lmdb
if args.load_from_lmdb:
train_loader = torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-train.lmdb'), True),
batch_size=args.batch_size,
shuffle=True,
num_workers=8,
pin_memory=True
)
print('train_loader_success!')
val_loader = torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-val.lmdb'), False),
batch_size=args.batch_size,
num_workers=8,
pin_memory=True
)
else:
traindir = os.path.join('/opt/luojh/Dataset/ImageNet/images', 'train')
valdir = os.path.join('/opt/luojh/Dataset/ImageNet/images', 'val')
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
train_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(traindir, transforms.Compose([
transforms.Resize(256),
transforms.RandomCrop((224, 224)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])),
batch_size=args.batch_size, shuffle=True,
num_workers=args.workers, pin_memory=True)
val_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(valdir, transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])),
batch_size=args.batch_size, shuffle=False,
num_workers=args.workers, pin_memory=True)
# evaluate and train
if args.evaluate:
validate(val_loader, model, criterion)
return
for epoch in range(args.start_epoch, args.epochs):
adjust_learning_rate(optimizer, epoch, int(args.epochs/3.0))
# train for one epoch
train(train_loader, model, criterion, optimizer, epoch)
# evaluate on validation set
prec1 = validate(val_loader, model, criterion)
# remember best prec@1 and save checkpoint
is_best = prec1 > best_prec1
best_prec1 = max(prec1, best_prec1)
if is_best:
folder_path = 'checkpoint/fine_tune'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
torch.save(model.state_dict(), folder_path + '/model.pth')
print('best acc is %.3f' % best_prec1)
def train(train_loader, model, criterion, optimizer, epoch):
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to train mode
model.train()
end = time.time()
for i, (input, target) in enumerate(train_loader):
# measure data loading time
data_time.update(time.time() - end)
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input).cuda()
target_var = torch.autograd.Variable(target).cuda()
# compute output
output = model(input_var)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Epoch: [{0}][{1}/{2}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Data {data_time.val:.3f} ({data_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
epoch, i, len(train_loader), batch_time=batch_time,
data_time=data_time, loss=losses, top1=top1, top5=top5))
sys.stdout.flush()
def validate(val_loader, model, criterion):
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
for i, (input, target) in enumerate(val_loader):
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input, volatile=True)
target_var = torch.autograd.Variable(target, volatile=True)
# compute output
output = model(input_var)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
i, len(val_loader), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
sys.stdout.flush()
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
return top1.avg
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, 'model_best.pth.tar')
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def adjust_learning_rate(optimizer, epoch, epoch_num):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = args.lr * (0.1 ** (epoch // epoch_num))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == '__main__':
main()
| 10,897 | 35.693603 | 106 | py |
AutoPruner | AutoPruner-master/vgg16/50/main.py | # ************************************************************
# Author : Bumsoo Kim, 2017
# Github : https://github.com/meliketoy/fine-tuning.pytorch
#
# Korea University, Data-Mining Lab
# Deep Convolutional Network Fine tuning Implementation
#
# Description : main.py
# The main code for training classification networks.
# ***********************************************************
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import time
import os
import sys
import argparse
import numpy as np
import shutil
import math
from src_code import Network_FT
from src_code.lmdbdataset import lmdbDataset
parser = argparse.ArgumentParser(description='PyTorch Digital Mammography Training')
parser.add_argument('--lr', default=1e-3, type=float, help='learning rate')
parser.add_argument('--weight_decay', default=5e-4, type=float, help='weight decay')
parser.add_argument('--batch_size', default=256, type=int, help='batch size')
parser.add_argument('--num_epochs', default=3, type=int, help='number of training epochs')
parser.add_argument('--lr_decay_epoch', default=10, type=int, help='learning rate decay epoch')
parser.add_argument('--data_base', default='/data/zhangcl/ImageNet', type=str, help='the path of dataset')
parser.add_argument('--ft_model_path', default='/home/luojh2/.torch/models/vgg16-397923af.pth',
type=str, help='the path of fine tuned model')
parser.add_argument('--gpu_id', default='4,5,6,7', type=str,
help='id(s) for CUDA_VISIBLE_DEVICES')
parser.add_argument('--layer_id', default=11, type=int, help='the id of compressed layer, starting from 0')
parser.add_argument('--start_epoch', default=0, type=int, metavar='N',
help='manual epoch number (useful on restarts)')
parser.add_argument('--compression_rate', default=0.4, type=float, help='the percentage of 1 in compressed model')
parser.add_argument('--channel_index_range', default=20, type=int, help='the range to calculate channel index')
parser.add_argument('--alpha_range', default=100, type=int, help='the range to calculate channel index')
parser.add_argument('--print-freq', '-p', default=20, type=int,
metavar='N', help='print frequency (default: 10)')
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
best_prec1 = -1
scale_factor_list = list()
alpha_index = 0
threshold = 95
if args.layer_id == 12:
args.compression_rate = 0.4
print(args)
def main():
global args, best_prec1, scale_factor_list
# Phase 1 : Data Upload
print('\n[Phase 1] : Data Preperation')
train_loader = torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-train.lmdb'), True),
batch_size=args.batch_size,
shuffle=True,
num_workers=10,
pin_memory=True)
val_loader = torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-val.lmdb'), False),
batch_size=args.batch_size,
num_workers=8,
pin_memory=True)
print('data_loader_success!')
# Phase 2 : Model setup
print('\n[Phase 2] : Model setup')
if args.layer_id == 0:
model_ft = Network_FT.Vgg16(args.ft_model_path).cuda()
model_ft = torch.nn.DataParallel(model_ft)
model_param = model_ft.state_dict()
torch.save(model_param, 'checkpoint/model.pth')
model_ft = Network_FT.NetworkNew(args.layer_id).cuda()
print(model_ft)
model_ft = torch.nn.DataParallel(model_ft)
cudnn.benchmark = True
print("model setup success!")
# Phase 3: fine_tune model
print('\n[Phase 3] : Model fine tune')
# define loss function (criterion) and optimizer
criterion = nn.CrossEntropyLoss().cuda()
optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model_ft.parameters()), args.lr,
momentum=0.9,
weight_decay=args.weight_decay)
scale_factor_list = np.linspace(0.1, 2, int(args.num_epochs * len(train_loader) / args.alpha_range))
reg_lambda = 10.0
for epoch in range(args.start_epoch, args.num_epochs):
adjust_learning_rate(optimizer, epoch, 2)
# train for one epoch
channel_index, reg_lambda = train(train_loader, model_ft, criterion, optimizer, epoch, reg_lambda)
# evaluate on validation set
prec1 = validate(val_loader, model_ft, criterion, channel_index)
# remember best prec@1 and save checkpoint
is_best = prec1 > best_prec1
if is_best:
best_prec1 = prec1
folder_path = 'checkpoint/layer_' + str(args.layer_id)
if not os.path.exists(folder_path):
os.makedirs(folder_path)
torch.save(model_ft.state_dict(), folder_path+'/model.pth')
torch.save(channel_index, folder_path+'/channel_index.pth')
def train(train_loader, model, criterion, optimizer, epoch, reg_lambda):
global scale_factor_list, alpha_index, threshold
gpu_num = torch.cuda.device_count()
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to train mode
model.train()
channel_index_list = list()
channel_index = 0
end = time.time()
for i, (input, target) in enumerate(train_loader):
if i % args.alpha_range == 0:
if alpha_index == len(scale_factor_list):
alpha_index = len(scale_factor_list) - 1
scale_factor = scale_factor_list[alpha_index]
alpha_index = alpha_index + 1
# measure data loading time
data_time.update(time.time() - end)
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input).cuda()
target_var = torch.autograd.Variable(target).cuda()
# compute output
output, scale_vec = model(input_var, scale_factor)
loss = criterion(output, target_var)
loss = loss + float(reg_lambda) * (
scale_vec.norm(1) / float(scale_vec.size(0)) - args.compression_rate) ** 2
# compute channel index
tmp = scale_vec.data.cpu().numpy().reshape(gpu_num, -1).mean(0)
channel_index_list.append(tmp.copy())
if i == 0:
print('first 5 values: [{0:.6f}, {1:.6f}, {2:.6f}, {3:.6f}, {4:.6f}]'.format(tmp[0], tmp[1], tmp[2], tmp[3],
tmp[4]))
if len(channel_index_list) == args.channel_index_range:
channel_index_list = np.array(channel_index_list)
tmp_value = channel_index_list[args.channel_index_range-1, :]
tmp = tmp_value
two_side_rate = (np.sum(tmp_value > 0.8) + np.sum(tmp_value < 0.2)) / len(tmp_value)
print('first 5 values: [{0:.6f}, {1:.6f}, {2:.6f}, {3:.6f}, {4:.6f}]'.format(tmp[0], tmp[1], tmp[2], tmp[3],
tmp[4]))
tmp2 = channel_index_list.sum(axis=0)
tmp2 = tmp2 / args.channel_index_range
for tmp_i in range(len(channel_index_list)):
channel_index_list[tmp_i] = (np.sign(channel_index_list[tmp_i] - 0.5) + 1) / 2.0
tmp = channel_index_list.sum(axis=0)
tmp = tmp / args.channel_index_range
channel_index = (np.sign(tmp - 0.5) + 1) / 2.0 # to 0-1 binary
real_pruning_rate = 100.0 * np.sum(tmp2 < 10**-6) / len(tmp2)
binary_pruning_rate = 100.0 * np.sum(channel_index < 10**-6) / len(channel_index)
if binary_pruning_rate >= threshold:
scale_factor_list = scale_factor_list + 0.1
scale_factor = scale_factor + 0.1
threshold = threshold - 5
if threshold < 100 - 100*args.compression_rate:
threshold = 100 - 100*args.compression_rate
print('threshold is %d' % int(threshold))
if two_side_rate < 0.9 and alpha_index >= 20:
scale_factor_list = scale_factor_list + 0.1
scale_factor = scale_factor + 0.1
tmp[tmp == 0] = 1
channel_inconsistency = 100.0 * np.sum(tmp != 1) / len(tmp)
print(
"pruning rate (real/binary): {0:.4f}%/{1:.4f}%, index inconsistency: {2:.4f}%, two_side_rate: {3:.3f}".format(
real_pruning_rate, binary_pruning_rate, channel_inconsistency, two_side_rate))
channel_index_list = list()
reg_lambda = 100.0 * np.abs(binary_pruning_rate/100.0 - 1 + args.compression_rate)
sys.stdout.flush()
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Epoch[{0}]: [{1}/{2}]\t'
'scale_factor: {3:.4f}\t'
'reg_lambda: {4:.4f}\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
epoch, i, len(train_loader), scale_factor, reg_lambda, batch_time=batch_time,
top1=top1, top5=top5))
sys.stdout.flush()
return channel_index, reg_lambda
def validate(val_loader, model, criterion, channel_index):
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
for i, (input, target) in enumerate(val_loader):
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input, volatile=True)
target_var = torch.autograd.Variable(target, volatile=True)
# compute output
output, _ = model(input_var, 1.0, channel_index)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
i, len(val_loader), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
sys.stdout.flush()
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
return top1.avg
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, 'model_best.pth.tar')
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def adjust_learning_rate(optimizer, epoch, epoch_num):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = args.lr * (0.1 ** (epoch // epoch_num))
print('| Learning Rate = %f' % lr)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == "__main__":
main()
| 12,807 | 38.409231 | 126 | py |
AutoPruner | AutoPruner-master/vgg16/50/evaluate_network.py | import torch
import torch.backends.cudnn as cudnn
import os
import sys
import argparse
import time
from src_code.lmdbdataset import lmdbDataset
from src_code import Network_FT
parser = argparse.ArgumentParser(description='PyTorch Digital Mammography Training')
parser.add_argument('--batch_size', default=100, type=int, help='batch size')
parser.add_argument('--data_base', default='/data/zhangcl2/ImageNet', type=str, help='the path of dataset')
parser.add_argument('--gpu_id', default='12', type=str,
help='id(s) for CUDA_VISIBLE_DEVICES')
parser.add_argument('--ft_model_path', default='/home/luojh2/.torch/models/vgg16-397923af.pth',
type=str, help='the path of fine tuned model')
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
print(args)
# Phase 1 : Data Upload
print('\n[Phase 1] : Data Preperation')
dset_loaders = {
'train': torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-train.lmdb'), True),
batch_size=args.batch_size,
shuffle=True,
num_workers=8,
pin_memory=True),
'val': torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-val.lmdb'), False),
batch_size=args.batch_size,
num_workers=8,
pin_memory=True)
}
print('data_loader_success!')
# Phase 2 : Model setup
print('\n[Phase 2] : Model setup')
# model = Network_FT.NetworkNew(0).cuda()
model = Network_FT.Vgg16(args.ft_model_path).cuda()
model = torch.nn.DataParallel(model, device_ids=range(torch.cuda.device_count()))
cudnn.benchmark = True
# Phase 3: evaluation
def evaluate_net():
print("\n[Phase 3 : Inference on val")
criterion = torch.nn.CrossEntropyLoss().cuda()
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
for batch_idx, (input, target) in enumerate(dset_loaders['val']): # dset_loaders['val']):
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input, volatile=True)
target_var = torch.autograd.Variable(target, volatile=True)
# compute output
output = model(input_var)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
batch_idx, len(dset_loaders['val']), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
sys.stdout.flush()
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == '__main__':
evaluate_net()
| 4,055 | 31.709677 | 107 | py |
AutoPruner | AutoPruner-master/vgg16/50/mytest.py | # ************************************************************
# Author : Bumsoo Kim, 2017
# Github : https://github.com/meliketoy/fine-tuning.pytorch
#
# Korea University, Data-Mining Lab
# Deep Convolutional Network Fine tuning Implementation
#
# Description : main.py
# The main code for training classification networks.
# ***********************************************************
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import time
import os
import sys
import argparse
import numpy as np
import shutil
import math
from src_code import Network_FT
from src_code.lmdbdataset import lmdbDataset
parser = argparse.ArgumentParser(description='PyTorch Digital Mammography Training')
parser.add_argument('--lr', default=1e-3, type=float, help='learning rate')
parser.add_argument('--weight_decay', default=5e-4, type=float, help='weight decay')
parser.add_argument('--batch_size', default=256, type=int, help='batch size')
parser.add_argument('--num_epochs', default=2, type=int, help='number of training epochs')
parser.add_argument('--lr_decay_epoch', default=10, type=int, help='learning rate decay epoch')
parser.add_argument('--data_base', default='/data/zhangcl/ImageNet', type=str, help='the path of dataset')
parser.add_argument('--ft_model_path', default='/home/luojh2/.torch/models/vgg16-397923af.pth',
type=str, help='the path of fine tuned model')
parser.add_argument('--gpu_id', default='4,5,6,7', type=str,
help='id(s) for CUDA_VISIBLE_DEVICES')
parser.add_argument('--layer_id', default=7, type=int, help='the id of compressed layer, starting from 0')
parser.add_argument('--start_epoch', default=0, type=int, metavar='N',
help='manual epoch number (useful on restarts)')
parser.add_argument('--compression_rate', default=0.2, type=float, help='the percentage of 1 in compressed model')
parser.add_argument('--channel_index_range', default=20, type=int, help='the range to calculate channel index')
parser.add_argument('--print-freq', '-p', default=20, type=int,
metavar='N', help='print frequency (default: 10)')
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
best_prec1 = -1
print(args)
def main():
global args, best_prec1
# Phase 1 : Data Upload
print('\n[Phase 1] : Data Preperation')
train_loader = torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-train.lmdb'), True),
batch_size=args.batch_size,
shuffle=True,
num_workers=16,
pin_memory=True)
val_loader = torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-val.lmdb'), False),
batch_size=args.batch_size,
num_workers=16,
pin_memory=True)
print('data_loader_success!')
# Phase 2 : Model setup
print('\n[Phase 2] : Model setup')
if args.layer_id == 0:
model_ft = Network_FT.Vgg16(args.ft_model_path).cuda()
model_ft = torch.nn.DataParallel(model_ft)
model_param = model_ft.state_dict()
torch.save(model_param, 'checkpoint/model.pth')
model_ft = Network_FT.NetworkNew(args.layer_id).cuda()
weight = torch.load('checkpoint/layer_7/model.pth')
model_ft = torch.nn.DataParallel(model_ft)
model_ft.load_state_dict(weight)
cudnn.benchmark = True
print("model setup success!")
# Phase 3: fine_tune model
print('\n[Phase 3] : Model fine tune')
# define loss function (criterion) and optimizer
criterion = nn.CrossEntropyLoss().cuda()
optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model_ft.parameters()), args.lr,
momentum=0.9,
weight_decay=args.weight_decay)
scale_factor = 9.0
for epoch in range(args.start_epoch, args.num_epochs):
adjust_learning_rate(optimizer, epoch, 1)
# train for one epoch
channel_index, scale_factor = train(train_loader, model_ft, criterion, optimizer, epoch, scale_factor)
# evaluate on validation set
prec1 = validate(val_loader, model_ft, criterion, channel_index)
# remember best prec@1 and save checkpoint
is_best = prec1 > best_prec1
if is_best:
best_prec1 = prec1
folder_path = 'checkpoint/layer_' + str(args.layer_id)
if not os.path.exists(folder_path):
os.makedirs(folder_path)
torch.save(model_ft.state_dict(), folder_path+'/model.pth')
torch.save(channel_index, folder_path+'/channel_index.pth')
def train(train_loader, model, criterion, optimizer, epoch, scale_factor):
gpu_num = torch.cuda.device_count()
scale_factor_mul = math.pow(100, 1.0/(args.num_epochs*len(train_loader)))
reg_lambda = 100
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to train mode
model.train()
channel_index_list = list()
channel_index = 0
end = time.time()
for i, (input, target) in enumerate(train_loader):
scale_factor = scale_factor * scale_factor_mul
# measure data loading time
data_time.update(time.time() - end)
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input).cuda()
target_var = torch.autograd.Variable(target).cuda()
# compute output
output, scale_vec = model(input_var, scale_factor)
loss = criterion(output, target_var)
loss = loss + float(reg_lambda) * (
scale_vec.norm(1) / float(scale_vec.size(0)) - args.compression_rate) ** 2
# compute channel index
tmp = scale_vec.data.cpu().numpy().reshape(gpu_num, -1).mean(0)
channel_index_list.append(tmp.copy())
if len(channel_index_list) == args.channel_index_range:
channel_index_list = np.array(channel_index_list)
tmp = channel_index_list[0, :]
print('first 5 values: [{0:.6f}, {1:.6f}, {2:.6f}, {3:.6f}, {4:.6f}]'.format(tmp[0], tmp[1], tmp[2], tmp[3],
tmp[4]))
tmp2 = channel_index_list.sum(axis=0)
tmp2 = tmp2 / args.channel_index_range
for tmp_i in range(len(channel_index_list)):
channel_index_list[tmp_i] = (np.sign(channel_index_list[tmp_i] - 0.5) + 1) / 2.0
tmp = channel_index_list.sum(axis=0)
tmp = tmp / args.channel_index_range
channel_index = (np.sign(tmp - 0.5) + 1) / 2.0 # to 0-1 binary
real_pruning_rate = 100.0 * np.sum(tmp2 < 10**-6) / len(tmp2)
binary_pruning_rate = 100.0 * np.sum(channel_index < 10**-6) / len(channel_index)
tmp[tmp == 0] = 1
channel_inconsistency = 100.0 * np.sum(tmp != 1) / len(tmp)
print("pruning rate (real/binary): {0:.4f}%/{1:.4f}%, index inconsistency: {2:.4f}%".format(
real_pruning_rate, binary_pruning_rate, channel_inconsistency))
channel_index_list = list()
reg_lambda = 100.0 * np.abs(binary_pruning_rate/100.0 - 1 + args.compression_rate)
sys.stdout.flush()
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Epoch[{0}]: [{1}/{2}]\t'
'scale_factor: {3:.4f}\t'
'reg_lambda: {4:.4f}\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
epoch, i, len(train_loader), scale_factor, reg_lambda, batch_time=batch_time,
top1=top1, top5=top5))
sys.stdout.flush()
return channel_index, scale_factor
def validate(val_loader, model, criterion, channel_index):
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
for i, (input, target) in enumerate(val_loader):
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input, volatile=True)
target_var = torch.autograd.Variable(target, volatile=True)
# compute output
output, _ = model(input_var, 1.0, channel_index)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
i, len(val_loader), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
sys.stdout.flush()
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
return top1.avg
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, 'model_best.pth.tar')
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def adjust_learning_rate(optimizer, epoch, epoch_num):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = args.lr * (0.1 ** (epoch // epoch_num))
print('| Learning Rate = %f' % lr)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == "__main__":
main()
| 11,382 | 37.849829 | 120 | py |
AutoPruner | AutoPruner-master/vgg16/50/fine_tune_vgg16.py | import argparse
import os
import shutil
import time
import sys
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
from torchvision import datasets, models, transforms
from src_code.lmdbdataset import lmdbDataset
parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
'''parser.add_argument('data', metavar='DIR',
help='path to dataset')
'''
parser.add_argument('-j', '--workers', default=8, type=int, metavar='N',
help='number of data loading workers (default: 8)')
parser.add_argument('--epochs', default=2, type=int, metavar='N',
help='number of total epochs to run')
parser.add_argument('--start-epoch', default=0, type=int, metavar='N',
help='manual epoch number (useful on restarts)')
parser.add_argument('-b', '--batch-size', default=128, type=int,
metavar='N', help='mini-batch size (default: 128)')
parser.add_argument('--lr', '--learning-rate', default=0.0001, type=float,
metavar='LR', help='initial learning rate')
parser.add_argument('--momentum', default=0.9, type=float, metavar='M',
help='momentum')
parser.add_argument('--weight-decay', '--wd', default=1e-4, type=float,
metavar='W', help='weight decay (default: 1e-4)')
parser.add_argument('--print-freq', '-p', default=10, type=int,
metavar='N', help='print frequency (default: 10)')
parser.add_argument('--resume', default='', type=str, metavar='PATH',
help='path to latest checkpoint (default: none)')
parser.add_argument('--evaluate', default=True, type=bool,
help='evaluate model on validation set')
parser.add_argument('--pretrained', dest='pretrained', action='store_true',
help='use pre-trained model')
parser.add_argument('--world-size', default=1, type=int,
help='number of distributed processes')
parser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str,
help='url used to set up distributed training')
parser.add_argument('--dist-backend', default='gloo', type=str,
help='distributed backend')
parser.add_argument('--gpu_id', default='4,5', type=str,
help='id(s) for CUDA_VISIBLE_DEVICES')
parser.add_argument('--data_base', default='/data/zhangcl/ImageNet', type=str, help='the path of dataset')
parser.add_argument('--load_from_lmdb', default=True, type=bool, help='load image data from lmdb or not')
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
best_prec1 = 0
print(args)
def main():
global args, best_prec1
args = parser.parse_args()
args.distributed = args.world_size > 1
if args.distributed:
dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url,
world_size=args.world_size)
# create model
model = models.vgg16(pretrained=True)
model = torch.nn.DataParallel(model.cuda(), device_ids=range(torch.cuda.device_count()))
cudnn.benchmark = True
# define loss function (criterion) and optimizer
criterion = nn.CrossEntropyLoss().cuda()
optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), args.lr,
momentum=args.momentum,
weight_decay=args.weight_decay)
# optionally resume from a checkpoint
if args.resume:
if os.path.isfile(args.resume):
print("=> loading checkpoint '{}'".format(args.resume))
checkpoint = torch.load(args.resume)
args.start_epoch = checkpoint['epoch']
best_prec1 = checkpoint['best_prec1']
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
print("=> loaded checkpoint '{}' (epoch {})"
.format(args.resume, checkpoint['epoch']))
else:
print("=> no checkpoint found at '{}'".format(args.resume))
cudnn.benchmark = True
# Data loading code from lmdb
if args.load_from_lmdb:
train_loader = torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-train.lmdb'), True),
batch_size=args.batch_size,
num_workers=8,
pin_memory=True
)
print('train_loader_success!')
val_loader = torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-val.lmdb'), False),
batch_size=args.batch_size,
num_workers=8,
pin_memory=True
)
else:
traindir = os.path.join('/opt/luojh/Dataset/ImageNet/images', 'train')
valdir = os.path.join('/opt/luojh/Dataset/ImageNet/images', 'val')
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
train_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(traindir, transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])),
batch_size=args.batch_size, shuffle=True,
num_workers=args.workers, pin_memory=True)
val_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(valdir, transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])),
batch_size=args.batch_size, shuffle=False,
num_workers=args.workers, pin_memory=True)
# evaluate and train
if args.evaluate:
validate(val_loader, model, criterion)
return
for epoch in range(args.start_epoch, args.epochs):
adjust_learning_rate(optimizer, epoch)
# train for one epoch
train(train_loader, model, criterion, optimizer, epoch)
# evaluate on validation set
prec1 = validate(val_loader, model, criterion)
# remember best prec@1 and save checkpoint
is_best = prec1 > best_prec1
best_prec1 = max(prec1, best_prec1)
save_checkpoint({
'epoch': epoch + 1,
'arch': args.arch,
'state_dict': model.state_dict(),
'best_prec1': best_prec1,
'optimizer': optimizer.state_dict(),
}, is_best)
torch.save(model.state_dict(), 'checkpoint/model.pth')
def train(train_loader, model, criterion, optimizer, epoch):
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to train mode
model.train()
end = time.time()
for i, (input, target) in enumerate(train_loader):
# measure data loading time
data_time.update(time.time() - end)
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input).cuda()
target_var = torch.autograd.Variable(target).cuda()
# compute output
output = model(input_var)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Epoch: [{0}][{1}/{2}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Data {data_time.val:.3f} ({data_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
epoch, i, len(train_loader), batch_time=batch_time,
data_time=data_time, loss=losses, top1=top1, top5=top5))
sys.stdout.flush()
def validate(val_loader, model, criterion):
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
for i, (input, target) in enumerate(val_loader):
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input, volatile=True)
target_var = torch.autograd.Variable(target, volatile=True)
# compute output
output = model(input_var)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
i, len(val_loader), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
sys.stdout.flush()
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
return top1.avg
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, 'model_best.pth.tar')
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def adjust_learning_rate(optimizer, epoch):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = args.lr * (0.1 ** (epoch // 30))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == '__main__':
main()
| 11,358 | 35.760518 | 106 | py |
AutoPruner | AutoPruner-master/vgg16/50/fine_tune_GAP.py | import argparse
import os
import shutil
import time
import sys
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
from torchvision import datasets, transforms
from src_code.lmdbdataset import lmdbDataset
from compress_model.new_model import vgg16_GAP
parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
'''parser.add_argument('data', metavar='DIR',
help='path to dataset')
'''
parser.add_argument('-j', '--workers', default=8, type=int, metavar='N',
help='number of data loading workers (default: 8)')
parser.add_argument('--epochs', default=24, type=int, metavar='N',
help='number of total epochs to run')
parser.add_argument('--start-epoch', default=0, type=int, metavar='N',
help='manual epoch number (useful on restarts)')
parser.add_argument('-b', '--batch-size', default=256, type=int,
metavar='N', help='mini-batch size (default: 128)')
parser.add_argument('--lr', '--learning-rate', default=0.001, type=float,
metavar='LR', help='initial learning rate')
parser.add_argument('--momentum', default=0.9, type=float, metavar='M',
help='momentum')
parser.add_argument('--weight-decay', '--wd', default=5e-4, type=float,
metavar='W', help='weight decay (default: 1e-4)')
parser.add_argument('--print-freq', '-p', default=10, type=int,
metavar='N', help='print frequency (default: 10)')
parser.add_argument('--resume', default='', type=str, metavar='PATH',
help='path to latest checkpoint (default: none)')
parser.add_argument('--evaluate', default=False, type=bool,
help='evaluate model on validation set')
parser.add_argument('--pretrained', dest='pretrained', action='store_true',
help='use pre-trained model')
parser.add_argument('--world-size', default=1, type=int,
help='number of distributed processes')
parser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str,
help='url used to set up distributed training')
parser.add_argument('--dist-backend', default='gloo', type=str,
help='distributed backend')
parser.add_argument('--gpu_id', default='4,5,6,7', type=str,
help='id(s) for CUDA_VISIBLE_DEVICES')
parser.add_argument('--data_base', default='/data/zhangcl/ImageNet', type=str, help='the path of dataset')
parser.add_argument('--load_from_lmdb', default=True, type=bool, help='load image data from lmdb or not')
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
best_prec1 = 0
print(args)
def main():
global args, best_prec1
args = parser.parse_args()
args.distributed = args.world_size > 1
if args.distributed:
dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url,
world_size=args.world_size)
# create model
model = vgg16_GAP('checkpoint/model.pth')
print(model)
model = torch.nn.DataParallel(model.cuda(), device_ids=range(torch.cuda.device_count()))
cudnn.benchmark = True
# define loss function (criterion) and optimizer
criterion = nn.CrossEntropyLoss().cuda()
optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), args.lr,
momentum=args.momentum,
weight_decay=args.weight_decay)
cudnn.benchmark = True
# Data loading code from lmdb
if args.load_from_lmdb:
train_loader = torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-train.lmdb'), True),
batch_size=args.batch_size,
num_workers=16,
pin_memory=True
)
print('train_loader_success!')
val_loader = torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-val.lmdb'), False),
batch_size=args.batch_size,
num_workers=16,
pin_memory=True
)
else:
traindir = os.path.join('/opt/luojh/Dataset/ImageNet/images', 'train')
valdir = os.path.join('/opt/luojh/Dataset/ImageNet/images', 'val')
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
train_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(traindir, transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])),
batch_size=args.batch_size, shuffle=True,
num_workers=args.workers, pin_memory=True)
val_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(valdir, transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])),
batch_size=args.batch_size, shuffle=False,
num_workers=args.workers, pin_memory=True)
# evaluate and train
if args.evaluate:
validate(val_loader, model, criterion)
return
for epoch in range(args.start_epoch, args.epochs):
adjust_learning_rate(optimizer, epoch, int(args.epochs/3.0))
# train for one epoch
train(train_loader, model, criterion, optimizer, epoch)
# evaluate on validation set
prec1 = validate(val_loader, model, criterion)
# remember best prec@1 and save checkpoint
is_best = prec1 > best_prec1
best_prec1 = max(prec1, best_prec1)
if is_best:
folder_path = 'checkpoint/fine_tune_GAP'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
torch.save(model.state_dict(), folder_path + '/model.pth')
print('best acc is %.3f' % best_prec1)
def train(train_loader, model, criterion, optimizer, epoch):
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to train mode
model.train()
end = time.time()
for i, (input, target) in enumerate(train_loader):
# measure data loading time
data_time.update(time.time() - end)
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input).cuda()
target_var = torch.autograd.Variable(target).cuda()
# compute output
output = model(input_var)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Epoch: [{0}][{1}/{2}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Data {data_time.val:.3f} ({data_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
epoch, i, len(train_loader), batch_time=batch_time,
data_time=data_time, loss=losses, top1=top1, top5=top5))
sys.stdout.flush()
def validate(val_loader, model, criterion):
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
for i, (input, target) in enumerate(val_loader):
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input, volatile=True)
target_var = torch.autograd.Variable(target, volatile=True)
# compute output
output = model(input_var)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
i, len(val_loader), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
sys.stdout.flush()
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
return top1.avg
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, 'model_best.pth.tar')
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def adjust_learning_rate(optimizer, epoch, epoch_num):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = args.lr * (0.1 ** (epoch // epoch_num))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == '__main__':
main()
| 10,791 | 35.707483 | 106 | py |
AutoPruner | AutoPruner-master/vgg16/50/tools/create_lmdb.py | # loads imagenet and writes it into one massive binary file
import os
import numpy as np
from tensorpack.dataflow import *
import sys
if __name__ == '__main__':
if len(sys.argv) < 4 :
print("Usage: python create_lmdb.py gt_file.txt root_folder target_lmdb_name")
print("gt_file.txt split by \"\t\"")
sys.exit(1)
class BinaryDataSet(RNGDataFlow):
def __init__(self,text_name,root_folder):
self.text_name = text_name
self.length = 0
self.root_folder = root_folder
with open(self.text_name,'r') as f:
self.length = len(f.readlines())
self.gt_list = []
with open(self.text_name,'r') as f:
for line in f:
now_list = line.split('\t')
fname = now_list[0]
label = int(now_list[1].strip())
self.gt_list.append((fname,label))
def size(self):
return self.length
def get_data(self):
for fname, label in self.gt_list:
with open(os.path.join(self.root_folder,fname), 'rb') as f:
jpeg = f.read()
jpeg = np.asarray(bytearray(jpeg), dtype='uint8')
yield [jpeg, label]
gt_filename = sys.argv[1]
root_folder = sys.argv[2]
name = sys.argv[3]
ds0 = BinaryDataSet(gt_filename,root_folder)
ds1 = PrefetchDataZMQ(ds0, nr_proc=1)
dftools.dump_dataflow_to_lmdb(ds1, '%s.lmdb'%name)
| 1,514 | 35.95122 | 86 | py |
AutoPruner | AutoPruner-master/vgg16/50/tools/organize_dataset.py | """
this script is used for organize CUB200 dataset:
-- images
-- train
-- [:class 0]
-- [:class 1]
...
-- [:class n]
-- val
-- [:class 0]
-- [:class 1]
...
-- [:class n]
"""
import os
import PIL.Image
import numpy as np
import shutil
original_dataset_path = '/data/luojh/CUB_200_2011/CUB_200_2011'
dest_path = '/opt/luojh/Dataset/CUB/images'
def main():
image_path = os.path.join(original_dataset_path, 'images/')
# Format of images.txt: <image_id> <image_name>
id2name = np.genfromtxt(os.path.join(
original_dataset_path, 'images.txt'), dtype=str)
# Format of train_test_split.txt: <image_id> <is_training_image>
id2train = np.genfromtxt(os.path.join(
original_dataset_path, 'train_test_split.txt'), dtype=int)
for id_ in range(id2name.shape[0]):
image = PIL.Image.open(os.path.join(image_path, id2name[id_, 1]))
folder_name = id2name[id_, 1].split('/')[0]
if id2train[id_, 1] == 1:
# train
save_path = os.path.join(dest_path, 'train', folder_name)
if not os.path.isdir(save_path):
os.makedirs(save_path)
# Convert gray scale image to RGB image.
if image.getbands()[0] == 'L':
image = image.convert('RGB')
image.save(os.path.join(dest_path, 'train', id2name[id_, 1]))
else:
shutil.copyfile(os.path.join(image_path, id2name[id_, 1]),
os.path.join(dest_path, 'train', id2name[id_, 1]))
image.close()
else:
# test
save_path = os.path.join(dest_path, 'val', folder_name)
if not os.path.isdir(save_path):
os.makedirs(save_path)
# Convert gray scale image to RGB image.
if image.getbands()[0] == 'L':
image = image.convert('RGB')
image.save(os.path.join(dest_path, 'val', id2name[id_, 1]))
else:
shutil.copyfile(os.path.join(image_path, id2name[id_, 1]),
os.path.join(dest_path, 'val', id2name[id_, 1]))
image.close()
if __name__ == '__main__':
main()
print('finished')
| 2,295 | 31.8 | 82 | py |
AutoPruner | AutoPruner-master/vgg16/50/src_code/my_op_fc.py | import torch
from torch.autograd import Variable
import torch.nn as nn
from torch.autograd import gradcheck
import numpy as np
class MyGAP_fc(torch.autograd.Function):
'''
Global Average Pooling with batchsize: N*4096 -> 1*4096
'''
@staticmethod
def forward(ctx, input):
ctx.save_for_backward(input)
input = torch.mean(input, dim=0, keepdim=True)
return input
@staticmethod
def backward(ctx, grad_output):
input = ctx.saved_tensors
grad_input = input[0].clone()
for i in range(grad_input.shape[0]):
grad_input[i, :] = grad_output.data / grad_input.shape[0]
return Variable(grad_input)
class MyScale_fc(torch.autograd.Function):
'''
input: x: 64*4096, scale:4096 ==> x[:, i]*scale[i]
'''
@staticmethod
def forward(self, input_data, scale_vec):
self.save_for_backward(input_data, scale_vec)
input_data2 = input_data.clone()
for i in range(scale_vec.shape[0]):
input_data2[:, i] = input_data[:, i] * scale_vec[i]
return input_data2
@staticmethod
def backward(self, grad_output):
input_data, scale_vec = self.saved_tensors
grad_input = input_data.clone()
for i in range(scale_vec.shape[0]):
grad_input[:, i] = grad_output.data[:, i] * scale_vec[i]
grad_vec = scale_vec.clone()
for i in range(scale_vec.shape[0]):
grad_vec[i] = torch.sum(grad_output.data[:, i]*input_data[:, i])
return Variable(grad_input), Variable(grad_vec)
class MyCS_fc(nn.Module):
def __init__(self, channels_num):
super(MyCS_fc, self).__init__()
self.layer_type = 'MyCS_fc'
self.fc = nn.Linear(channels_num, channels_num)
self.sigmoid = nn.Sigmoid()
def forward(self, x, scale_factor):
x_scale = MyGAP_fc.apply(x) # apply my GAP: N*4096 => 1*4096
x_scale = self.fc(x_scale) # 1*4096
x_scale = torch.squeeze(x_scale) # 4096
x_scale = x_scale * scale_factor # apply scale sigmoid
x_scale = self.sigmoid(x_scale)
if not self.training:
index = (np.sign(x_scale.data.cpu().numpy() - 0.5) + 1) / 2.0
x_scale.data = torch.FloatTensor(index).cuda()
x = MyScale_fc.apply(x, x_scale)
return x, x_scale
if __name__ == '__main__':
in_ = (Variable(torch.randn(3, 4).double(), requires_grad=True),
Variable(torch.randn(4).double(), requires_grad=True))
res = gradcheck(MyScale_fc.apply, in_, eps=1e-6, atol=1e-4)
# in_ = (Variable(torch.randn(4, 64).double(), requires_grad=True),)
# res = gradcheck(MyGAP_fc.apply, in_, eps=1e-6, atol=1e-4)
print(res)
| 2,729 | 31.117647 | 76 | py |
AutoPruner | AutoPruner-master/vgg16/50/src_code/my_op.py | import torch
from torch.autograd import Variable
import torch.nn as nn
from torch.autograd import gradcheck
import math
class MyGAP(torch.autograd.Function):
'''
Global Average Pooling with batchsize: N*512*14*14 -> 1*512*14*14
'''
@staticmethod
def forward(ctx, input):
ctx.save_for_backward(input)
input = torch.mean(input, dim=0, keepdim=True)
return input
@staticmethod
def backward(ctx, grad_output):
input = ctx.saved_tensors
grad_input = input[0].clone()
for i in range(grad_input.shape[0]):
grad_input[i, :, :, :] = grad_output.data / grad_input.shape[0]
return Variable(grad_input)
class MyScale(torch.autograd.Function):
'''
input: x: 64*512*7*7, scale:512 ==> x[:, i, :, :]*scale[i]
'''
@staticmethod
def forward(self, input_data, scale_vec):
self.save_for_backward(input_data, scale_vec)
input_data2 = input_data.clone()
for i in range(scale_vec.shape[0]):
input_data2[:, i, :, :] = input_data[:, i, :, :] * scale_vec[i]
return input_data2
@staticmethod
def backward(self, grad_output):
input_data, scale_vec = self.saved_tensors
grad_input = input_data.clone()
for i in range(scale_vec.shape[0]):
grad_input[:, i, :, :] = grad_output.data[:, i, :, :] * scale_vec[i]
grad_vec = scale_vec.clone()
for i in range(scale_vec.shape[0]):
grad_vec[i] = torch.sum(grad_output.data[:, i, :, :]*input_data[:, i, :, :])
return Variable(grad_input), Variable(grad_vec)
class MyCS(nn.Module):
def __init__(self, channels_num, activation_size=14, max_ks=2):
super(MyCS, self).__init__()
self.layer_type = 'MyCS'
self.conv = nn.Conv2d(channels_num, channels_num,
kernel_size=int(activation_size / max_ks), stride=1, padding=0)
self.map = nn.MaxPool2d(kernel_size=max_ks, stride=max_ks)
self.sigmoid = nn.Sigmoid()
# self.conv.weight.data.normal_(0, 0.005)
n = int(activation_size / max_ks) * int(activation_size / max_ks) * channels_num
self.conv.weight.data.normal_(0, 10*math.sqrt(2.0/n))
# torch.nn.init.xavier_normal(self.conv.weight)
# torch.nn.init.constant(self.conv.bias, 0)
def forward(self, x, scale_factor, channel_index=None):
x_scale = MyGAP.apply(x) # apply my GAP: N*512*14*14 => 1*512*14*14
x_scale = self.map(x_scale) # apply MAP: 1*512*14*14 => 1*512*7*7
x_scale = self.conv(x_scale) # 1*512*1*1
x_scale = torch.squeeze(x_scale) # 512
x_scale = x_scale * scale_factor # apply scale sigmoid
x_scale = self.sigmoid(x_scale)
if not self.training:
x_scale.data = torch.FloatTensor(channel_index).cuda()
x = MyScale.apply(x, x_scale)
return x, x_scale
if __name__ == '__main__':
# in_ = (Variable(torch.randn(1, 1, 3, 3).double(), requires_grad=True),
# Variable(torch.randn(1).double(), requires_grad=True))
# res = gradcheck(MyScale.apply, in_, eps=1e-6, atol=1e-4)
in_ = (Variable(torch.randn(2, 64, 3, 3).double(), requires_grad=True),)
res = gradcheck(MyGAP.apply, in_, eps=1e-6, atol=1e-4)
print(res)
| 3,318 | 33.572917 | 93 | py |
AutoPruner | AutoPruner-master/vgg16/50/src_code/Network_FT.py | import torch
from . import my_op
from torch import nn
class NetworkNew(torch.nn.Module):
def __init__(self, layer_id=0):
torch.nn.Module.__init__(self)
model_weight = torch.load('checkpoint/model.pth')
channel_length = list()
channel_length.append(3)
for k, v in model_weight.items():
if 'bias' in k:
channel_length.append(v.size()[0])
self.feature_1 = nn.Sequential()
self.feature_2 = nn.Sequential()
self.classifier = nn.Sequential()
# add channel selection layers
ks_dict = {0: 224, 1: 224, 2: 112, 3: 112, 4: 56, 5: 56, 6: 56, 7: 28, 8: 28, 9: 28, 10: 14, 11: 14, 12: 14}
self.CS = my_op.MyCS(channel_length[layer_id+1], activation_size=ks_dict[layer_id], max_ks=2)
conv_names = {0: 'conv1_1', 1: 'conv1_2', 2: 'conv2_1', 3: 'conv2_2', 4: 'conv3_1', 5: 'conv3_2', 6: 'conv3_3',
7: 'conv4_1', 8: 'conv4_2', 9: 'conv4_3', 10: 'conv5_1', 11: 'conv5_2', 12: 'conv5_3'}
relu_names = {0: 'relu1_1', 1: 'relu1_2', 2: 'relu2_1', 3: 'relu2_2', 4: 'relu3_1', 5: 'relu3_2', 6: 'relu3_3',
7: 'relu4_1', 8: 'relu4_2', 9: 'relu4_3', 10: 'relu5_1', 11: 'relu5_2', 12: 'relu5_3'}
pool_names = {1: 'pool1', 3: 'pool2', 6: 'pool3', 9: 'pool4', 12: 'pool5'}
pooling_layer_id = [1, 3, 6, 9, 12]
# add feature_1 and feature_2 layers
for i in range(13):
if i < layer_id:
self.feature_1.add_module(conv_names[i],
nn.Conv2d(channel_length[i], channel_length[i + 1], kernel_size=3, stride=1,
padding=1))
self.feature_1.add_module(relu_names[i], nn.ReLU(inplace=True))
if i in pooling_layer_id:
self.feature_1.add_module(pool_names[i], nn.MaxPool2d(kernel_size=2, stride=2))
elif i == layer_id:
self.feature_1.add_module(conv_names[i],
nn.Conv2d(channel_length[i], channel_length[i + 1], kernel_size=3, stride=1,
padding=1))
self.feature_1.add_module(relu_names[i], nn.ReLU(inplace=True))
if i in pooling_layer_id:
self.feature_2.add_module(pool_names[i], nn.MaxPool2d(kernel_size=2, stride=2))
elif i > layer_id:
self.feature_2.add_module(conv_names[i],
nn.Conv2d(channel_length[i], channel_length[i + 1], kernel_size=3, stride=1,
padding=1))
self.feature_2.add_module(relu_names[i], nn.ReLU(inplace=True))
if i in pooling_layer_id:
self.feature_2.add_module(pool_names[i], nn.MaxPool2d(kernel_size=2, stride=2))
# add classifier
self.classifier.add_module('fc6', nn.Linear(channel_length[13] * 7 * 7, channel_length[14]))
self.classifier.add_module('relu6', nn.ReLU(inplace=True))
self.classifier.add_module('dropout6', nn.Dropout())
self.classifier.add_module('fc7', nn.Linear(channel_length[14], channel_length[15]))
self.classifier.add_module('relu7', nn.ReLU(inplace=True))
self.classifier.add_module('dropout7', nn.Dropout())
self.classifier.add_module('fc8', nn.Linear(channel_length[15], channel_length[16]))
# load pretrain model weights
my_weight = self.state_dict()
my_keys = list(my_weight.keys())
for k, v in model_weight.items():
name = k.split('.')
name = 'feature_1.'+name[2]+'.'+name[3]
if name in my_keys:
my_weight[name] = v
name = k.split('.')
name = 'feature_2.' + name[2] + '.' + name[3]
if name in my_keys:
my_weight[name] = v
name = k[7:]
if name in my_keys:
my_weight[name] = v
self.load_state_dict(my_weight)
def forward(self, x, scale_factor=1.0, channel_index=None):
x = self.feature_1(x)
x, scale_vector = self.CS(x, scale_factor, channel_index)
x = self.feature_2(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x, scale_vector
class Vgg16(torch.nn.Module):
def __init__(self, model_path):
torch.nn.Module.__init__(self)
self.feature_1 = nn.Sequential()
self.classifier = nn.Sequential()
# add feature layers
self.feature_1.add_module('conv1_1', nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1))
self.feature_1.add_module('relu1_1', nn.ReLU(inplace=True))
self.feature_1.add_module('conv1_2', nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1))
self.feature_1.add_module('relu1_2', nn.ReLU(inplace=True))
self.feature_1.add_module('pool1', nn.MaxPool2d(kernel_size=2, stride=2))
self.feature_1.add_module('conv2_1', nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1))
self.feature_1.add_module('relu2_1', nn.ReLU(inplace=True))
self.feature_1.add_module('conv2_2', nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1))
self.feature_1.add_module('relu2_2', nn.ReLU(inplace=True))
self.feature_1.add_module('pool2', nn.MaxPool2d(kernel_size=2, stride=2))
self.feature_1.add_module('conv3_1', nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1))
self.feature_1.add_module('relu3_1', nn.ReLU(inplace=True))
self.feature_1.add_module('conv3_2', nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1))
self.feature_1.add_module('relu3_2', nn.ReLU(inplace=True))
self.feature_1.add_module('conv3_3', nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1))
self.feature_1.add_module('relu3_3', nn.ReLU(inplace=True))
self.feature_1.add_module('pool3', nn.MaxPool2d(kernel_size=2, stride=2))
self.feature_1.add_module('conv4_1', nn.Conv2d(256, 512, kernel_size=3, stride=1, padding=1))
self.feature_1.add_module('relu4_1', nn.ReLU(inplace=True))
self.feature_1.add_module('conv4_2', nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1))
self.feature_1.add_module('relu4_2', nn.ReLU(inplace=True))
self.feature_1.add_module('conv4_3', nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1))
self.feature_1.add_module('relu4_3', nn.ReLU(inplace=True))
self.feature_1.add_module('pool4', nn.MaxPool2d(kernel_size=2, stride=2))
self.feature_1.add_module('conv5_1', nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1))
self.feature_1.add_module('relu5_1', nn.ReLU(inplace=True))
self.feature_1.add_module('conv5_2', nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1))
self.feature_1.add_module('relu5_2', nn.ReLU(inplace=True))
self.feature_1.add_module('conv5_3', nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1))
self.feature_1.add_module('relu5_3', nn.ReLU(inplace=True))
self.feature_1.add_module('pool5', nn.MaxPool2d(kernel_size=2, stride=2))
# add classifier
self.classifier.add_module('fc6', nn.Linear(512*7*7, 4096))
self.classifier.add_module('relu6', nn.ReLU(inplace=True))
self.classifier.add_module('dropout6', nn.Dropout())
self.classifier.add_module('fc7', nn.Linear(4096, 4096))
self.classifier.add_module('relu7', nn.ReLU(inplace=True))
self.classifier.add_module('dropout7', nn.Dropout())
self.classifier.add_module('fc8', nn.Linear(4096, 1000))
model_weight = torch.load(model_path)
my_weight = self.state_dict()
my_keys = list(my_weight.keys())
count = 0
for k, v in model_weight.items():
my_weight[my_keys[count]] = v
count += 1
self.load_state_dict(my_weight)
def forward(self, x):
x = self.feature_1(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x
| 8,144 | 49.590062 | 119 | py |
AutoPruner | AutoPruner-master/vgg16/50/src_code/lmdbdataset.py | import cv2
import numpy as np
import torchvision.transforms as transforms
import lmdb
import msgpack
from torch.utils.data import Dataset
from PIL import Image
class lmdbDataset(Dataset):
def __init__(self, location, is_train):
self.env = lmdb.open(location, subdir=False, max_readers=1, readonly=True, lock=False, readahead=False,
meminit=False)
self.txn = self.env.begin(write=False)
self.length = self.txn.stat()['entries']
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
# train data augment
if is_train:
self.transform = transforms.Compose([
transforms.Resize(256),
transforms.RandomCrop((224, 224)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])
# test data augment
else:
self.transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])
'''
for key,data in self.txn.cursor():
now_data = msgpack.loads(data,raw=False)
data_img = now_data[0]
label = now_data[1]
now_arr = np.frombuffer(data_img[b'data'],dtype=np.uint8)
print(now_arr)
image_content = cv2.imdecode(now_arr, cv2.IMREAD_COLOR)
print(image_content.shape)
#print(type(_))
break
'''
def __len__(self):
return self.length - 1
def __getitem__(self, index):
new_index = str(index).encode()
data = self.txn.get(new_index)
now_data = msgpack.loads(data, raw=False)
data_img = now_data[0]
label = now_data[1]
now_arr = np.frombuffer(data_img[b'data'], dtype=np.uint8)
image_content = cv2.imdecode(now_arr, cv2.IMREAD_COLOR)
image_content = cv2.cvtColor(image_content, cv2.COLOR_BGR2RGB)
image_content = Image.fromarray(image_content)
image_content = self.transform(image_content)
return image_content, label
if __name__ == '__main__':
temp_dataset = lmdbDataset('indoor67.lmdb', True)
print(temp_dataset[0])
#print(i)
#assert temp_dataset[i][0] is not None | 2,431 | 34.246377 | 111 | py |
AutoPruner | AutoPruner-master/vgg16/50/compress_model/new_model.py | import torch
from torch import nn
import numpy as np
import os
import torch.nn.init as init
class vgg16_compressed(torch.nn.Module):
def __init__(self, layer_id=0, model_path=None):
torch.nn.Module.__init__(self)
model_weight = torch.load(model_path + 'model.pth')
channel_index = torch.load(model_path + 'channel_index.pth')
channel_index = np.where(channel_index != 0)[0]
new_num = int(channel_index.shape[0])
channel_length = list()
channel_length.append(3)
for k, v in model_weight.items():
if 'bias' in k:
channel_length.append(v.size()[0])
channel_length[layer_id + 1] = new_num
self.feature_1 = nn.Sequential()
self.classifier = nn.Sequential()
# add channel selection layers
conv_names = {0: 'conv1_1', 1: 'conv1_2', 2: 'conv2_1', 3: 'conv2_2', 4: 'conv3_1', 5: 'conv3_2', 6: 'conv3_3',
7: 'conv4_1', 8: 'conv4_2', 9: 'conv4_3', 10: 'conv5_1', 11: 'conv5_2', 12: 'conv5_3'}
relu_names = {0: 'relu1_1', 1: 'relu1_2', 2: 'relu2_1', 3: 'relu2_2', 4: 'relu3_1', 5: 'relu3_2', 6: 'relu3_3',
7: 'relu4_1', 8: 'relu4_2', 9: 'relu4_3', 10: 'relu5_1', 11: 'relu5_2', 12: 'relu5_3'}
pool_names = {1: 'pool1', 3: 'pool2', 6: 'pool3', 9: 'pool4', 12: 'pool5'}
pooling_layer_id = [1, 3, 6, 9, 12]
# add feature_1 and feature_2 layers
for i in range(13):
self.feature_1.add_module(conv_names[i],
nn.Conv2d(channel_length[i], channel_length[i + 1], kernel_size=3, stride=1,
padding=1))
self.feature_1.add_module(relu_names[i], nn.ReLU(inplace=True))
if i in pooling_layer_id:
self.feature_1.add_module(pool_names[i], nn.MaxPool2d(kernel_size=2, stride=2))
# add classifier
self.classifier.add_module('fc6', nn.Linear(channel_length[13] * 7 * 7, channel_length[14]))
self.classifier.add_module('relu6', nn.ReLU(inplace=True))
self.classifier.add_module('dropout6', nn.Dropout())
self.classifier.add_module('fc7', nn.Linear(channel_length[14], channel_length[15]))
self.classifier.add_module('relu7', nn.ReLU(inplace=True))
self.classifier.add_module('dropout7', nn.Dropout())
self.classifier.add_module('fc8', nn.Linear(channel_length[15], channel_length[16]))
# load pretrain model weights
my_weight = self.state_dict()
my_keys = list(my_weight.keys())
channel_index = torch.cuda.LongTensor(channel_index)
if layer_id < 12:
# conv1_1 to conv5_2
for k, v in model_weight.items():
name = k.split('.')
if name[2] == conv_names[layer_id]:
if name[3] == 'weight':
name = 'feature_1.' + name[2] + '.' + name[3]
my_weight[name] = v[channel_index, :, :, :]
else:
name = 'feature_1.' + name[2] + '.' + name[3]
my_weight[name] = v[channel_index]
elif name[2] == conv_names[layer_id + 1]:
if name[3] == 'weight':
name = 'feature_1.' + name[2] + '.' + name[3]
my_weight[name] = v[:, channel_index, :, :]
else:
name = 'feature_1.' + name[2] + '.' + name[3]
my_weight[name] = v
else:
if name[1] in ['feature_1', 'feature_2']:
name = 'feature_1.' + name[2] + '.' + name[3]
else:
name = name[1] + '.' + name[2] + '.' + name[3]
if name in my_keys:
my_weight[name] = v
elif layer_id == 12:
# conv5_3
for k, v in model_weight.items():
name = k.split('.')
if name[2] == conv_names[layer_id]:
if name[3] == 'weight':
name = 'feature_1.' + name[2] + '.' + name[3]
my_weight[name] = v[channel_index, :, :, :]
else:
name = 'feature_1.' + name[2] + '.' + name[3]
my_weight[name] = v[channel_index]
elif name[2] == 'fc6':
if name[3] == 'weight':
name = 'classifier.' + name[2] + '.' + name[3]
tmp = v.view(4096, 512, 7, 7)
tmp = tmp[:, channel_index, :, :]
my_weight[name] = tmp.view(4096, -1)
else:
name = 'classifier.' + name[2] + '.' + name[3]
my_weight[name] = v
else:
if name[1] in ['feature_1', 'feature_2']:
name = 'feature_1.' + name[2] + '.' + name[3]
else:
name = name[1] + '.' + name[2] + '.' + name[3]
if name in my_keys:
my_weight[name] = v
self.load_state_dict(my_weight)
def forward(self, x):
x = self.feature_1(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x
class vgg16_test(torch.nn.Module):
def __init__(self, model_path):
torch.nn.Module.__init__(self)
model_weight = torch.load(model_path)
channel_length = list()
channel_length.append(3)
for k, v in model_weight.items():
if 'bias' in k:
channel_length.append(v.size()[0])
self.feature_1 = nn.Sequential()
self.classifier = nn.Sequential()
# add channel selection layers
conv_names = {0: 'conv1_1', 1: 'conv1_2', 2: 'conv2_1', 3: 'conv2_2', 4: 'conv3_1', 5: 'conv3_2', 6: 'conv3_3',
7: 'conv4_1', 8: 'conv4_2', 9: 'conv4_3', 10: 'conv5_1', 11: 'conv5_2', 12: 'conv5_3'}
relu_names = {0: 'relu1_1', 1: 'relu1_2', 2: 'relu2_1', 3: 'relu2_2', 4: 'relu3_1', 5: 'relu3_2', 6: 'relu3_3',
7: 'relu4_1', 8: 'relu4_2', 9: 'relu4_3', 10: 'relu5_1', 11: 'relu5_2', 12: 'relu5_3'}
pool_names = {1: 'pool1', 3: 'pool2', 6: 'pool3', 9: 'pool4', 12: 'pool5'}
pooling_layer_id = [1, 3, 6, 9, 12]
# add feature_1 and feature_2 layers
for i in range(13):
self.feature_1.add_module(conv_names[i],
nn.Conv2d(channel_length[i], channel_length[i + 1], kernel_size=3, stride=1,
padding=1))
self.feature_1.add_module(relu_names[i], nn.ReLU(inplace=True))
if i in pooling_layer_id:
self.feature_1.add_module(pool_names[i], nn.MaxPool2d(kernel_size=2, stride=2))
# add classifier
self.classifier.add_module('fc6', nn.Linear(channel_length[13] * 7 * 7, channel_length[14]))
self.classifier.add_module('relu6', nn.ReLU(inplace=True))
self.classifier.add_module('dropout6', nn.Dropout())
self.classifier.add_module('fc7', nn.Linear(channel_length[14], channel_length[15]))
self.classifier.add_module('relu7', nn.ReLU(inplace=True))
self.classifier.add_module('dropout7', nn.Dropout())
self.classifier.add_module('fc8', nn.Linear(channel_length[15], channel_length[16]))
# load pretrain model weights
my_weight = self.state_dict()
my_keys = list(my_weight.keys())
for k, v in model_weight.items():
name = k.split('.')
name = name[1] + '.' + name[2] + '.' + name[3]
if name in my_keys:
my_weight[name] = v
else:
print('error')
os.exit(0)
self.load_state_dict(my_weight)
def forward(self, x):
x = self.feature_1(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x
class vgg16_GAP(torch.nn.Module):
def __init__(self, model_path):
torch.nn.Module.__init__(self)
model_weight = torch.load(model_path)
channel_length = list()
channel_length.append(3)
for k, v in model_weight.items():
if 'bias' in k:
channel_length.append(v.size()[0])
self.feature_1 = nn.Sequential()
self.classifier = nn.Sequential()
# add channel selection layers
conv_names = {0: 'conv1_1', 1: 'conv1_2', 2: 'conv2_1', 3: 'conv2_2', 4: 'conv3_1', 5: 'conv3_2', 6: 'conv3_3',
7: 'conv4_1', 8: 'conv4_2', 9: 'conv4_3', 10: 'conv5_1', 11: 'conv5_2', 12: 'conv5_3'}
relu_names = {0: 'relu1_1', 1: 'relu1_2', 2: 'relu2_1', 3: 'relu2_2', 4: 'relu3_1', 5: 'relu3_2', 6: 'relu3_3',
7: 'relu4_1', 8: 'relu4_2', 9: 'relu4_3', 10: 'relu5_1', 11: 'relu5_2', 12: 'relu5_3'}
pool_names = {1: 'pool1', 3: 'pool2', 6: 'pool3', 9: 'pool4', 12: 'pool5'}
pooling_layer_id = [1, 3, 6, 9]
# add feature_1 and feature_2 layers
for i in range(13):
self.feature_1.add_module(conv_names[i],
nn.Conv2d(channel_length[i], channel_length[i + 1], kernel_size=3, stride=1,
padding=1))
self.feature_1.add_module(relu_names[i], nn.ReLU(inplace=True))
if i in pooling_layer_id:
self.feature_1.add_module(pool_names[i], nn.MaxPool2d(kernel_size=2, stride=2))
if i == 12:
self.feature_1.add_module(pool_names[i], nn.AvgPool2d(kernel_size=14, stride=1))
# add classifier
self.classifier.add_module('fc', nn.Linear(channel_length[13], channel_length[16]))
init.xavier_uniform(self.classifier.fc.weight, gain=np.sqrt(2.0))
init.constant(self.classifier.fc.bias, 0)
# load pretrain model weights
my_weight = self.state_dict()
my_keys = list(my_weight.keys())
for k, v in model_weight.items():
name = k.split('.')
name = name[1] + '.' + name[2] + '.' + name[3]
if name in my_keys:
my_weight[name] = v
else:
print(name)
self.load_state_dict(my_weight)
def forward(self, x):
x = self.feature_1(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x
if __name__ == '__main__':
model = vgg16_GAP('../checkpoint/fine_tune/model.pth')
print(model)
| 10,696 | 43.570833 | 119 | py |
AutoPruner | AutoPruner-master/vgg16/50/compress_model/compress_model.py | import torch
from new_model import vgg16_compressed
import argparse
import torch.backends.cudnn as cudnn
parser = argparse.ArgumentParser(description='PyTorch Digital Mammography Training')
parser.add_argument('--layer_id', default=2, type=int, help='the id of compressed layer, starting from 0')
args = parser.parse_args()
print(args)
def main(model_path):
# 1. create compressed model
vgg16_new = vgg16_compressed(layer_id=args.layer_id, model_path=model_path)
# Phase 2 : Model setup
vgg16_new = vgg16_new.cuda()
vgg16_new = torch.nn.DataParallel(vgg16_new.cuda(), device_ids=range(torch.cuda.device_count()))
cudnn.benchmark = True
new_model_param = vgg16_new.state_dict()
torch.save(new_model_param, '../checkpoint/model.pth')
print('Finished!')
if __name__ == '__main__':
folder_path = '../checkpoint/layer_' + str(args.layer_id)+'/'
main(folder_path)
| 908 | 31.464286 | 106 | py |
AutoPruner | AutoPruner-master/vgg16/50/compress_model/evaluate_net.py | import torch
from new_model import vgg16_compressed, vgg16_test
import argparse
import torch.backends.cudnn as cudnn
import os
import sys
import time
sys.path.append('../')
from src_code.lmdbdataset import lmdbDataset
parser = argparse.ArgumentParser(description='PyTorch Digital Mammography Training')
parser.add_argument('--batch_size', default=500, type=int, help='batch size')
parser.add_argument('--data_base', default='/data/zhangcl/ImageNet', type=str, help='the path of dataset')
parser.add_argument('--gpu_id', default='4,5,6,7', type=str,
help='id(s) for CUDA_VISIBLE_DEVICES')
args = parser.parse_args()
print(args)
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
def main(model_path):
# 1. create compressed model
vgg16_new = vgg16_compressed(layer_id=args.layer_id, model_path=model_path)
# Phase 2 : Model setup
vgg16_new = vgg16_new.cuda()
vgg16_new = torch.nn.DataParallel(vgg16_new.cuda(), device_ids=range(torch.cuda.device_count()))
cudnn.benchmark = True
new_model_param = vgg16_new.state_dict()
torch.save(new_model_param, model_path+'model.pth')
print('Finished!')
return vgg16_new
def evaluate():
# Phase 1: load model
model = vgg16_test('../checkpoint/model.pth')
# Phase 2 : Model setup
model = model.cuda()
model = torch.nn.DataParallel(model.cuda(), device_ids=range(torch.cuda.device_count()))
cudnn.benchmark = True
# Phase 2 : Data Upload
print('\n[Phase 2] : Data Preperation')
dset_loaders = {
'train': torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-train.lmdb'), True),
batch_size=args.batch_size,
shuffle=True,
num_workers=8,
pin_memory=True),
'val': torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-val.lmdb'), False),
batch_size=args.batch_size,
num_workers=8,
pin_memory=True)
}
print('data_loader_success!')
# Phase 3: Validation
print("\n[Phase 3 : Inference on val")
criterion = torch.nn.CrossEntropyLoss().cuda()
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
for batch_idx, (input, target) in enumerate(dset_loaders['val']): # dset_loaders['val']):
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input, volatile=True)
target_var = torch.autograd.Variable(target, volatile=True)
# compute output
output = model(input_var)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
batch_idx, len(dset_loaders['val']), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
sys.stdout.flush()
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == '__main__':
evaluate()
| 4,451 | 31.977778 | 106 | py |
AutoPruner | AutoPruner-master/MobileNetv2/released_model/evaluate.py | import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import time
import os
import sys
import argparse
from torchvision import datasets, transforms
import mobilenetv2
from torchsummaryX import summary
parser = argparse.ArgumentParser(description='PyTorch Digital Mammography Training')
parser.add_argument('--lr', default=0.001, type=float, help='learning rate')
parser.add_argument('--weight_decay', default=1e-4, type=float, help='weight decay')
parser.add_argument('--batch_size', default=64, type=int, help='batch size')
parser.add_argument('--num_epochs', default=0, type=int, help='number of training epochs')
parser.add_argument('--lr_decay_epoch', default=10, type=int, help='learning rate decay epoch')
parser.add_argument('--data_base', default='/mnt/ramdisk/ImageNet', type=str, help='the path of dataset')
parser.add_argument('--gpu_id', default='2', type=str,
help='id(s) for CUDA_VISIBLE_DEVICES')
parser.add_argument('--start_epoch', default=0, type=int, metavar='N',
help='manual epoch number (useful on restarts)')
parser.add_argument('--print-freq', '-p', default=20, type=int,
metavar='N', help='print frequency (default: 10)')
parser.add_argument('--ft_model_path', default='mobilenetv2-pruned.pth',
type=str, help='the path of fine tuned model')
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
best_prec1 = -1
print(args)
def main():
global args, best_prec1
# Phase 1 : Model setup
print('\n[Phase 2] : Model setup')
model = mobilenetv2.MobileNetV2(args.ft_model_path)
model.eval()
summary(model, torch.zeros((1, 3, 224, 224)))
model_ft = torch.nn.DataParallel(model.cuda())
cudnn.benchmark = True
print("model setup success!")
# Phase 2 : Data Load
# Data pre-processing
data_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop(224),
# transforms.Resize(256),
# transforms.RandomCrop((224, 224)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
]),
'val': transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
}
data_dir = args.data_base
print("| Preparing data...")
dsets = {
x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x])
for x in ['train', 'val']
}
val_loader = torch.utils.data.DataLoader(dsets['val'], batch_size=args.batch_size, shuffle=False, num_workers=8,
pin_memory=True)
print('data_loader_success!')
# Phase 3: fine_tune model
print('\n[Phase 3] : Model fine tune')
# define loss function (criterion) and optimizer
criterion = nn.CrossEntropyLoss().cuda()
validate(val_loader, model_ft, criterion)
def validate(val_loader, model, criterion):
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
for i, (input, target) in enumerate(val_loader):
input, target = input.cuda(), target.cuda()
# compute output
output = model(input)
loss = criterion(output, target)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data.item(), input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
i, len(val_loader), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
sys.stdout.flush()
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
return top1.avg
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def adjust_learning_rate(optimizer, epoch, epoch_num):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = args.lr * (0.1 ** (epoch // epoch_num))
print('| Learning Rate = %f' % lr)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == "__main__":
main()
| 5,806 | 32.761628 | 116 | py |
AutoPruner | AutoPruner-master/MobileNetv2/released_model/mobilenetv2.py | """
Creates a MobileNetV2 Model as defined in:
Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen. (2018).
MobileNetV2: Inverted Residuals and Linear Bottlenecks
arXiv preprint arXiv:1801.04381.
import from https://github.com/tonylins/pytorch-mobilenet-v2
"""
import torch.nn as nn
import math
import torch
import numpy as np
__all__ = ['mobilenetv2']
def _make_divisible(v, divisor, min_value=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
:param v:
:param divisor:
:param min_value:
:return:
"""
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
# Make sure that round down does not go down by more than 10%.
if new_v < 0.9 * v:
new_v += divisor
return new_v
def conv_3x3_bn(inp, oup, stride):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
nn.BatchNorm2d(oup),
nn.ReLU6(inplace=True)
)
def conv_1x1_bn(inp, oup):
return nn.Sequential(
nn.Conv2d(inp, oup, 1, 1, 0, bias=False),
nn.BatchNorm2d(oup),
nn.ReLU6(inplace=True)
)
class InvertedResidual(nn.Module):
def __init__(self, channel_number, inp, oup, stride, expand_ratio):
super(InvertedResidual, self).__init__()
assert stride in [1, 2]
hidden_dim = round(inp * expand_ratio)
self.identity = stride == 1 and inp == oup
if expand_ratio == 1:
self.conv = nn.Sequential(
# dw
nn.Conv2d(inp, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),
nn.BatchNorm2d(hidden_dim),
nn.ReLU6(inplace=True),
# pw-linear
nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
nn.BatchNorm2d(oup),
)
else:
hidden_dim = channel_number.pop(0)
self.conv = nn.Sequential(
# pw
nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False),
nn.BatchNorm2d(hidden_dim),
nn.ReLU6(inplace=True),
# dw
nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),
nn.BatchNorm2d(hidden_dim),
nn.ReLU6(inplace=True),
# pw-linear
nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
nn.BatchNorm2d(oup),
)
def forward(self, x):
if self.identity:
return x + self.conv(x)
else:
return self.conv(x)
class MobileNetV2(nn.Module):
def __init__(self, model_path, num_classes=1000, width_mult=1.):
super(MobileNetV2, self).__init__()
# setting of inverted residual blocks
self.cfgs = [
# t, c, n, s
[1, 16, 1, 1],
[6, 24, 2, 2],
[6, 32, 3, 2],
[6, 64, 4, 2],
[6, 96, 3, 1],
[6, 160, 3, 2],
[6, 320, 1, 1],
]
# load channel index
file_path = model_path.split('mobilenet')[0]
f = open('channel_index_AP.txt')
lines = f.readlines()
channel_number = []
for line in lines:
line = line.split(', ')
line = line[0:-1] # remove '\n'
tmp = []
for item in line:
tmp.append(int(float(item)))
channel_number.append(int(np.sum(tmp)))
f.close()
# building first layer
input_channel = _make_divisible(32 * width_mult, 4 if width_mult == 0.1 else 8)
layers = [conv_3x3_bn(3, input_channel, 2)]
# building inverted residual blocks
block = InvertedResidual
for t, c, n, s in self.cfgs:
output_channel = _make_divisible(c * width_mult, 4 if width_mult == 0.1 else 8)
for i in range(n):
layers.append(block(channel_number, input_channel, output_channel, s if i == 0 else 1, t))
input_channel = output_channel
# building last several layers
output_channel = _make_divisible(1280 * width_mult, 4 if width_mult == 0.1 else 8) if width_mult > 1.0 else 1280
layers.append(conv_1x1_bn(input_channel, output_channel))
self.features = nn.Sequential(*layers)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.classifier = nn.Linear(output_channel, num_classes)
self._initialize_weights(model_path)
def forward(self, x):
x = self.features(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x
def _initialize_weights(self, model_path):
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
if m.bias is not None:
m.bias.data.zero_()
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
m.weight.data.normal_(0, 0.01)
m.bias.data.zero_()
# initialized from pretrained model
model_weight = torch.load(model_path)
my_weight = self.state_dict()
my_keys = list(my_weight)
for i, (k, v) in enumerate(model_weight.items()):
my_weight[my_keys[i]] = v
self.load_state_dict(my_weight)
| 5,774 | 32.77193 | 120 | py |
AutoPruner | AutoPruner-master/MobileNetv2/2_fine_tune/main.py | import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import time
import os
import sys
import argparse
from torchvision import datasets, transforms
from src_code import mobilenetv2
from torchsummaryX import summary
from math import cos, pi
parser = argparse.ArgumentParser(description='PyTorch Digital Mammography Training')
parser.add_argument('--lr', default=0.01, type=float, help='learning rate')
parser.add_argument('--weight_decay', default=4e-5, type=float, help='weight decay')
parser.add_argument('--batch_size', default=256, type=int, help='batch size')
parser.add_argument('--num_epochs', default=150, type=int, help='number of training epochs')
parser.add_argument('--lr_decay_epoch', default=10, type=int, help='learning rate decay epoch')
parser.add_argument('--data_base', default='/mnt/ramdisk/ImageNet', type=str, help='the path of dataset')
parser.add_argument('--gpu_id', default='4,5,6,7', type=str,
help='id(s) for CUDA_VISIBLE_DEVICES')
parser.add_argument('--start_epoch', default=0, type=int, metavar='N',
help='manual epoch number (useful on restarts)')
parser.add_argument('--print-freq', '-p', default=20, type=int,
metavar='N', help='print frequency (default: 10)')
parser.add_argument('--resume', default=False, type=bool,
help='path to latest checkpoint (default: none)')
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
best_prec1 = -1
print(args)
def main():
global args, best_prec1
# Phase 1 : Model setup
print('\n[Phase 2] : Model setup')
model = mobilenetv2.MobileNetV2('../1_pruning/checkpoint/model.pth')
model.eval()
summary(model, torch.zeros((1, 3, 224, 224)))
model_ft = torch.nn.DataParallel(model.cuda())
cudnn.benchmark = True
print("model setup success!")
if args.resume:
weight = torch.load('checkpoint/model.pth')
model_ft.load_state_dict(weight)
# Phase 2 : Data Load
# Data pre-processing
data_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop(224, scale=(0.2, 1.0)),
# transforms.Resize(256),
# transforms.RandomCrop((224, 224)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
]),
'val': transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
}
data_dir = args.data_base
print("| Preparing data...")
dsets = {
x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x])
for x in ['train', 'val']
}
train_loader = torch.utils.data.DataLoader(dsets['train'], batch_size=args.batch_size, shuffle=True, num_workers=8,
pin_memory=True)
val_loader = torch.utils.data.DataLoader(dsets['val'], batch_size=args.batch_size, shuffle=False, num_workers=8,
pin_memory=True)
print('data_loader_success!')
# Phase 3: fine_tune model
print('\n[Phase 3] : Model fine tune')
# define loss function (criterion) and optimizer
criterion = nn.CrossEntropyLoss().cuda()
optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model_ft.parameters()), args.lr,
momentum=0.9,
weight_decay=args.weight_decay)
validate(val_loader, model_ft, criterion)
for epoch in range(args.start_epoch, args.num_epochs):
# adjust_learning_rate(optimizer, epoch, 10) # reduce lr every 3 epochs
# train for one epoch
time1 = time.time()
train(train_loader, model_ft, criterion, optimizer, epoch)
print('training one epoch takes {0:.3f} seconds.'.format(time.time()-time1))
# evaluate on validation set
prec1 = validate(val_loader, model_ft, criterion)
# remember best prec@1 and save checkpoint
is_best = prec1 > best_prec1
if is_best:
best_prec1 = prec1
print('best accuracy is {0:.3f}'.format(best_prec1))
folder_path = 'checkpoint'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
torch.save(model_ft.state_dict(), folder_path+'/model.pth')
def train(train_loader, model, criterion, optimizer, epoch):
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to train mode
model.train()
end = time.time()
for i, (input, target) in enumerate(train_loader):
# measure data loading time
adjust_learning_rate(optimizer, epoch, i, len(train_loader))
data_time.update(time.time() - end)
input, target = input.cuda(), target.cuda()
# compute output
output = model(input)
# calculate loss
loss = criterion(output, target)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data.item(), input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Epoch[{0}]: [{1}/{2}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})\t'
'Loss {loss.val:.3f} ({loss.avg:.3f})'.format(
epoch, i, len(train_loader), batch_time=batch_time,
top1=top1, top5=top5, loss=losses))
sys.stdout.flush()
def validate(val_loader, model, criterion):
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
for i, (input, target) in enumerate(val_loader):
input, target = input.cuda(), target.cuda()
# compute output
output = model(input)
loss = criterion(output, target)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data.item(), input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
i, len(val_loader), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
sys.stdout.flush()
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
return top1.avg
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
# step lr
# def adjust_learning_rate(optimizer, epoch, epoch_num):
# """Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
# lr = args.lr * (0.1 ** (epoch // epoch_num))
# print('| Learning Rate = %f' % lr)
# for param_group in optimizer.param_groups:
# param_group['lr'] = lr
# consine lr
def adjust_learning_rate(optimizer, epoch, iteration, num_iter):
warmup_epoch = 0
warmup_iter = warmup_epoch * num_iter
current_iter = iteration + epoch * num_iter
max_iter = args.num_epochs * num_iter
lr = args.lr * (1 + cos(pi * (current_iter - warmup_iter) / (max_iter - warmup_iter))) / 2
if epoch < warmup_epoch:
lr = args.lr * current_iter / warmup_iter
if iteration == 0:
print('current learning rate:{0}'.format(lr))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == "__main__":
main()
| 9,434 | 33.944444 | 119 | py |
AutoPruner | AutoPruner-master/MobileNetv2/2_fine_tune/src_code/mobilenetv2.py | """
Creates a MobileNetV2 Model as defined in:
Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen. (2018).
MobileNetV2: Inverted Residuals and Linear Bottlenecks
arXiv preprint arXiv:1801.04381.
import from https://github.com/tonylins/pytorch-mobilenet-v2
"""
import torch.nn as nn
import torch
import numpy as np
__all__ = ['mobilenetv2']
def _make_divisible(v, divisor, min_value=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
:param v:
:param divisor:
:param min_value:
:return:
"""
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
# Make sure that round down does not go down by more than 10%.
if new_v < 0.9 * v:
new_v += divisor
return new_v
def conv_3x3_bn(inp, oup, stride):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
nn.BatchNorm2d(oup),
nn.ReLU6(inplace=True)
)
def conv_1x1_bn(inp, oup):
return nn.Sequential(
nn.Conv2d(inp, oup, 1, 1, 0, bias=False),
nn.BatchNorm2d(oup),
nn.ReLU6(inplace=True)
)
class InvertedResidual(nn.Module):
def __init__(self, channel_number, inp, oup, stride, expand_ratio):
super(InvertedResidual, self).__init__()
assert stride in [1, 2]
hidden_dim = round(inp * expand_ratio)
self.identity = stride == 1 and inp == oup
if expand_ratio == 1:
self.conv = nn.Sequential(
# dw
nn.Conv2d(inp, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),
nn.BatchNorm2d(hidden_dim),
nn.ReLU6(inplace=True),
# pw-linear
nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
nn.BatchNorm2d(oup),
)
else:
hidden_dim = channel_number.pop(0)
self.conv = nn.Sequential(
# pw
nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False),
nn.BatchNorm2d(hidden_dim),
nn.ReLU6(inplace=True),
# dw
nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),
nn.BatchNorm2d(hidden_dim),
nn.ReLU6(inplace=True),
# pw-linear
nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
nn.BatchNorm2d(oup),
)
def forward(self, x):
if self.identity:
return x + self.conv(x)
else:
return self.conv(x)
class MobileNetV2(nn.Module):
def __init__(self, model_path, num_classes=1000, width_mult=1.):
super(MobileNetV2, self).__init__()
# setting of inverted residual blocks
self.cfgs = [
# t, c, n, s
[1, 16, 1, 1],
[6, 24, 2, 2],
[6, 32, 3, 2],
[6, 64, 4, 2],
[6, 96, 3, 1],
[6, 160, 3, 2],
[6, 320, 1, 1],
]
# load channel index
f = open('../1_pruning/checkpoint/channel_index.txt')
lines = f.readlines()
index_code = []
channel_number = []
for line in lines:
line = line.split(', ')
line = line[0:-1] # remove '\n'
tmp = []
for item in line:
tmp.append(int(float(item)))
index_code.append(tmp)
channel_number.append(int(np.sum(tmp)))
f.close()
# building first layer
input_channel = _make_divisible(32 * width_mult, 4 if width_mult == 0.1 else 8)
layers = [conv_3x3_bn(3, input_channel, 2)]
# building inverted residual blocks
block = InvertedResidual
for t, c, n, s in self.cfgs:
output_channel = _make_divisible(c * width_mult, 4 if width_mult == 0.1 else 8)
for i in range(n):
layers.append(block(channel_number, input_channel, output_channel, s if i == 0 else 1, t))
input_channel = output_channel
self.features = nn.Sequential(*layers)
# building last several layers
output_channel = _make_divisible(1280 * width_mult, 4 if width_mult == 0.1 else 8) if width_mult > 1.0 else 1280
self.conv = conv_1x1_bn(input_channel, output_channel)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.classifier = nn.Linear(output_channel, num_classes)
self._initialize_weights(model_path, index_code)
def forward(self, x):
x = self.features(x)
x = self.conv(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x
def _initialize_weights(self, model_path, index_code):
model_weight = torch.load(model_path)
my_weight = self.state_dict()
my_keys = list(my_weight.keys())
i = 0
for k, v in model_weight.items():
if 'AP' in k:
if 'AP.conv.bias' in k and i != 6:
index = index_code.pop(0)
ind_ = np.array(index).nonzero()[0]
continue
if 'num_batches_tracked' in k:
i = i + 1
continue
if i < 18 or i > 305:
# not pruned, # layers = (306-18)/6=48, 16blocks=16*3=48 layers
my_weight[my_keys[i]] = v
else:
# pruned blocks, 3 layers/block
if len(my_weight[my_keys[i]]) == len(ind_):
my_weight[my_keys[i]] = v[ind_] # the first and second layer, conv+bn, 6 layers
elif 'conv.6.weight' in my_keys[i]:
my_weight[my_keys[i]] = v[:, ind_, :, :] # remove the conv layer of third layer
else:
my_weight[my_keys[i]] = v # not change
i = i + 1
self.load_state_dict(my_weight)
def mobilenetv2(**kwargs):
"""
Constructs a MobileNet V2 model
"""
return MobileNetV2(**kwargs)
if __name__ == '__main__':
model = MobileNetV2('../../1_pruning/checkpoint/model.pth')
| 6,370 | 32.356021 | 120 | py |
AutoPruner | AutoPruner-master/MobileNetv2/2_fine_tune/src_code/Network_FT.py | import torch
from torch import nn
import numpy as np
class VGG16(torch.nn.Module):
def __init__(self, model_path):
torch.nn.Module.__init__(self)
self.maxpool = nn.MaxPool2d(kernel_size=2, stride=2)
self.ReLU = nn.ReLU(inplace=True)
# load channel index
f = open('../1_pruning/checkpoint/channel_index.txt')
lines = f.readlines()
index_code = []
channel_number = []
for line in lines:
line = line.split(', ')
line = line[0:-1] # remove '\n'
tmp = []
for item in line:
tmp.append(int(float(item)))
index_code.append(tmp)
channel_number.append(np.sum(tmp))
f.close()
# add feature layers
self.conv1_1 = nn.Conv2d(3, channel_number[0], kernel_size=3, stride=1, padding=1)
self.conv1_2 = nn.Conv2d(channel_number[0], channel_number[1], kernel_size=3, stride=1, padding=1)
self.conv2_1 = nn.Conv2d(channel_number[1], channel_number[2], kernel_size=3, stride=1, padding=1)
self.conv2_2 = nn.Conv2d(channel_number[2], channel_number[3], kernel_size=3, stride=1, padding=1)
self.conv3_1 = nn.Conv2d(channel_number[3], channel_number[4], kernel_size=3, stride=1, padding=1)
self.conv3_2 = nn.Conv2d(channel_number[4], channel_number[5], kernel_size=3, stride=1, padding=1)
self.conv3_3 = nn.Conv2d(channel_number[5], channel_number[6], kernel_size=3, stride=1, padding=1)
self.conv4_1 = nn.Conv2d(channel_number[6], channel_number[7], kernel_size=3, stride=1, padding=1)
self.conv4_2 = nn.Conv2d(channel_number[7], channel_number[8], kernel_size=3, stride=1, padding=1)
self.conv4_3 = nn.Conv2d(channel_number[8], channel_number[9], kernel_size=3, stride=1, padding=1)
self.conv5_1 = nn.Conv2d(channel_number[9], channel_number[10], kernel_size=3, stride=1, padding=1)
self.conv5_2 = nn.Conv2d(channel_number[10], channel_number[11], kernel_size=3, stride=1, padding=1)
self.conv5_3 = nn.Conv2d(channel_number[11], 512, kernel_size=3, stride=1, padding=1)
# add classifier
self.classifier = nn.Sequential()
self.classifier.add_module('fc6', nn.Linear(512*7*7, 4096))
self.classifier.add_module('relu6', nn.ReLU(inplace=True))
self.classifier.add_module('dropout6', nn.Dropout())
self.classifier.add_module('fc7', nn.Linear(4096, 4096))
self.classifier.add_module('relu7', nn.ReLU(inplace=True))
self.classifier.add_module('dropout7', nn.Dropout())
self.classifier.add_module('fc8', nn.Linear(4096, 1000))
model_weight = torch.load(model_path)
my_weight = self.state_dict()
my_keys = list(my_weight.keys())
count = 0
i = 0
ind_old = [0, 1, 2]
for k, v in model_weight.items():
if 'AP' in k:
continue
if 'conv' in k:
if 'conv5_3' in k:
if 'weight' in k:
my_weight[my_keys[i]] = v[:, ind_old, :, :]
else:
my_weight[my_keys[i]] = v
else:
# conv layer
if 'weight' in k:
# weight
ind_ = np.array(index_code[count]).nonzero()[0]
v = v[:, ind_old, :, :]
my_weight[my_keys[i]] = v[ind_, :, :, :]
else:
# bias
my_weight[my_keys[i]] = v[ind_]
ind_old = ind_
count += 1
else:
# fc layer
my_weight[my_keys[i]] = v
i = i + 1
self.load_state_dict(my_weight)
def forward(self, x):
x = self.ReLU(self.conv1_1(x))
x = self.maxpool(self.ReLU(self.conv1_2(x)))
x = self.ReLU(self.conv2_1(x))
x = self.maxpool(self.ReLU(self.conv2_2(x)))
x = self.ReLU(self.conv3_1(x))
x = self.ReLU(self.conv3_2(x))
x = self.maxpool(self.ReLU(self.conv3_3(x)))
x = self.ReLU(self.conv4_1(x))
x = self.ReLU(self.conv4_2(x))
x = self.maxpool(self.ReLU(self.conv4_3(x)))
x = self.ReLU(self.conv5_1(x))
x = self.ReLU(self.conv5_2(x))
x = self.maxpool(self.ReLU(self.conv5_3(x)))
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x
if __name__ == '__main__':
VGG16('/home/luojh2/model.pth')
| 4,591 | 38.247863 | 108 | py |
AutoPruner | AutoPruner-master/MobileNetv2/1_pruning/main.py | import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import time
import os
import sys
import argparse
import numpy as np
import shutil
from torchvision import datasets, transforms
from src_code import mobilenetv2
parser = argparse.ArgumentParser(description='PyTorch Digital Mammography Training')
parser.add_argument('--lr', default=0.01, type=float, help='learning rate')
parser.add_argument('--weight_decay', default=1e-4, type=float, help='weight decay')
parser.add_argument('--batch_size', default=256, type=int, help='batch size')
parser.add_argument('--num_epochs', default=5, type=int, help='number of training epochs')
parser.add_argument('--lr_decay_epoch', default=10, type=int, help='learning rate decay epoch')
parser.add_argument('--data_base', default='/mnt/ramdisk/ImageNet', type=str, help='the path of dataset')
parser.add_argument('--ft_model_path', default='/mnt/data3/luojh/project/6_CURL/Journal/pretrained_model/ImageNet/mobilenetv2_1.0-0c6065bc.pth',
type=str, help='the path of fine tuned model')
parser.add_argument('--gpu_id', default='4,5,6,7', type=str,
help='id(s) for CUDA_VISIBLE_DEVICES')
parser.add_argument('--start_epoch', default=0, type=int, metavar='N',
help='manual epoch number (useful on restarts)')
parser.add_argument('--compression_rate', default=0.64, type=float, help='the proportion of 1 in compressed model')
parser.add_argument('--print-freq', '-p', default=20, type=int,
metavar='N', help='print frequency (default: 10)')
parser.add_argument('--alpha_start', default=0.1, type=float, help='the initial value of alpha in AutoPruner layer')
parser.add_argument('--alpha_end', default=100, type=float, help='the initial value of alpha in AutoPruner layer')
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
best_prec1 = -1
alpha = 0
alpha_step = 0
print(args)
# args.ft_model_path = '/home/luojh2/.torch/models/vgg16-397923af.pth'
def main():
global args, best_prec1, alpha, alpha_step
# Phase 1 : Model setup
print('\n[Phase 2] : Model setup')
model = mobilenetv2.MobileNetV2(args.ft_model_path).cuda()
print(model)
model_ft = torch.nn.DataParallel(model)
cudnn.benchmark = True
print("model setup success!")
# Phase 2 : Data Load
# Data pre-processing
data_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
]),
'val': transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
}
data_dir = args.data_base
print("| Preparing data...")
dsets = {
x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x])
for x in ['train', 'val']
}
train_loader = torch.utils.data.DataLoader(dsets['train'], batch_size=args.batch_size, shuffle=True, num_workers=8,
pin_memory=True)
val_loader = torch.utils.data.DataLoader(dsets['val'], batch_size=args.batch_size, shuffle=False, num_workers=8,
pin_memory=True)
print('data_loader_success!')
# Phase 3: fine_tune model
print('\n[Phase 3] : Model fine tune')
# define loss function (criterion) and optimizer
criterion = nn.CrossEntropyLoss().cuda()
optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model_ft.parameters()), args.lr,
momentum=0.9,
weight_decay=args.weight_decay)
alpha_step = (args.alpha_end - args.alpha_start)/float(args.num_epochs * len(train_loader))
alpha = args.alpha_start
for epoch in range(args.start_epoch, args.num_epochs):
# adjust_learning_rate(optimizer, epoch, 3) # reduce lr every 3 epochs
# train for one epoch
time1 = time.time()
channel_index = train(train_loader, model_ft, criterion, optimizer, epoch)
print('training one epoch takes {0:.3f} seconds.'.format(time.time()-time1))
# evaluate on validation set
prec1 = validate(val_loader, model_ft, criterion, channel_index)
# remember best prec@1 and save checkpoint
is_best = prec1 > best_prec1
if is_best:
best_prec1 = prec1
folder_path = 'checkpoint'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
torch.save(model_ft.state_dict(), folder_path+'/model.pth')
fw = open(folder_path+'/channel_index.txt', 'w')
for item in channel_index:
for item_ in item:
fw.write('{0}, '.format(item_))
fw.write('\n')
fw.close()
def train(train_loader, model, criterion, optimizer, epoch):
global alpha_step, alpha
gpu_num = torch.cuda.device_count()
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to train mode
model.train()
end = time.time()
for i, (input, target) in enumerate(train_loader):
# measure data loading time
alpha = alpha + alpha_step
data_time.update(time.time() - end)
input, target = input.cuda(), target.cuda()
# compute output
output, scale_vec = model(input, alpha)
# adjust alpha and reg_lambda
channel_index = []
first_value = []
binary_pruning_rate = []
index_code = []
two_side_rate = []
for item in scale_vec:
tmp = item.data.cpu().numpy().reshape(gpu_num, -1).mean(0)
index_code.append(tmp)
for item in index_code:
tmp = item
channel_index.append((np.sign(tmp - 0.5) + 1) / 2.0)
first_value.append(tmp[0])
binary_pruning_rate.append(np.sum(tmp < 0.1) / len(tmp)) # The proportion of 0
two_side_rate.append((np.sum(tmp > 0.9) + np.sum(tmp < 0.1)) / len(tmp))
if i % args.print_freq == 0:
print('The first value of each layer: {0}'.format(first_value))
print('The binary rate of each layer: {0}'.format(binary_pruning_rate))
print('The two side rate of each layer: {0}'.format(two_side_rate))
# check the binary rate in the last epoch
if epoch == args.num_epochs - 1:
if not all(my_item > 0.9 for my_item in two_side_rate):
alpha = alpha + 10*alpha_step
# calculate loss
loss1 = criterion(output, target)
loss2 = 0
for ind_, item in enumerate(scale_vec):
loss2 += (item.norm(1) / float(item.size(0)) - args.compression_rate) ** 2
loss = loss1 + 10.0*loss2
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data.item(), input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Epoch[{0}]: [{1}/{2}]\t'
'alpha: {3:.4f}\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})\t'
'Loss {loss.val:.3f} ({loss.avg:.3f})'.format(
epoch, i, len(train_loader), alpha, batch_time=batch_time,
top1=top1, top5=top5, loss=losses))
sys.stdout.flush()
return channel_index
def validate(val_loader, model, criterion, channel_index):
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
for i, (input, target) in enumerate(val_loader):
input, target = input.cuda(), target.cuda()
# compute output
output, _ = model(input, 1.0, channel_index)
loss = criterion(output, target)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data.item(), input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
i, len(val_loader), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
sys.stdout.flush()
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
return top1.avg
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, 'model_best.pth.tar')
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def adjust_learning_rate(optimizer, epoch, epoch_num):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = args.lr * (0.1 ** (epoch // epoch_num))
print('| Learning Rate = %f' % lr)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == "__main__":
main()
| 11,003 | 35.68 | 144 | py |
AutoPruner | AutoPruner-master/MobileNetv2/1_pruning/evaluate.py | import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import time
import os
import sys
import argparse
from torchvision import datasets, transforms
from src_code import mobilenetv2
from torchsummaryX import summary
parser = argparse.ArgumentParser(description='PyTorch Digital Mammography Training')
parser.add_argument('--lr', default=0.001, type=float, help='learning rate')
parser.add_argument('--weight_decay', default=1e-4, type=float, help='weight decay')
parser.add_argument('--batch_size', default=256, type=int, help='batch size')
parser.add_argument('--num_epochs', default=0, type=int, help='number of training epochs')
parser.add_argument('--lr_decay_epoch', default=10, type=int, help='learning rate decay epoch')
parser.add_argument('--data_base', default='/mnt/ramdisk/ImageNet', type=str, help='the path of dataset')
parser.add_argument('--gpu_id', default='4,5,6,7', type=str,
help='id(s) for CUDA_VISIBLE_DEVICES')
parser.add_argument('--start_epoch', default=0, type=int, metavar='N',
help='manual epoch number (useful on restarts)')
parser.add_argument('--print-freq', '-p', default=20, type=int,
metavar='N', help='print frequency (default: 10)')
parser.add_argument('--ft_model_path', default='/mnt/data3/luojh/project/6_CURL/Journal/pretrained_model/ImageNet/mobilenetv2_1.0-0c6065bc.pth',
type=str, help='the path of fine tuned model')
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
best_prec1 = -1
print(args)
def main():
global args, best_prec1
# Phase 1 : Model setup
print('\n[Phase 2] : Model setup')
model = mobilenetv2.MobileNetV2(args.ft_model_path)
model.eval()
summary(model, torch.zeros((1, 3, 224, 224)))
model_ft = torch.nn.DataParallel(model.cuda())
cudnn.benchmark = True
print("model setup success!")
# Phase 2 : Data Load
# Data pre-processing
data_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop(224),
# transforms.Resize(256),
# transforms.RandomCrop((224, 224)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
]),
'val': transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
}
data_dir = args.data_base
print("| Preparing data...")
dsets = {
x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x])
for x in ['train', 'val']
}
train_loader = torch.utils.data.DataLoader(dsets['train'], batch_size=args.batch_size, shuffle=True, num_workers=8,
pin_memory=True)
val_loader = torch.utils.data.DataLoader(dsets['val'], batch_size=args.batch_size, shuffle=False, num_workers=8,
pin_memory=True)
print('data_loader_success!')
# Phase 3: fine_tune model
print('\n[Phase 3] : Model fine tune')
# define loss function (criterion) and optimizer
criterion = nn.CrossEntropyLoss().cuda()
optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model_ft.parameters()), args.lr,
momentum=0.9,
weight_decay=args.weight_decay)
validate(val_loader, model_ft, criterion)
for epoch in range(args.start_epoch, args.num_epochs):
adjust_learning_rate(optimizer, epoch, 10) # reduce lr every 3 epochs
# train for one epoch
time1 = time.time()
train(train_loader, model_ft, criterion, optimizer, epoch)
print('training one epoch takes {0:.3f} seconds.'.format(time.time()-time1))
# evaluate on validation set
prec1 = validate(val_loader, model_ft, criterion)
# remember best prec@1 and save checkpoint
is_best = prec1 > best_prec1
if is_best:
best_prec1 = prec1
folder_path = 'checkpoint'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
torch.save(model_ft.state_dict(), folder_path+'/model.pth')
def train(train_loader, model, criterion, optimizer, epoch):
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to train mode
model.train()
end = time.time()
for i, (input, target) in enumerate(train_loader):
# measure data loading time
data_time.update(time.time() - end)
input, target = input.cuda(), target.cuda()
# compute output
output = model(input)
# calculate loss
loss = criterion(output, target)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data.item(), input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Epoch[{0}]: [{1}/{2}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})\t'
'Loss {loss.val:.3f} ({loss.avg:.3f})'.format(
epoch, i, len(train_loader), batch_time=batch_time,
top1=top1, top5=top5, loss=losses))
sys.stdout.flush()
def validate(val_loader, model, criterion):
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
for i, (input, target) in enumerate(val_loader):
input, target = input.cuda(), target.cuda()
# compute output
output = model(input)
loss = criterion(output, target)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data.item(), input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
i, len(val_loader), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
sys.stdout.flush()
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
return top1.avg
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def adjust_learning_rate(optimizer, epoch, epoch_num):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = args.lr * (0.1 ** (epoch // epoch_num))
print('| Learning Rate = %f' % lr)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == "__main__":
main()
| 8,623 | 34.489712 | 144 | py |
AutoPruner | AutoPruner-master/MobileNetv2/1_pruning/src_code/mobilenetv2.py | """
Creates a MobileNetV2 Model as defined in:
Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen. (2018).
MobileNetV2: Inverted Residuals and Linear Bottlenecks
arXiv preprint arXiv:1801.04381.
import from https://github.com/tonylins/pytorch-mobilenet-v2
"""
import torch.nn as nn
import math
import torch
from . import my_op
__all__ = ['mobilenetv2']
def _make_divisible(v, divisor, min_value=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
:param v:
:param divisor:
:param min_value:
:return:
"""
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
# Make sure that round down does not go down by more than 10%.
if new_v < 0.9 * v:
new_v += divisor
return new_v
def conv_3x3_bn(inp, oup, stride):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
nn.BatchNorm2d(oup),
nn.ReLU6(inplace=True)
)
def conv_1x1_bn(inp, oup):
return nn.Sequential(
nn.Conv2d(inp, oup, 1, 1, 0, bias=False),
nn.BatchNorm2d(oup),
nn.ReLU6(inplace=True)
)
class InvertedResidual(nn.Module):
def __init__(self, block_id, inp, oup, stride, expand_ratio):
super(InvertedResidual, self).__init__()
assert stride in [1, 2]
hidden_dim = round(inp * expand_ratio)
self.expand_ratio = expand_ratio
self.identity = stride == 1 and inp == oup
self.ReLU = nn.ReLU6(inplace=True)
if expand_ratio == 1:
self.conv1 = nn.Conv2d(inp, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False)
self.bn1 = nn.BatchNorm2d(hidden_dim)
self.conv2 = nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False)
self.bn2 = nn.BatchNorm2d(oup)
else:
self.block_id = block_id
self.activation_size_list = [112, 56, 56, 28, 28, 28, 14, 14, 14, 14, 14, 14, 14, 7, 7, 7]
self.AP = my_op.APLayer(hidden_dim, hidden_dim, activation_size=self.activation_size_list[block_id], max_ks=2,
layer_id=block_id)
# hidden layer of each block
# 96, 144, 144, 192, 192, 192, 384, 384, 384, 384, 576, 576, 576, 960, 960, 960]
self.conv1 = nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False)
self.bn1 = nn.BatchNorm2d(hidden_dim)
self.conv2 = nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False)
self.bn2 = nn.BatchNorm2d(hidden_dim)
self.conv3 = nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False)
self.bn3 = nn.BatchNorm2d(oup)
self.index_code = [] # the generated index code
self.scale_factor = 0.1
self.channel_index = [] # binary index code for evaluation
def forward(self, x):
output = x
if self.expand_ratio == 1:
x = self.ReLU(self.bn1(self.conv1(x)))
x = self.bn2(self.conv2(x))
else:
x = self.ReLU(self.bn1(self.conv1(x)))
x_scale = self.AP(x, self.scale_factor, self.channel_index)
self.index_code = x_scale
x = my_op.MyScale.apply(x, x_scale)
x = self.ReLU(self.bn2(self.conv2(x)))
x = my_op.MyScale.apply(x, x_scale)
x = self.bn3(self.conv3(x))
if self.identity:
return x + output
else:
return x
class MobileNetV2(nn.Module):
def __init__(self, model_path, num_classes=1000, width_mult=1.):
super(MobileNetV2, self).__init__()
# setting of inverted residual blocks
self.cfgs = [
# t, c, n, s
[1, 16, 1, 1],
[6, 24, 2, 2],
[6, 32, 3, 2],
[6, 64, 4, 2],
[6, 96, 3, 1],
[6, 160, 3, 2],
[6, 320, 1, 1],
]
# building first layer
input_channel = _make_divisible(32 * width_mult, 4 if width_mult == 0.1 else 8)
layers = [conv_3x3_bn(3, input_channel, 2)]
# building inverted residual blocks
block = InvertedResidual
block_id = -1
for t, c, n, s in self.cfgs:
output_channel = _make_divisible(c * width_mult, 4 if width_mult == 0.1 else 8)
for i in range(n):
layers.append(block(block_id, input_channel, output_channel, s if i == 0 else 1, t))
input_channel = output_channel
block_id += 1
self.features = nn.Sequential(*layers)
# building last several layers
output_channel = _make_divisible(1280 * width_mult, 4 if width_mult == 0.1 else 8) if width_mult > 1.0 else 1280
self.conv = conv_1x1_bn(input_channel, output_channel)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.classifier = nn.Linear(output_channel, num_classes)
self._initialize_weights(model_path)
def forward(self, x, scale_factor=1.0, channel_index=None):
self.set_scale_factor(scale_factor)
if not self.training:
self.set_channel_index(channel_index)
x = self.features(x)
x = self.conv(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
index_code = self.get_index_code()
return x, index_code
def set_scale_factor(self, scale_factor):
for item in self.features._modules:
if item == '0' or item == '1':
continue # pass the first two blocks
block = self.features._modules[item]
block.scale_factor = scale_factor
def set_channel_index(self, channel_index):
for item in self.features._modules:
if item == '0' or item == '1':
continue # pass the first two blocks
block = self.features._modules[item]
block.channel_index = channel_index
def get_index_code(self):
index_code = []
for item in self.features._modules:
if item == '0' or item == '1':
continue # pass the first two blocks
block = self.features._modules[item]
index_code.append(block.index_code)
return index_code
def _initialize_weights(self, model_path):
model_weight = torch.load(model_path)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
if m.bias is not None:
m.bias.data.zero_()
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
m.weight.data.normal_(0, 0.01)
m.bias.data.zero_()
my_weight = self.state_dict()
my_keys = list(my_weight)
new_keys = []
for item in my_keys:
if 'AP' not in item:
new_keys.append(item)
for i, (k, v) in enumerate(model_weight.items()):
my_weight[new_keys[i]] = v
self.load_state_dict(my_weight)
def mobilenetv2(**kwargs):
"""
Constructs a MobileNet V2 model
"""
return MobileNetV2(**kwargs)
if __name__ == '__main__':
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
model_path = '/mnt/data3/luojh/project/6_CURL/Journal/pretrained_model/ImageNet/mobilenetv2_1.0-0c6065bc.pth'
model = MobileNetV2(model_path).cuda()
input = torch.zeros((1, 3, 224, 224)).cuda()
output = model(input)
a=1
| 7,872 | 34.949772 | 122 | py |
AutoPruner | AutoPruner-master/MobileNetv2/1_pruning/src_code/my_op.py | import torch
from torch.autograd import Variable
import torch.nn as nn
from torch.autograd import gradcheck
import math
class MyGAP(torch.autograd.Function):
'''
Global Average Pooling with batchsize: N*512*14*14 -> 1*512*14*14
'''
@staticmethod
def forward(ctx, input):
ctx.save_for_backward(input)
return input.mean(dim=0, keepdim=True)
@staticmethod
def backward(ctx, grad_output):
input, = ctx.saved_tensors
batch_size, num_channels, h, w = input.size()
grad_input = grad_output.div(batch_size).expand(batch_size, num_channels, h, w)
return grad_input
class MyScale(torch.autograd.Function):
'''
input: x: 64*512*7*7, scale:512 ==> x[:, i, :, :]*scale[i]
'''
@staticmethod
def forward(self, input_data, scale_vec):
self.save_for_backward(input_data, scale_vec)
batch_size, num_channels, h, w = input_data.size()
scale_vec = scale_vec.view([1, num_channels, 1, 1]).expand(input_data.size())
return input_data.mul(scale_vec)
@staticmethod
def backward(self, grad_output):
input_data, scale_vec = self.saved_tensors
batch_size, num_channels, h, w = input_data.size()
scale_vec = scale_vec.view([1, num_channels, 1, 1]).expand(input_data.size())
grad_input = grad_output.mul(scale_vec)
grad_vec = grad_output.mul(input_data).sum(-1).sum(-1).sum(0)
return grad_input, grad_vec
# AutoPruner layer
class APLayer(nn.Module):
def __init__(self, in_num, out_num, activation_size=14, max_ks=2, layer_id=0):
super(APLayer, self).__init__()
self.layer_type = 'APLayer'
self.id = layer_id
self.conv = nn.Conv2d(in_num, out_num,
kernel_size=int(activation_size / max_ks), stride=1, padding=0)
self.map = nn.MaxPool2d(kernel_size=max_ks, stride=max_ks)
self.sigmoid = nn.Sigmoid()
# n = int(activation_size / max_ks) * int(activation_size / max_ks) * channels_num
# self.conv.weight.data.normal_(0, 10 * math.sqrt(2.0 / n))
nn.init.kaiming_normal_(self.conv.weight, mode='fan_out', nonlinearity='relu')
def forward(self, x, scale_factor, channel_index=None):
x_scale = MyGAP.apply(x) # apply my GAP: N*512*14*14 => 1*512*14*14
x_scale = self.map(x_scale) # apply MAP: 1*512*14*14 => 1*512*7*7
x_scale = self.conv(x_scale) # 1*512*1*1
x_scale = torch.squeeze(x_scale) # 512
x_scale = x_scale * scale_factor # apply scale sigmoid
x_scale = self.sigmoid(x_scale)
if not self.training:
x_scale.data = torch.FloatTensor(channel_index[self.id]).cuda()
return x_scale
if __name__ == '__main__':
in_ = (Variable(torch.randn(1, 1, 3, 3).double(), requires_grad=True),
Variable(torch.randn(1).double(), requires_grad=True))
res = gradcheck(MyScale.apply, in_, eps=1e-6, atol=1e-4)
# in_ = (Variable(torch.randn(2, 64, 3, 3).double(), requires_grad=True),)
# res = gradcheck(MyGAP.apply, in_, eps=1e-6, atol=1e-4)
print(res)
| 3,128 | 34.965517 | 93 | py |
AutoPruner | AutoPruner-master/MobileNetv2/1_pruning/src_code/Network_FT.py | import torch
from . import my_op
from torch import nn
class VGG16(torch.nn.Module):
def __init__(self, model_path):
torch.nn.Module.__init__(self)
self.maxpool = nn.MaxPool2d(kernel_size=2, stride=2)
self.ReLU = nn.ReLU(inplace=True)
# add feature layers
self.conv1_1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1)
self.AP1_1 = my_op.APLayer(64, activation_size=224, max_ks=2, layer_id=0)
self.conv1_2 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1)
self.AP1_2 = my_op.APLayer(64, activation_size=112, max_ks=2, layer_id=1)
self.conv2_1 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1)
self.AP2_1 = my_op.APLayer(128, activation_size=112, max_ks=2, layer_id=2)
self.conv2_2 = nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1)
self.AP2_2 = my_op.APLayer(128, activation_size=56, max_ks=2, layer_id=3)
self.conv3_1 = nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1)
self.AP3_1 = my_op.APLayer(256, activation_size=56, max_ks=2, layer_id=4)
self.conv3_2 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1)
self.AP3_2 = my_op.APLayer(256, activation_size=56, max_ks=2, layer_id=5)
self.conv3_3 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1)
self.AP3_3 = my_op.APLayer(256, activation_size=28, max_ks=2, layer_id=6)
self.conv4_1 = nn.Conv2d(256, 512, kernel_size=3, stride=1, padding=1)
self.AP4_1 = my_op.APLayer(512, activation_size=28, max_ks=2, layer_id=7)
self.conv4_2 = nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1)
self.AP4_2 = my_op.APLayer(512, activation_size=28, max_ks=2, layer_id=8)
self.conv4_3 = nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1)
self.AP4_3 = my_op.APLayer(512, activation_size=14, max_ks=2, layer_id=9)
self.conv5_1 = nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1)
self.AP5_1 = my_op.APLayer(512, activation_size=14, max_ks=2, layer_id=10)
self.conv5_2 = nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1)
self.AP5_2 = my_op.APLayer(512, activation_size=14, max_ks=2, layer_id=11)
self.conv5_3 = nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1)
# add classifier
self.classifier = nn.Sequential()
self.classifier.add_module('fc6', nn.Linear(512*7*7, 4096))
self.classifier.add_module('relu6', nn.ReLU(inplace=True))
self.classifier.add_module('dropout6', nn.Dropout())
self.classifier.add_module('fc7', nn.Linear(4096, 4096))
self.classifier.add_module('relu7', nn.ReLU(inplace=True))
self.classifier.add_module('dropout7', nn.Dropout())
self.classifier.add_module('fc8', nn.Linear(4096, 1000))
model_weight = torch.load(model_path)
my_weight = self.state_dict()
my_keys = list(my_weight.keys())
count = 0
for k, v in model_weight.items():
if 'AP' in my_keys[count]:
count = count + 2
my_weight[my_keys[count]] = v
count += 1
self.load_state_dict(my_weight)
def forward(self, x, scale_factor=1.0, channel_index=None):
x, s1 = self.AP1_1(self.ReLU(self.conv1_1(x)), scale_factor, channel_index)
x, s2 = self.AP1_2(self.maxpool(self.ReLU(self.conv1_2(x))), scale_factor, channel_index)
x, s3 = self.AP2_1(self.ReLU(self.conv2_1(x)), scale_factor, channel_index)
x, s4 = self.AP2_2(self.maxpool(self.ReLU(self.conv2_2(x))), scale_factor, channel_index)
x, s5 = self.AP3_1(self.ReLU(self.conv3_1(x)), scale_factor, channel_index)
x, s6 = self.AP3_2(self.ReLU(self.conv3_2(x)), scale_factor, channel_index)
x, s7 = self.AP3_3(self.maxpool(self.ReLU(self.conv3_3(x))), scale_factor, channel_index)
x, s8 = self.AP4_1(self.ReLU(self.conv4_1(x)), scale_factor, channel_index)
x, s9 = self.AP4_2(self.ReLU(self.conv4_2(x)), scale_factor, channel_index)
x, s10 = self.AP4_3(self.maxpool(self.ReLU(self.conv4_3(x))), scale_factor, channel_index)
x, s11 = self.AP5_1(self.ReLU(self.conv5_1(x)), scale_factor, channel_index)
x, s12 = self.AP5_2(self.ReLU(self.conv5_2(x)), scale_factor, channel_index)
x = self.maxpool(self.ReLU(self.conv5_3(x)))
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x, [s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12]
| 4,519 | 50.363636 | 98 | py |
AutoPruner | AutoPruner-master/MobileNetv2/1_pruning/compress_model/new_model.py | import torch
from torch import nn
import numpy as np
import os
import torch.nn.init as init
class vgg16_compressed(torch.nn.Module):
def __init__(self, layer_id=0, model_path=None):
torch.nn.Module.__init__(self)
model_weight = torch.load(model_path + 'model.pth')
channel_index = torch.load(model_path + 'channel_index.pth')
channel_index = np.where(channel_index != 0)[0]
new_num = int(channel_index.shape[0])
channel_length = list()
channel_length.append(3)
for k, v in model_weight.items():
if 'bias' in k:
channel_length.append(v.size()[0])
channel_length[layer_id + 1] = new_num
self.feature_1 = nn.Sequential()
self.classifier = nn.Sequential()
# add channel selection layers
conv_names = {0: 'conv1_1', 1: 'conv1_2', 2: 'conv2_1', 3: 'conv2_2', 4: 'conv3_1', 5: 'conv3_2', 6: 'conv3_3',
7: 'conv4_1', 8: 'conv4_2', 9: 'conv4_3', 10: 'conv5_1', 11: 'conv5_2', 12: 'conv5_3'}
relu_names = {0: 'relu1_1', 1: 'relu1_2', 2: 'relu2_1', 3: 'relu2_2', 4: 'relu3_1', 5: 'relu3_2', 6: 'relu3_3',
7: 'relu4_1', 8: 'relu4_2', 9: 'relu4_3', 10: 'relu5_1', 11: 'relu5_2', 12: 'relu5_3'}
pool_names = {1: 'pool1', 3: 'pool2', 6: 'pool3', 9: 'pool4', 12: 'pool5'}
pooling_layer_id = [1, 3, 6, 9, 12]
# add feature_1 and feature_2 layers
for i in range(13):
self.feature_1.add_module(conv_names[i],
nn.Conv2d(channel_length[i], channel_length[i + 1], kernel_size=3, stride=1,
padding=1))
self.feature_1.add_module(relu_names[i], nn.ReLU(inplace=True))
if i in pooling_layer_id:
self.feature_1.add_module(pool_names[i], nn.MaxPool2d(kernel_size=2, stride=2))
# add classifier
self.classifier.add_module('fc6', nn.Linear(channel_length[13] * 7 * 7, channel_length[14]))
self.classifier.add_module('relu6', nn.ReLU(inplace=True))
self.classifier.add_module('dropout6', nn.Dropout())
self.classifier.add_module('fc7', nn.Linear(channel_length[14], channel_length[15]))
self.classifier.add_module('relu7', nn.ReLU(inplace=True))
self.classifier.add_module('dropout7', nn.Dropout())
self.classifier.add_module('fc8', nn.Linear(channel_length[15], channel_length[16]))
# load pretrain model weights
my_weight = self.state_dict()
my_keys = list(my_weight.keys())
channel_index = torch.cuda.LongTensor(channel_index)
if layer_id < 12:
# conv1_1 to conv5_2
for k, v in model_weight.items():
name = k.split('.')
if name[2] == conv_names[layer_id]:
if name[3] == 'weight':
name = 'feature_1.' + name[2] + '.' + name[3]
my_weight[name] = v[channel_index, :, :, :]
else:
name = 'feature_1.' + name[2] + '.' + name[3]
my_weight[name] = v[channel_index]
elif name[2] == conv_names[layer_id + 1]:
if name[3] == 'weight':
name = 'feature_1.' + name[2] + '.' + name[3]
my_weight[name] = v[:, channel_index, :, :]
else:
name = 'feature_1.' + name[2] + '.' + name[3]
my_weight[name] = v
else:
if name[1] in ['feature_1', 'feature_2']:
name = 'feature_1.' + name[2] + '.' + name[3]
else:
name = name[1] + '.' + name[2] + '.' + name[3]
if name in my_keys:
my_weight[name] = v
elif layer_id == 12:
# conv5_3
for k, v in model_weight.items():
name = k.split('.')
if name[2] == conv_names[layer_id]:
if name[3] == 'weight':
name = 'feature_1.' + name[2] + '.' + name[3]
my_weight[name] = v[channel_index, :, :, :]
else:
name = 'feature_1.' + name[2] + '.' + name[3]
my_weight[name] = v[channel_index]
elif name[2] == 'fc6':
if name[3] == 'weight':
name = 'classifier.' + name[2] + '.' + name[3]
tmp = v.view(4096, 512, 7, 7)
tmp = tmp[:, channel_index, :, :]
my_weight[name] = tmp.view(4096, -1)
else:
name = 'classifier.' + name[2] + '.' + name[3]
my_weight[name] = v
else:
if name[1] in ['feature_1', 'feature_2']:
name = 'feature_1.' + name[2] + '.' + name[3]
else:
name = name[1] + '.' + name[2] + '.' + name[3]
if name in my_keys:
my_weight[name] = v
self.load_state_dict(my_weight)
def forward(self, x):
x = self.feature_1(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x
class vgg16_test(torch.nn.Module):
def __init__(self, model_path):
torch.nn.Module.__init__(self)
model_weight = torch.load(model_path)
channel_length = list()
channel_length.append(3)
for k, v in model_weight.items():
if 'bias' in k:
channel_length.append(v.size()[0])
self.feature_1 = nn.Sequential()
self.classifier = nn.Sequential()
# add channel selection layers
conv_names = {0: 'conv1_1', 1: 'conv1_2', 2: 'conv2_1', 3: 'conv2_2', 4: 'conv3_1', 5: 'conv3_2', 6: 'conv3_3',
7: 'conv4_1', 8: 'conv4_2', 9: 'conv4_3', 10: 'conv5_1', 11: 'conv5_2', 12: 'conv5_3'}
relu_names = {0: 'relu1_1', 1: 'relu1_2', 2: 'relu2_1', 3: 'relu2_2', 4: 'relu3_1', 5: 'relu3_2', 6: 'relu3_3',
7: 'relu4_1', 8: 'relu4_2', 9: 'relu4_3', 10: 'relu5_1', 11: 'relu5_2', 12: 'relu5_3'}
pool_names = {1: 'pool1', 3: 'pool2', 6: 'pool3', 9: 'pool4', 12: 'pool5'}
pooling_layer_id = [1, 3, 6, 9, 12]
# add feature_1 and feature_2 layers
for i in range(13):
self.feature_1.add_module(conv_names[i],
nn.Conv2d(channel_length[i], channel_length[i + 1], kernel_size=3, stride=1,
padding=1))
self.feature_1.add_module(relu_names[i], nn.ReLU(inplace=True))
if i in pooling_layer_id:
self.feature_1.add_module(pool_names[i], nn.MaxPool2d(kernel_size=2, stride=2))
# add classifier
self.classifier.add_module('fc6', nn.Linear(channel_length[13] * 7 * 7, channel_length[14]))
self.classifier.add_module('relu6', nn.ReLU(inplace=True))
self.classifier.add_module('dropout6', nn.Dropout())
self.classifier.add_module('fc7', nn.Linear(channel_length[14], channel_length[15]))
self.classifier.add_module('relu7', nn.ReLU(inplace=True))
self.classifier.add_module('dropout7', nn.Dropout())
self.classifier.add_module('fc8', nn.Linear(channel_length[15], channel_length[16]))
# load pretrain model weights
my_weight = self.state_dict()
my_keys = list(my_weight.keys())
for k, v in model_weight.items():
name = k.split('.')
name = name[1] + '.' + name[2] + '.' + name[3]
if name in my_keys:
my_weight[name] = v
else:
print('error')
os.exit(0)
self.load_state_dict(my_weight)
def forward(self, x):
x = self.feature_1(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x
class vgg16_GAP(torch.nn.Module):
def __init__(self, model_path):
torch.nn.Module.__init__(self)
model_weight = torch.load(model_path)
channel_length = list()
channel_length.append(3)
for k, v in model_weight.items():
if 'bias' in k:
channel_length.append(v.size()[0])
self.feature_1 = nn.Sequential()
self.classifier = nn.Sequential()
# add channel selection layers
conv_names = {0: 'conv1_1', 1: 'conv1_2', 2: 'conv2_1', 3: 'conv2_2', 4: 'conv3_1', 5: 'conv3_2', 6: 'conv3_3',
7: 'conv4_1', 8: 'conv4_2', 9: 'conv4_3', 10: 'conv5_1', 11: 'conv5_2', 12: 'conv5_3'}
relu_names = {0: 'relu1_1', 1: 'relu1_2', 2: 'relu2_1', 3: 'relu2_2', 4: 'relu3_1', 5: 'relu3_2', 6: 'relu3_3',
7: 'relu4_1', 8: 'relu4_2', 9: 'relu4_3', 10: 'relu5_1', 11: 'relu5_2', 12: 'relu5_3'}
pool_names = {1: 'pool1', 3: 'pool2', 6: 'pool3', 9: 'pool4', 12: 'pool5'}
pooling_layer_id = [1, 3, 6, 9]
# add feature_1 and feature_2 layers
for i in range(13):
self.feature_1.add_module(conv_names[i],
nn.Conv2d(channel_length[i], channel_length[i + 1], kernel_size=3, stride=1,
padding=1))
self.feature_1.add_module(relu_names[i], nn.ReLU(inplace=True))
if i in pooling_layer_id:
self.feature_1.add_module(pool_names[i], nn.MaxPool2d(kernel_size=2, stride=2))
if i == 12:
self.feature_1.add_module(pool_names[i], nn.AvgPool2d(kernel_size=14, stride=1))
# add classifier
self.classifier.add_module('fc', nn.Linear(channel_length[13], channel_length[16]))
init.xavier_uniform(self.classifier.fc.weight, gain=np.sqrt(2.0))
init.constant(self.classifier.fc.bias, 0)
# load pretrain model weights
my_weight = self.state_dict()
my_keys = list(my_weight.keys())
for k, v in model_weight.items():
name = k.split('.')
name = name[1] + '.' + name[2] + '.' + name[3]
if name in my_keys:
my_weight[name] = v
else:
print(name)
self.load_state_dict(my_weight)
def forward(self, x):
x = self.feature_1(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x
if __name__ == '__main__':
model = vgg16_GAP('../checkpoint/fine_tune/model.pth')
print(model)
| 10,696 | 43.570833 | 119 | py |
AutoPruner | AutoPruner-master/MobileNetv2/1_pruning/compress_model/compress_model.py | import torch
from new_model import vgg16_compressed
import argparse
import torch.backends.cudnn as cudnn
parser = argparse.ArgumentParser(description='PyTorch Digital Mammography Training')
parser.add_argument('--layer_id', default=2, type=int, help='the id of compressed layer, starting from 0')
args = parser.parse_args()
print(args)
def main(model_path):
# 1. create compressed model
vgg16_new = vgg16_compressed(layer_id=args.layer_id, model_path=model_path)
# Phase 2 : Model setup
vgg16_new = vgg16_new.cuda()
vgg16_new = torch.nn.DataParallel(vgg16_new.cuda(), device_ids=range(torch.cuda.device_count()))
cudnn.benchmark = True
new_model_param = vgg16_new.state_dict()
torch.save(new_model_param, '../checkpoint/model.pth')
print('Finished!')
if __name__ == '__main__':
folder_path = '../checkpoint/layer_' + str(args.layer_id)+'/'
main(folder_path)
| 908 | 31.464286 | 106 | py |
AutoPruner | AutoPruner-master/MobileNetv2/1_pruning/compress_model/evaluate_net.py | import torch
from new_model import vgg16_compressed, vgg16_test
import argparse
import torch.backends.cudnn as cudnn
import os
import sys
import time
sys.path.append('../')
from src_code.lmdbdataset import lmdbDataset
parser = argparse.ArgumentParser(description='PyTorch Digital Mammography Training')
parser.add_argument('--batch_size', default=500, type=int, help='batch size')
parser.add_argument('--data_base', default='/data/zhangcl/ImageNet', type=str, help='the path of dataset')
parser.add_argument('--gpu_id', default='4,5,6,7', type=str,
help='id(s) for CUDA_VISIBLE_DEVICES')
args = parser.parse_args()
print(args)
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
def main(model_path):
# 1. create compressed model
vgg16_new = vgg16_compressed(layer_id=args.layer_id, model_path=model_path)
# Phase 2 : Model setup
vgg16_new = vgg16_new.cuda()
vgg16_new = torch.nn.DataParallel(vgg16_new.cuda(), device_ids=range(torch.cuda.device_count()))
cudnn.benchmark = True
new_model_param = vgg16_new.state_dict()
torch.save(new_model_param, model_path+'model.pth')
print('Finished!')
return vgg16_new
def evaluate():
# Phase 1: load model
model = vgg16_test('../checkpoint/model.pth')
# Phase 2 : Model setup
model = model.cuda()
model = torch.nn.DataParallel(model.cuda(), device_ids=range(torch.cuda.device_count()))
cudnn.benchmark = True
# Phase 2 : Data Upload
print('\n[Phase 2] : Data Preperation')
dset_loaders = {
'train': torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-train.lmdb'), True),
batch_size=args.batch_size,
shuffle=True,
num_workers=8,
pin_memory=True),
'val': torch.utils.data.DataLoader(
lmdbDataset(os.path.join(args.data_base, 'ILSVRC-val.lmdb'), False),
batch_size=args.batch_size,
num_workers=8,
pin_memory=True)
}
print('data_loader_success!')
# Phase 3: Validation
print("\n[Phase 3 : Inference on val")
criterion = torch.nn.CrossEntropyLoss().cuda()
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
for batch_idx, (input, target) in enumerate(dset_loaders['val']): # dset_loaders['val']):
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input, volatile=True)
target_var = torch.autograd.Variable(target, volatile=True)
# compute output
output = model(input_var)
loss = criterion(output, target_var)
# measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data[0], input.size(0))
top1.update(prec1[0], input.size(0))
top5.update(prec5[0], input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
batch_idx, len(dset_loaders['val']), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
sys.stdout.flush()
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == '__main__':
evaluate()
| 4,451 | 31.977778 | 106 | py |
noise2noise | noise2noise-master/train_mri.py | # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the Creative Commons Attribution-NonCommercial
# 4.0 International License. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
import os
import math
import time
import numpy as np
import tensorflow as tf
import scipy
import dnnlib
import dnnlib.submission.submit as submit
from dnnlib.tflib.autosummary import autosummary
import dnnlib.tflib.tfutil as tfutil
import config_mri
import util
#----------------------------------------------------------------------------
# The network.
def autoencoder(input):
def conv(n, name, n_out, size=3, gain=np.sqrt(2)):
with tf.variable_scope(name):
wshape = [size, size, int(n.get_shape()[-1]), n_out]
wstd = gain / np.sqrt(np.prod(wshape[:-1])) # He init
W = tf.get_variable('W', shape=wshape, initializer=tf.initializers.random_normal(0., wstd))
b = tf.get_variable('b', shape=[n_out], initializer=tf.initializers.zeros())
n = tf.nn.conv2d(n, W, strides=[1]*4, padding='SAME')
n = tf.nn.bias_add(n, b)
return n
def up(n, name, f=2):
with tf.name_scope(name):
s = [-1 if i.value is None else i.value for i in n.shape]
n = tf.reshape(n, [s[0], s[1], 1, s[2], 1, s[3]])
n = tf.tile(n, [1, 1, f, 1, f, 1])
n = tf.reshape(n, [s[0], s[1] * f, s[2] * f, s[3]])
return n
def down(n, name, f=2): return tf.nn.max_pool(n, ksize=[1, f, f, 1], strides=[1, f, f, 1], padding='SAME', name=name)
def concat(name, layers): return tf.concat(layers, axis=-1, name=name)
def LR(n): return tf.nn.leaky_relu(n, alpha=0.1, name='lrelu')
# Make even size and add the channel dimension.
input = tf.pad(input, ((0, 0), (0, 1), (0, 1)), 'constant', constant_values=-.5)
input = tf.expand_dims(input, axis=-1)
# Encoder part.
x = input
x = LR(conv(x, 'enc_conv0', 48))
x = LR(conv(x, 'enc_conv1', 48))
x = down(x, 'pool1'); pool1 = x
x = LR(conv(x, 'enc_conv2', 48))
x = down(x, 'pool2'); pool2 = x
x = LR(conv(x, 'enc_conv3', 48))
x = down(x, 'pool3'); pool3 = x
x = LR(conv(x, 'enc_conv4', 48))
x = down(x, 'pool4'); pool4 = x
x = LR(conv(x, 'enc_conv5', 48))
x = down(x, 'pool5')
x = LR(conv(x, 'enc_conv6', 48))
# Decoder part.
x = up(x, 'upsample5')
x = concat('concat5', [x, pool4])
x = LR(conv(x, 'dec_conv5', 96))
x = LR(conv(x, 'dec_conv5b', 96))
x = up(x, 'upsample4')
x = concat('concat4', [x, pool3])
x = LR(conv(x, 'dec_conv4', 96))
x = LR(conv(x, 'dec_conv4b', 96))
x = up(x, 'upsample3')
x = concat('concat3', [x, pool2])
x = LR(conv(x, 'dec_conv3', 96))
x = LR(conv(x, 'dec_conv3b', 96))
x = up(x, 'upsample2')
x = concat('concat2', [x, pool1])
x = LR(conv(x, 'dec_conv2', 96))
x = LR(conv(x, 'dec_conv2b', 96))
x = up(x, 'upsample1')
x = concat('concat1', [x, input])
x = LR(conv(x, 'dec_conv1a', 64))
x = LR(conv(x, 'dec_conv1b', 32))
x = conv(x, 'dec_conv1', 1, gain=1.0)
# Remove the channel dimension and crop to odd size.
return tf.squeeze(x, axis=-1)[:, :-1, :-1]
#----------------------------------------------------------------------------
# Dataset loader
def load_dataset(fn, num_images=None, shuffle=False):
datadir = submit.get_path_from_template(config_mri.data_dir)
if fn.lower().endswith('.pkl'):
abspath = os.path.join(datadir, fn)
print ('Loading dataset from', abspath)
img, spec = util.load_pkl(abspath)
else:
assert False
if shuffle:
perm = np.arange(img.shape[0])
np.random.shuffle(perm)
if num_images is not None:
perm = perm[:num_images]
img = img[perm]
spec = spec[perm]
if num_images is not None:
img = img[:num_images]
spec = spec[:num_images]
# Remove last row/column of the images, we're officially 255x255 now.
img = img[:, :-1, :-1]
# Convert to float32.
assert img.dtype == np.uint8
img = img.astype(np.float32) / 255.0 - 0.5
return img, spec
#----------------------------------------------------------------------------
# Dataset iterator.
def fftshift2d(x, ifft=False):
assert (len(x.shape) == 2) and all([(s % 2 == 1) for s in x.shape])
s0 = (x.shape[0] // 2) + (0 if ifft else 1)
s1 = (x.shape[1] // 2) + (0 if ifft else 1)
x = np.concatenate([x[s0:, :], x[:s0, :]], axis=0)
x = np.concatenate([x[:, s1:], x[:, :s1]], axis=1)
return x
bernoulli_mask_cache = dict()
def corrupt_data(img, spec, params):
ctype = params['type']
assert ctype == 'bspec'
p_at_edge = params['p_at_edge']
global bernoulli_mask_cache
if bernoulli_mask_cache.get(p_at_edge) is None:
h = [s // 2 for s in spec.shape]
r = [np.arange(s, dtype=np.float32) - h for s, h in zip(spec.shape, h)]
r = [x ** 2 for x in r]
r = (r[0][:, np.newaxis] + r[1][np.newaxis, :]) ** .5
m = (p_at_edge ** (1./h[1])) ** r
bernoulli_mask_cache[p_at_edge] = m
print('Bernoulli probability at edge = %.5f' % m[h[0], 0])
print('Average Bernoulli probability = %.5f' % np.mean(m))
mask = bernoulli_mask_cache[p_at_edge]
keep = (np.random.uniform(0.0, 1.0, size=spec.shape)**2 < mask)
keep = keep & keep[::-1, ::-1]
sval = spec * keep
smsk = keep.astype(np.float32)
spec = fftshift2d(sval / (mask + ~keep), ifft=True) # Add 1.0 to not-kept values to prevent div-by-zero.
img = np.real(np.fft.ifft2(spec)).astype(np.float32)
return img, sval, smsk
augment_translate_cache = dict()
def augment_data(img, spec, params):
t = params.get('translate', 0)
if t > 0:
global augment_translate_cache
trans = np.random.randint(-t, t + 1, size=(2,))
key = (trans[0], trans[1])
if key not in augment_translate_cache:
x = np.zeros_like(img)
x[trans[0], trans[1]] = 1.0
augment_translate_cache[key] = fftshift2d(np.fft.fft2(x).astype(np.complex64))
img = np.roll(img, trans, axis=(0, 1))
spec = spec * augment_translate_cache[key]
return img, spec
def iterate_minibatches(input_img, input_spec, batch_size, shuffle, corrupt_targets, corrupt_params, augment_params=dict(), max_images=None):
assert input_img.shape[0] == input_spec.shape[0]
num = input_img.shape[0]
all_indices = np.arange(num)
if shuffle:
np.random.shuffle(all_indices)
if max_images:
all_indices = all_indices[:max_images]
num = len(all_indices)
for start_idx in range(0, num, batch_size):
if start_idx + batch_size <= num:
indices = all_indices[start_idx : start_idx + batch_size]
inputs, targets = [], []
spec_val, spec_mask = [], []
for i in indices:
img, spec = augment_data(input_img[i], input_spec[i], augment_params)
inp, sv, sm = corrupt_data(img, spec, corrupt_params)
inputs.append(inp)
spec_val.append(sv)
spec_mask.append(sm)
if corrupt_targets:
t, _, _ = corrupt_data(img, spec, corrupt_params)
targets.append(t)
else:
targets.append(img)
yield indices, inputs, targets, spec_val, spec_mask
#----------------------------------------------------------------------------
# Training function helpers.
def rampup(epoch, rampup_length):
if epoch < rampup_length:
p = max(0.0, float(epoch)) / float(rampup_length)
p = 1.0 - p
return math.exp(-p*p*5.0)
return 1.0
def rampdown(epoch, num_epochs, rampdown_length):
if epoch >= (num_epochs - rampdown_length):
ep = (epoch - (num_epochs - rampdown_length)) * 0.5
return math.exp(-(ep * ep) / rampdown_length)
return 1.0
#----------------------------------------------------------------------------
# Network parameter import/export.
def save_all_variables(fn):
util.save_pkl({var.name: var.eval() for var in tf.global_variables()}, fn)
#----------------------------------------------------------------------------
# Training function.
def train(submit_config,
num_epochs = 300,
start_epoch = 0,
minibatch_size = 16,
epoch_train_max = None,
post_op = None,
corrupt_targets = True,
corrupt_params = dict(),
augment_params = dict(),
rampup_length = 10,
rampdown_length = 30,
learning_rate_max = 0.001,
adam_beta1_initial = 0.9,
adam_beta1_rampdown = 0.5,
adam_beta2 = 0.99,
dataset_train = dict(),
dataset_test = dict(),
load_network = None):
result_subdir = submit_config.run_dir
# Create a run context (hides low level details, exposes simple API to manage the run)
ctx = dnnlib.RunContext(submit_config, config_mri)
# Initialize TensorFlow graph and session using good default settings
tfutil.init_tf(config_mri.tf_config)
tf.set_random_seed(config_mri.random_seed)
np.random.seed(config_mri.random_seed)
print('Loading training set.')
train_img, train_spec = load_dataset(**dataset_train)
print('Loading test set.')
test_img, test_spec = load_dataset(**dataset_test)
print('Got %d training, %d test images.' % (train_img.shape[0], test_img.shape[0]))
print('Image size is %d x %d' % train_img.shape[1:])
print('Spectrum size is %d x %d' % train_spec.shape[1:])
# Construct TF graph.
input_shape = [None] + list(train_img.shape)[1:]
spectrum_shape = [None] + list(train_spec.shape)[1:]
inputs_var = tf.placeholder(tf.float32, shape=input_shape, name='inputs')
targets_var = tf.placeholder(tf.float32, shape=input_shape, name='targets')
denoised = autoencoder(inputs_var)
denoised_orig = denoised
if post_op == 'fspec':
def fftshift3d(x, ifft):
assert len(x.shape) == 3
s0 = (x.shape[1] // 2) + (0 if ifft else 1)
s1 = (x.shape[2] // 2) + (0 if ifft else 1)
x = tf.concat([x[:, s0:, :], x[:, :s0, :]], axis=1)
x = tf.concat([x[:, :, s1:], x[:, :, :s1]], axis=2)
return x
print('Forcing denoised spectrum to known values.')
spec_value_var = tf.placeholder(tf.complex64, shape=spectrum_shape, name='spec_value')
spec_mask_var = tf.placeholder(tf.float32, shape=spectrum_shape, name='spec_mask')
denoised_spec = tf.fft2d(tf.complex(denoised, tf.zeros_like(denoised))) # Take FFT of denoiser output.
denoised_spec = fftshift3d(denoised_spec, False) # Shift before applying mask.
spec_mask_c64 = tf.cast(spec_mask_var, tf.complex64) # TF wants operands to have same type.
denoised_spec = spec_value_var * spec_mask_c64 + denoised_spec * (1. - spec_mask_c64) # Force known frequencies.
denoised = tf.cast(tf.spectral.ifft2d(fftshift3d(denoised_spec, True)), dtype = tf.float32) # Shift back and IFFT.
else:
assert post_op is None
with tf.name_scope('loss'):
targets_clamped = tf.clip_by_value(targets_var, -0.5, 0.5)
denoised_clamped = tf.clip_by_value(denoised, -0.5, 0.5)
# Keep MSE for each item in the minibatch for PSNR computation:
loss_clamped = tf.reduce_mean((targets_clamped - denoised_clamped)**2, axis=[1,2])
diff_expr = targets_var - denoised
loss_test = tf.reduce_mean(diff_expr**2)
loss_train = loss_test
# Construct optimization function.
learning_rate_var = tf.placeholder(tf.float32, shape=[], name='learning_rate')
adam_beta1_var = tf.placeholder(tf.float32, shape=[], name='adam_beta1')
train_updates = tf.train.AdamOptimizer(learning_rate=learning_rate_var, beta1=adam_beta1_var, beta2=adam_beta2).minimize(loss_train)
# Create a log file for Tensorboard
summary_log = tf.summary.FileWriter(submit_config.run_dir)
summary_log.add_graph(tf.get_default_graph())
ctx.update(loss='run %d' % submit_config.run_id, cur_epoch=0, max_epoch=num_epochs)
# Start training.
session = tf.get_default_session()
num_start_epoch = 0 if start_epoch == 'final' else start_epoch
for epoch in range(num_start_epoch, num_epochs):
if ctx.should_stop():
break
time_start = time.time()
# Calculate epoch parameters.
rampup_value = rampup(epoch, rampup_length)
rampdown_value = rampdown(epoch, num_epochs, rampdown_length)
adam_beta1 = (rampdown_value * adam_beta1_initial) + ((1.0 - rampdown_value) * adam_beta1_rampdown)
learning_rate = rampup_value * rampdown_value * learning_rate_max
# Epoch initializer.
if epoch == num_start_epoch:
session.run(tf.global_variables_initializer(), feed_dict={adam_beta1_var: adam_beta1})
if load_network:
print('Loading network %s' % load_network)
var_dict = util.load_pkl(os.path.join(result_subdir, load_network))
for var in tf.global_variables():
if var.name in var_dict:
tf.assign(var, var_dict[var.name]).eval()
# Skip the rest if we only want the final inference.
if start_epoch == 'final':
break
# Train.
train_loss, train_n = 0., 0.
for (indices, inputs, targets, input_spec_val, input_spec_mask) in iterate_minibatches(train_img, train_spec, batch_size=minibatch_size, shuffle=True, corrupt_targets=corrupt_targets, corrupt_params=corrupt_params, augment_params=augment_params, max_images=epoch_train_max):
# Export example training pairs from the first batch.
if epoch == num_start_epoch and train_n == 0:
img = np.concatenate([np.concatenate(inputs[:6], axis=1), np.concatenate(targets[:6], axis=1)], axis=0) + 0.5
scipy.misc.toimage(img, cmin=0.0, cmax=1.0).save(os.path.join(result_subdir, 'example_train.png'))
# Construct feed dictionary.
feed_dict = {inputs_var: inputs, targets_var: targets, learning_rate_var: learning_rate, adam_beta1_var: adam_beta1}
if post_op == 'fspec':
feed_dict.update({spec_value_var: input_spec_val, spec_mask_var: input_spec_mask})
# Run.
loss_val, _ = session.run([loss_train, train_updates], feed_dict=feed_dict)
# Stats.
train_loss += loss_val * len(indices)
train_n += len(indices)
train_loss /= train_n
# Test.
test_db_clamped = 0.0
test_n = 0.0
for (indices, inputs, targets, input_spec_val, input_spec_mask) in iterate_minibatches(test_img, test_spec, batch_size=minibatch_size, shuffle=False, corrupt_targets=False, corrupt_params=corrupt_params):
# Construct feed dictionary.
feed_dict = {inputs_var: inputs, targets_var: targets}
if post_op == 'fspec':
feed_dict.update({spec_value_var: input_spec_val, spec_mask_var: input_spec_mask})
# Run.
if test_n == 0:
# Export example result.
loss_clamped_vals, orig, outputs = session.run([loss_clamped, denoised_orig, denoised], feed_dict=feed_dict)
prim = [inputs[0], orig[0], outputs[0], targets[0]]
spec = [fftshift2d(abs(np.fft.fft2(x))) for x in prim]
pimg = np.concatenate(prim, axis=1) + 0.5
simg = np.concatenate(spec, axis=1) * 0.03
img = np.concatenate([pimg, simg], axis=0)
scipy.misc.toimage(img, cmin=0.0, cmax=1.0).save(os.path.join(result_subdir, 'img%05d.png' % epoch))
else:
# Just run.
loss_clamped_vals, = session.run([loss_clamped], feed_dict=feed_dict)
# Stats.
indiv_db = 10 * np.log10(1.0 / loss_clamped_vals)
test_db_clamped += np.sum(indiv_db)
test_n += len(indices)
test_db_clamped /= test_n
# Export network.
if epoch % 10 == 0:
save_all_variables(os.path.join(result_subdir, 'network-snapshot-%05d.pkl' % epoch))
# Export and print stats, update progress monitor.
time_epoch = time.time() - time_start
print('Epoch %3d/%d: time=%7.3f, train_loss=%.7f, test_db_clamped=%.5f, lr=%7f' % (
epoch, num_epochs,
autosummary("Timing/sec_per_epoch", time_epoch),
autosummary("Train/loss", train_loss),
autosummary("Test/dB_clamped", test_db_clamped),
autosummary("Learning_rate", learning_rate)
))
ctx.update(loss='run %d' % submit_config.run_id, cur_epoch=epoch, max_epoch=num_epochs)
dnnlib.tflib.autosummary.save_summaries(summary_log, epoch)
# Training done, session still around. Save final network weights.
print("Saving final network weights.")
save_all_variables(os.path.join(result_subdir, 'network-final.pkl'))
print("Resetting random seed and saving a bunch of example images.")
np.random.seed(config_mri.random_seed)
idx = 0
with open(os.path.join(result_subdir, 'psnr.txt'), 'wt') as fout:
for (indices, inputs, targets, input_spec_val, input_spec_mask) in iterate_minibatches(test_img, test_spec, batch_size=1, shuffle=True, corrupt_targets=False, corrupt_params=corrupt_params):
# Construct feed dictionary.
feed_dict = {inputs_var: inputs, targets_var: targets}
if post_op == 'fspec':
feed_dict.update({spec_value_var: input_spec_val, spec_mask_var: input_spec_mask})
# Export example result.
loss_val, loss_clamped_val, orig, outputs = session.run([loss_test, loss_clamped, denoised_orig, denoised], feed_dict=feed_dict)
prim = [inputs[0], orig[0], outputs[0], targets[0]]
spec = [fftshift2d(abs(np.fft.fft2(x))) for x in prim]
pimg = np.concatenate(prim, axis=1) + 0.5
simg = np.concatenate(spec, axis=1) * 0.03
img = np.concatenate([pimg, simg], axis=0)
scipy.misc.toimage(img, cmin=0.0, cmax=1.0).save(os.path.join(result_subdir, 'final%05d.png' % idx))
input_clamped = np.clip(inputs[0], -.5, .5)
trg_clamped = np.clip(targets[0], -.5, .5)
db = -10.0 * math.log10(loss_val)
db_clamped = -10.0 * math.log10(loss_clamped_val)
db_input = -10.0 * math.log10(np.mean((input_clamped - trg_clamped)**2))
fout.write('%3d: %.5f %.5f %.5f\n' % (idx, db_input, db, db_clamped))
idx += 1
if idx == 100:
break
# Session deleted, clean up.
summary_log.close()
ctx.close()
| 19,442 | 39.422037 | 282 | py |
noise2noise | noise2noise-master/config_mri.py | # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the Creative Commons Attribution-NonCommercial
# 4.0 International License. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
import dnnlib
import dnnlib.submission.submit as submit
# Submit config
# ------------------------------------------------------------------------------------------
submit_config = dnnlib.SubmitConfig()
submit_config.run_dir_root = "results"
submit_config.run_dir_ignore += ['datasets', 'results']
desc = "n2n-mri"
# Tensorflow config
# ------------------------------------------------------------------------------------------
tf_config = dnnlib.EasyDict()
tf_config["graph_options.place_pruned_graph"] = True
#----------------------------------------------------------------------------
# Paths etc.
data_dir = 'datasets'
num_gpus = 1
#----------------------------------------------------------------------------
# Baseline configuration.
run_desc = desc
random_seed = 1000
#----------------------------------------------------------------------------
# Basic MRI runs.
run_desc = 'mri'
train = dict(corrupt_params=dict(), augment_params=dict())
run_desc += '-ixi'
train.update(dataset_train=dict(fn='ixi_train.pkl'), augment_params=dict(translate=64)) # 4936 images, lots of augmentation.
train.update(dataset_test=dict(fn='ixi_valid.pkl')) # use all images, should be 1000
train['run_func_name'] = 'train_mri.train'
train['corrupt_params'].update(type='bspec', p_at_edge=0.025) # 256x256 avg = 0.10477
train.update(learning_rate_max=0.001)
# Noise2noise (corrupt_targets=True) or noise2clean (corrupt_targets=False)
train.update(corrupt_targets=True)
train.update(post_op='fspec')
train.update(num_epochs=300) # Long training runs.
# Paper cases. Overrides post-op and target corruption modes.
if train.get('corrupt_targets'):
run_desc += '_s-n2n_'
else:
run_desc += '_s-n2c_'
# Final inference only. Note: verify that dataset, corruption, and post_op match with loaded network.
#train.update(load_network='382-mri-ixi_s-n2n_-lr0.001000-Cbs0.025000-At64-Pfspec/network-final.pkl', start_epoch='final') # N2N
#train.update(load_network='380-mri-ixi_s-n2c_-lr0.001000-clean-Cbs0.025000-At64-Pfspec/network-final.pkl', start_epoch='final') # N2C
if train.get('num_epochs'): run_desc += '-ep%d' % train['num_epochs']
if train.get('learning_rate_max'): run_desc += '-lr%f' % train['learning_rate_max']
if not train.get('corrupt_targets', True): run_desc += '-clean'
if train.get('minibatch_size'): run_desc += '-mb%d' % train['minibatch_size']
if train['corrupt_params'].get('type') == 'gaussian': run_desc += '-Cg%f' % train['corrupt_params']['scale']
if train['corrupt_params'].get('type') == 'bspec': run_desc += '-Cbs%f' % train['corrupt_params']['p_at_edge']
if train['corrupt_params'].get('type') == 'bspeclin': run_desc += '-Cbslin%f' % train['corrupt_params']['p_at_edge']
if train['augment_params'].get('translate', 0) > 0: run_desc += '-At%d' % train['augment_params']['translate']
if train.get('post_op'): run_desc += '-P%s' % train['post_op']
if random_seed != 1000: run_desc += '-%d' % random_seed
if train.get('load_network'): run_desc += '-LOAD%s' % train['load_network'][:3]
if train.get('start_epoch'): run_desc += '-start%s' % train['start_epoch']
# Farm submit config
# ----------------------------------------------------------------
# Number of GPUs
run_desc += "-1gpu"
submit_config.num_gpus = 1
# Submission target
run_desc += "-L"; submit_config.submit_target = dnnlib.SubmitTarget.LOCAL
submit_config.run_desc = run_desc
#----------------------------------------------------------------------------
if __name__ == "__main__":
submit.submit_run(submit_config, **train)
| 3,947 | 40.125 | 134 | py |
noise2noise | noise2noise-master/validation.py | # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the Creative Commons Attribution-NonCommercial
# 4.0 International License. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
import os
import sys
import numpy as np
import PIL.Image
import tensorflow as tf
import dnnlib
import dnnlib.submission.submit as submit
import dnnlib.tflib.tfutil as tfutil
from dnnlib.tflib.autosummary import autosummary
import util
import config
class ValidationSet:
def __init__(self, submit_config):
self.images = None
self.submit_config = submit_config
return
def load(self, dataset_dir):
import glob
abs_dirname = os.path.join(submit.get_path_from_template(dataset_dir), '*')
fnames = sorted(glob.glob(abs_dirname))
if len(fnames) == 0:
print ('\nERROR: No files found using the following glob pattern:', abs_dirname, '\n')
sys.exit(1)
images = []
for fname in fnames:
try:
im = PIL.Image.open(fname).convert('RGB')
arr = np.array(im, dtype=np.float32)
reshaped = arr.transpose([2, 0, 1]) / 255.0 - 0.5
images.append(reshaped)
except OSError as e:
print ('Skipping file', fname, 'due to error: ', e)
self.images = images
def evaluate(self, net, iteration, noise_func):
avg_psnr = 0.0
for idx in range(len(self.images)):
orig_img = self.images[idx]
w = orig_img.shape[2]
h = orig_img.shape[1]
noisy_img = noise_func(orig_img)
pred255 = util.infer_image(net, noisy_img)
orig255 = util.clip_to_uint8(orig_img)
assert (pred255.shape[2] == w and pred255.shape[1] == h)
sqerr = np.square(orig255.astype(np.float32) - pred255.astype(np.float32))
s = np.sum(sqerr)
cur_psnr = 10.0 * np.log10((255*255)/(s / (w*h*3)))
avg_psnr += cur_psnr
util.save_image(self.submit_config, pred255, "img_{0}_val_{1}_pred.png".format(iteration, idx))
if iteration == 0:
util.save_image(self.submit_config, orig_img, "img_{0}_val_{1}_orig.png".format(iteration, idx))
util.save_image(self.submit_config, noisy_img, "img_{0}_val_{1}_noisy.png".format(iteration, idx))
avg_psnr /= len(self.images)
print ('Average PSNR: %.2f' % autosummary('PSNR_avg_psnr', avg_psnr))
def validate(submit_config: dnnlib.SubmitConfig, noise: dict, dataset: dict, network_snapshot: str):
noise_augmenter = dnnlib.util.call_func_by_name(**noise)
validation_set = ValidationSet(submit_config)
validation_set.load(**dataset)
ctx = dnnlib.RunContext(submit_config, config)
tfutil.init_tf(config.tf_config)
with tf.device("/gpu:0"):
net = util.load_snapshot(network_snapshot)
validation_set.evaluate(net, 0, noise_augmenter.add_validation_noise_np)
ctx.close()
def infer_image(network_snapshot: str, image: str, out_image: str):
tfutil.init_tf(config.tf_config)
net = util.load_snapshot(network_snapshot)
im = PIL.Image.open(image).convert('RGB')
arr = np.array(im, dtype=np.float32)
reshaped = arr.transpose([2, 0, 1]) / 255.0 - 0.5
pred255 = util.infer_image(net, reshaped)
t = pred255.transpose([1, 2, 0]) # [RGB, H, W] -> [H, W, RGB]
PIL.Image.fromarray(t, 'RGB').save(os.path.join(out_image))
print ('Inferred image saved in', out_image)
| 3,678 | 36.540816 | 114 | py |
noise2noise | noise2noise-master/network.py | # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the Creative Commons Attribution-NonCommercial
# 4.0 International License. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
import tensorflow as tf
import numpy as np
#----------------------------------------------------------------------------
# Get/create weight tensor for a convolutional or fully-connected layer.
def get_weight(shape, gain=np.sqrt(2)):
fan_in = np.prod(shape[:-1]) # [kernel, kernel, fmaps_in, fmaps_out] or [in, out]
std = gain / np.sqrt(fan_in) # He init
w = tf.get_variable('weight', shape=shape, initializer=tf.initializers.random_normal(0, std))
return w
#----------------------------------------------------------------------------
# Convolutional layer.
def apply_bias(x):
b = tf.get_variable('bias', shape=[x.shape[1]], initializer=tf.initializers.zeros())
b = tf.cast(b, x.dtype)
if len(x.shape) == 2:
return x + b
return x + tf.reshape(b, [1, -1, 1, 1])
def conv2d_bias(x, fmaps, kernel, gain=np.sqrt(2)):
assert kernel >= 1 and kernel % 2 == 1
w = get_weight([kernel, kernel, x.shape[1].value, fmaps], gain=gain)
w = tf.cast(w, x.dtype)
return apply_bias(tf.nn.conv2d(x, w, strides=[1,1,1,1], padding='SAME', data_format='NCHW'))
def maxpool2d(x, k=2):
ksize = [1, 1, k, k]
return tf.nn.max_pool(x, ksize=ksize, strides=ksize, padding='SAME', data_format='NCHW')
# TODO use fused upscale+conv2d from gan2
def upscale2d(x, factor=2):
assert isinstance(factor, int) and factor >= 1
if factor == 1: return x
with tf.variable_scope('Upscale2D'):
s = x.shape
x = tf.reshape(x, [-1, s[1], s[2], 1, s[3], 1])
x = tf.tile(x, [1, 1, 1, factor, 1, factor])
x = tf.reshape(x, [-1, s[1], s[2] * factor, s[3] * factor])
return x
def conv_lr(name, x, fmaps):
with tf.variable_scope(name):
return tf.nn.leaky_relu(conv2d_bias(x, fmaps, 3), alpha=0.1)
def conv(name, x, fmaps, gain):
with tf.variable_scope(name):
return conv2d_bias(x, fmaps, 3, gain)
def autoencoder(x, width=256, height=256, **_kwargs):
x.set_shape([None, 3, height, width])
skips = [x]
n = x
n = conv_lr('enc_conv0', n, 48)
n = conv_lr('enc_conv1', n, 48)
n = maxpool2d(n)
skips.append(n)
n = conv_lr('enc_conv2', n, 48)
n = maxpool2d(n)
skips.append(n)
n = conv_lr('enc_conv3', n, 48)
n = maxpool2d(n)
skips.append(n)
n = conv_lr('enc_conv4', n, 48)
n = maxpool2d(n)
skips.append(n)
n = conv_lr('enc_conv5', n, 48)
n = maxpool2d(n)
n = conv_lr('enc_conv6', n, 48)
#-----------------------------------------------
n = upscale2d(n)
n = tf.concat([n, skips.pop()], axis=1)
n = conv_lr('dec_conv5', n, 96)
n = conv_lr('dec_conv5b', n, 96)
n = upscale2d(n)
n = tf.concat([n, skips.pop()], axis=1)
n = conv_lr('dec_conv4', n, 96)
n = conv_lr('dec_conv4b', n, 96)
n = upscale2d(n)
n = tf.concat([n, skips.pop()], axis=1)
n = conv_lr('dec_conv3', n, 96)
n = conv_lr('dec_conv3b', n, 96)
n = upscale2d(n)
n = tf.concat([n, skips.pop()], axis=1)
n = conv_lr('dec_conv2', n, 96)
n = conv_lr('dec_conv2b', n, 96)
n = upscale2d(n)
n = tf.concat([n, skips.pop()], axis=1)
n = conv_lr('dec_conv1a', n, 64)
n = conv_lr('dec_conv1b', n, 32)
n = conv('dec_conv1', n, 3, gain=1.0)
return n
| 3,609 | 30.391304 | 97 | py |
noise2noise | noise2noise-master/dataset.py | # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the Creative Commons Attribution-NonCommercial
# 4.0 International License. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
import tensorflow as tf
def parse_tfrecord_tf(record):
features = tf.parse_single_example(record, features={
'shape': tf.FixedLenFeature([3], tf.int64),
'data': tf.FixedLenFeature([], tf.string)})
data = tf.decode_raw(features['data'], tf.uint8)
return tf.reshape(data, features['shape'])
# [c,h,w] -> [h,w,c]
def chw_to_hwc(x):
return tf.transpose(x, perm=[1, 2, 0])
# [h,w,c] -> [c,h,w]
def hwc_to_chw(x):
return tf.transpose(x, perm=[2, 0, 1])
def resize_small_image(x):
shape = tf.shape(x)
return tf.cond(
tf.logical_or(
tf.less(shape[2], 256),
tf.less(shape[1], 256)
),
true_fn=lambda: hwc_to_chw(tf.image.resize_images(chw_to_hwc(x), size=[256,256], method=tf.image.ResizeMethod.BICUBIC)),
false_fn=lambda: tf.cast(x, tf.float32)
)
def random_crop_noised_clean(x, add_noise):
cropped = tf.random_crop(resize_small_image(x), size=[3, 256, 256]) / 255.0 - 0.5
return (add_noise(cropped), add_noise(cropped), cropped)
def create_dataset(train_tfrecords, minibatch_size, add_noise):
print ('Setting up dataset source from', train_tfrecords)
buffer_mb = 256
num_threads = 2
dset = tf.data.TFRecordDataset(train_tfrecords, compression_type='', buffer_size=buffer_mb<<20)
dset = dset.repeat()
buf_size = 1000
dset = dset.prefetch(buf_size)
dset = dset.map(parse_tfrecord_tf, num_parallel_calls=num_threads)
dset = dset.shuffle(buffer_size=buf_size)
dset = dset.map(lambda x: random_crop_noised_clean(x, add_noise))
dset = dset.batch(minibatch_size)
it = dset.make_one_shot_iterator()
return it
| 2,009 | 35.545455 | 128 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.