code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
import logging from typing import List, Dict, Any, Tuple, Callable import math import numpy as np from scipy.special import logit from fiesta.util import belief_calc logger = logging.getLogger(__name__) def TTTS(data: List[Dict[str, Any]], model_functions: List[Callable[[List[Dict[str, Any]], List[Dict[str, Any]]], float]], split_function: Callable[[List[Dict[str, Any]]], Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]], p_value: float, logit_transform: bool = False, samples: int = 100000 ) -> Tuple[List[float], List[float], int, List[List[float]]]: ''' :param data: A list of dictionaries, that as a whole represents the entire dataset. Each dictionary within the list represents one sample from the dataset. :param model_functions: A list of functions that represent different models e.g. pytorch model. Which take a train and test dataset as input and returns a metric score e.g. Accuracy. The model functions should not have random seeds set else it defeats the point of finding the best model independent of the random seed and data split. :param split_function: A function that can be used to split the data into train and test splits. This should produce random splits each time it is called. If you would like to use a fixed split each time, you can hard code this function to produce a fixed split each time. :param p_value: The significance value for the best model to be truely the best model e.g. 0.05 if you want to be at least 95% confident. :param logit_transform: Whether to transform the model function's returned metric score by the logit function. :param samples: Number of samples to generate from our belief distribution for each model. This argument is passed directly to :func:`fiesta.util.belief_calc` within this function. This should be large e.g. minimum 10000. :returns: Tuple containing 4 values: 1. The confidence socres for each model, the best model should have the highest confidence 2. The number of times each model was evaluated as a proportion of the number of evaluations 3. The total number of model evaluations 4. The scores that each model generated when evaluated. :NOTE: That if the logit transform is True then the last item in the tuple would be scores that have been transformed by the logit function. :raises ValueError: If the ``p_value`` is not between 0 and 1. ''' if p_value < 0.0 or p_value > 1.0: raise ValueError('The p value has to be between 0 and 1 and ' f'not: {p_value}') num_models = len(model_functions) total_samples = samples * num_models # initialize data storage # (use lists because will be of different lengths) evaluations = [[] for _ in range(num_models)] est_means = np.zeros(num_models) est_variances = np.zeros(num_models) # Number of times each model has been evaluated. eval_counts = np.zeros(num_models) init_num_evals = 3 #start by evaluating each model 3 times for model_index, model_function in enumerate(model_functions): for _ in range(0, init_num_evals): train, test = split_function(data) score = model_function(train, test) if logit_transform: score = logit(score) evaluations[model_index].append(score) est_means[model_index] = np.mean(evaluations[model_index]) est_variances[model_index] = np.var(evaluations[model_index], ddof=0) eval_counts[model_index] = len(evaluations[model_index]) #initialize belief about location of best arm pi = belief_calc(est_means, est_variances, eval_counts, total_samples) #run TTTS until hit required confidence #count number of evals num = init_num_evals * num_models #store running counts of each arm pulled #props = [] #pis = [] while max(pi) < 1 - p_value: # Get new train test split train, test = split_function(data) #pis.append(pi) #sample m-1 m_1 = np.random.choice(range(0, num_models), 1, p=pi)[0] r = np.random.uniform(0, 1) if r<=0.5: #eval model m_1 score = model_functions[m_1](train, test) if logit_transform: score = logit(score) evaluations[m_1].append(score) #update summary stats est_means[m_1] = np.mean(evaluations[m_1]) est_variances[m_1] = np.var(evaluations[m_1],ddof=0) eval_counts[m_1] += 1 logger.info("Evalaution: %s, Model: %s", str(num), str(m_1)) else: #sample other model m_2 = np.random.choice(range(0, num_models), 1, p=pi)[0] #resample until unique from model 1 while m_1==m_2: m_2 = np.random.choice(range(0, num_models), 1, p=pi)[0] #eval m_2 score = model_functions[m_2](train, test) if logit_transform: score = logit(score) evaluations[m_2].append(score) #update summary stats est_means[m_2] = np.mean(evaluations[m_2]) est_variances[m_2] = np.var(evaluations[m_2],ddof=0) eval_counts[m_2] += 1 logger.info("Evalaution: %s, Model: %s", str(num), str(m_2)) num += 1 #update belief pi = belief_calc(est_means,est_variances,eval_counts, total_samples) logger.info("Evalaution: %s, Model confidences: %s", str(num), str(pi)) logger.info("selected model %s", str(np.argmax(pi))) props = [x / sum(eval_counts) for x in eval_counts] return pi, props, num, evaluations def sequential_halving(data: List[Dict[str, Any]], model_functions: List[Callable[[List[Dict[str, Any]], List[Dict[str, Any]]], float]], split_function: Callable[[List[Dict[str, Any]]], Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]], budget: int, logit_transform: bool = False ) -> Tuple[int, List[float], List[List[float]]]: ''' :param data: A list of dictionaries, that as a whole represents the entire dataset. Each dictionary within the list represents one sample from the dataset. :param model_functions: A list of functions that represent different models e.g. pytorch model. Which take a train and test dataset as input and returns a metric score e.g. Accuracy. The model functions should not have random seeds set else it defeats the point of finding the best model independent of the random seed and data split. :param split_function: A function that can be used to split the data into train and test splits. This should produce random splits each time it is called. If you would like to use a fixed split each time, you can hard code this function to produce a fixed split each time. :param budget: The total number of evaluations :param logit_transform: Whether to transform the model function's returned metric score by the logit function. :returns: Tuple containing 3 values: 1. The best performing model function index given the budget 2. The number of times each model was evaluated as a proportion of the total number of evaluations 3. The scores that each model generated when evaluated. :NOTE: That if the logit transform is True then the last item in the tuple would be scores that have been transformed by the logit function. :raises ValueError: Given budget :math:`T` and the models :math:`N` this will be raised if: :math:`T < (|N| * \log_2|N|)` ''' num_models = len(model_functions) R = math.ceil(np.log2(num_models)) min_num_models = num_models * R if budget < min_num_models: raise ValueError(f'The budget {budget} cannot be smaller than (the ' f'number of models to evaluate {num_models}) * ' '(the log to the base 2 of the number of models ' f'{R}) = {min_num_models}') evaluations = [[] for x in range(0, num_models)] candidate_names = [x for x in range(0, num_models)] candidate_est_means = [0 for x in range(0, num_models)] _round = 0 while len(candidate_names) != 1: # calc number of evals for this round number_candidates = len(candidate_names) num_evals = math.floor(budget / (number_candidates * R)) logger.info("Starting round %s, with %s models, with %s this round", str(_round), str(number_candidates), str(num_evals)) # collect evaluations for candidate_name in candidate_names: for _ in range(0, num_evals): train, test = split_function(data) score = model_functions[candidate_name](train, test) if logit_transform: score = logit(score) evaluations[candidate_name].append(score) # update means candidate_index = candidate_names.index(candidate_name) candidate_est_mean = np.mean(evaluations[candidate_name]) candidate_est_means[candidate_index] = candidate_est_mean # remove approx half models for _ in range(0, math.floor(number_candidates / 2)): drop_index = np.argmin(candidate_est_means) del candidate_names[drop_index] del candidate_est_means[drop_index] _round = _round + 1 total_num_evals = sum([len(model_evaluations) for model_evaluations in evaluations]) props = [len(model_evaluations) / total_num_evals for model_evaluations in evaluations] return candidate_names[0], props, evaluations def non_adaptive_fb(data: List[Dict[str, Any]], model_functions: List[Callable[[List[Dict[str, Any]], List[Dict[str, Any]]], float]], split_function: Callable[[List[Dict[str, Any]]], Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]], budget: int, logit_transform: bool = False ) -> Tuple[int, List[List[float]]]: ''' :param data: A list of dictionaries, that as a whole represents the entire dataset. Each dictionary within the list represents one sample from the dataset. :param model_functions: A list of functions that represent different models e.g. pytorch model. Which take a train and test dataset as input and returns a metric score e.g. Accuracy. The model functions should not have random seeds set else it defeats the point of finding the best model independent of the random seed and data split. :param split_function: A function that can be used to split the data into train and test splits. This should produce random splits each time it is called. If you would like to use a fixed split each time, you can hard code this function to produce a fixed split each time. :param budget: The total number of evaluations :param logit_transform: Whether to transform the model function's returned metric score by the logit function. :returns: Tuple containing 2 values: 1. The best performing model function index given the budget 2. The scores that each model generated when evaluated. :NOTE: That if the logit transform is True then the last item in the tuple would be scores that have been transformed by the logit function. :raises ValueError: Given budget :math:`T` and the models :math:`N` this will be raised if: :math:`T < |N|` ''' num_models = len(model_functions) if budget < num_models: raise ValueError(f'The budget {budget} cannot be smaller than the ' f'number of models to evaluate {num_models}') evals: List[List[float]] = [] num_evals_per_model = math.floor(budget / num_models) for model_function in model_functions: model_evals: List[float] = [] for _ in range(0, num_evals_per_model): train, test = split_function(data) score = model_function(train, test) if logit_transform: score = logit(score) model_evals.append(score) evals.append(model_evals) # return model index with largest sample mean, and all the models scores. eval_means = np.mean(evals, axis=1) num_means = len(eval_means) assert_msg = f'The number of means: {num_means} should equal the number of'\ f' models {num_models}' assert len(eval_means) == num_models, assert_msg return np.argmax(eval_means), evals def non_adaptive_fc(data: List[Dict[str, Any]], model_functions: List[Callable[[List[Dict[str, Any]], List[Dict[str, Any]]], float]], split_function: Callable[[List[Dict[str, Any]]], Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]], p_value: float, logit_transform: bool = False, samples: int = 100000 ) -> Tuple[List[float], List[float], int, List[List[float]]]: ''' :param data: A list of dictionaries, that as a whole represents the entire dataset. Each dictionary within the list represents one sample from the dataset. :param model_functions: A list of functions that represent different models e.g. pytorch model. Which take a train and test dataset as input and returns a metric score e.g. Accuracy. The model functions should not have random seeds set else it defeats the point of finding the best model independent of the random seed and data split. :param split_function: A function that can be used to split the data into train and test splits. This should produce random splits each time it is called. If you would like to use a fixed split each time, you can hard code this function to produce a fixed split each time. :param p_value: The significance value for the best model to be truely the best model e.g. 0.05 if you want to be at least 95% confident. :param logit_transform: Whether to transform the model function's returned metric score by the logit function. :param samples: Number of samples to generate from our belief distribution for each model. This argument is passed directly to :func:`fiesta.util.belief_calc` within this function. This should be large e.g. minimum 10000. :returns: Tuple containing 4 values: 1. The confidence socres for each model, the best model should have the highest confidence 2. The number of times each model was evaluated as a proportion of the number of evaluations 3. The total number of model evaluations 4. The scores that each model generated when evaluated. :NOTE: That if the logit transform is True then the last item in the tuple would be scores that have been transformed by the logit function. :raises ValueError: If the ``p_value`` is not between 0 and 1. ''' if p_value < 0.0 or p_value > 1.0: raise ValueError('The p value has to be between 0 and 1 and ' f'not: {p_value}') num_models = len(model_functions) total_samples = samples * num_models evaluations = [[] for i in range(num_models)] est_means = np.zeros(num_models) est_variances = np.zeros(num_models) eval_counts = np.zeros(num_models) # start by evaluating each model 3 times for model_index, model_function in enumerate(model_functions): for _ in range(0, 3): train, test = split_function(data) score = model_function(train, test) if logit_transform: score = logit(score) evaluations[model_index].append(score) est_means[model_index] = np.mean(evaluations[model_index]) est_variances[model_index] = np.var(evaluations[model_index], ddof=0) eval_counts[model_index] = len(evaluations[model_index]) #initialize belief about location of best arm pi = belief_calc(est_means, est_variances, eval_counts, total_samples) # count number of evals num = 3 * num_models # run until hit required confidence while max(pi) < 1 - p_value: # sample all arms for model_index, model_function in enumerate(model_functions): train, test = split_function(data) score = model_function(train, test) if logit_transform: score = logit(score) evaluations[model_index].append(score) # update summary stats est_means[model_index] = np.mean(evaluations[model_index]) est_variances[model_index] = np.var(evaluations[model_index], ddof=0) eval_counts[model_index] += 1 num += num_models # update belief pi = belief_calc(est_means, est_variances, eval_counts, total_samples) logger.info("Evalaution: %s, Model confidences: %s", str(num), str(pi)) logger.info("selected model %s", str(np.argmax(pi))) props = [x / sum(eval_counts) for x in eval_counts] return pi, props, num, evaluations
[ "fiesta.util.belief_calc", "numpy.random.uniform", "numpy.argmax", "numpy.log2", "numpy.zeros", "math.floor", "numpy.argmin", "scipy.special.logit", "numpy.mean", "numpy.var", "logging.getLogger" ]
[((178, 205), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (195, 205), False, 'import logging\n'), ((3504, 3524), 'numpy.zeros', 'np.zeros', (['num_models'], {}), '(num_models)\n', (3512, 3524), True, 'import numpy as np\n'), ((3545, 3565), 'numpy.zeros', 'np.zeros', (['num_models'], {}), '(num_models)\n', (3553, 3565), True, 'import numpy as np\n'), ((3637, 3657), 'numpy.zeros', 'np.zeros', (['num_models'], {}), '(num_models)\n', (3645, 3657), True, 'import numpy as np\n'), ((4326, 4391), 'fiesta.util.belief_calc', 'belief_calc', (['est_means', 'est_variances', 'eval_counts', 'total_samples'], {}), '(est_means, est_variances, eval_counts, total_samples)\n', (4337, 4391), False, 'from fiesta.util import belief_calc\n'), ((13658, 13689), 'math.floor', 'math.floor', (['(budget / num_models)'], {}), '(budget / num_models)\n', (13668, 13689), False, 'import math\n'), ((14150, 14172), 'numpy.mean', 'np.mean', (['evals'], {'axis': '(1)'}), '(evals, axis=1)\n', (14157, 14172), True, 'import numpy as np\n'), ((17784, 17804), 'numpy.zeros', 'np.zeros', (['num_models'], {}), '(num_models)\n', (17792, 17804), True, 'import numpy as np\n'), ((17825, 17845), 'numpy.zeros', 'np.zeros', (['num_models'], {}), '(num_models)\n', (17833, 17845), True, 'import numpy as np\n'), ((17864, 17884), 'numpy.zeros', 'np.zeros', (['num_models'], {}), '(num_models)\n', (17872, 17884), True, 'import numpy as np\n'), ((18518, 18583), 'fiesta.util.belief_calc', 'belief_calc', (['est_means', 'est_variances', 'eval_counts', 'total_samples'], {}), '(est_means, est_variances, eval_counts, total_samples)\n', (18529, 18583), False, 'from fiesta.util import belief_calc\n'), ((4084, 4117), 'numpy.mean', 'np.mean', (['evaluations[model_index]'], {}), '(evaluations[model_index])\n', (4091, 4117), True, 'import numpy as np\n'), ((4155, 4195), 'numpy.var', 'np.var', (['evaluations[model_index]'], {'ddof': '(0)'}), '(evaluations[model_index], ddof=0)\n', (4161, 4195), True, 'import numpy as np\n'), ((4808, 4831), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (4825, 4831), True, 'import numpy as np\n'), ((6075, 6140), 'fiesta.util.belief_calc', 'belief_calc', (['est_means', 'est_variances', 'eval_counts', 'total_samples'], {}), '(est_means, est_variances, eval_counts, total_samples)\n', (6086, 6140), False, 'from fiesta.util import belief_calc\n'), ((8956, 8975), 'numpy.log2', 'np.log2', (['num_models'], {}), '(num_models)\n', (8963, 8975), True, 'import numpy as np\n'), ((9661, 9705), 'math.floor', 'math.floor', (['(budget / (number_candidates * R))'], {}), '(budget / (number_candidates * R))\n', (9671, 9705), False, 'import math\n'), ((14391, 14412), 'numpy.argmax', 'np.argmax', (['eval_means'], {}), '(eval_means)\n', (14400, 14412), True, 'import numpy as np\n'), ((18276, 18309), 'numpy.mean', 'np.mean', (['evaluations[model_index]'], {}), '(evaluations[model_index])\n', (18283, 18309), True, 'import numpy as np\n'), ((18347, 18387), 'numpy.var', 'np.var', (['evaluations[model_index]'], {'ddof': '(0)'}), '(evaluations[model_index], ddof=0)\n', (18353, 18387), True, 'import numpy as np\n'), ((19321, 19386), 'fiesta.util.belief_calc', 'belief_calc', (['est_means', 'est_variances', 'eval_counts', 'total_samples'], {}), '(est_means, est_variances, eval_counts, total_samples)\n', (19332, 19386), False, 'from fiesta.util import belief_calc\n'), ((5108, 5133), 'numpy.mean', 'np.mean', (['evaluations[m_1]'], {}), '(evaluations[m_1])\n', (5115, 5133), True, 'import numpy as np\n'), ((5167, 5199), 'numpy.var', 'np.var', (['evaluations[m_1]'], {'ddof': '(0)'}), '(evaluations[m_1], ddof=0)\n', (5173, 5199), True, 'import numpy as np\n'), ((5822, 5847), 'numpy.mean', 'np.mean', (['evaluations[m_2]'], {}), '(evaluations[m_2])\n', (5829, 5847), True, 'import numpy as np\n'), ((5881, 5913), 'numpy.var', 'np.var', (['evaluations[m_2]'], {'ddof': '(0)'}), '(evaluations[m_2], ddof=0)\n', (5887, 5913), True, 'import numpy as np\n'), ((6260, 6273), 'numpy.argmax', 'np.argmax', (['pi'], {}), '(pi)\n', (6269, 6273), True, 'import numpy as np\n'), ((10359, 10395), 'numpy.mean', 'np.mean', (['evaluations[candidate_name]'], {}), '(evaluations[candidate_name])\n', (10366, 10395), True, 'import numpy as np\n'), ((10528, 10561), 'math.floor', 'math.floor', (['(number_candidates / 2)'], {}), '(number_candidates / 2)\n', (10538, 10561), False, 'import math\n'), ((10589, 10619), 'numpy.argmin', 'np.argmin', (['candidate_est_means'], {}), '(candidate_est_means)\n', (10598, 10619), True, 'import numpy as np\n'), ((19099, 19132), 'numpy.mean', 'np.mean', (['evaluations[model_index]'], {}), '(evaluations[model_index])\n', (19106, 19132), True, 'import numpy as np\n'), ((19174, 19214), 'numpy.var', 'np.var', (['evaluations[model_index]'], {'ddof': '(0)'}), '(evaluations[model_index], ddof=0)\n', (19180, 19214), True, 'import numpy as np\n'), ((19508, 19521), 'numpy.argmax', 'np.argmax', (['pi'], {}), '(pi)\n', (19517, 19521), True, 'import numpy as np\n'), ((3987, 3999), 'scipy.special.logit', 'logit', (['score'], {}), '(score)\n', (3992, 3999), False, 'from scipy.special import logit\n'), ((4989, 5001), 'scipy.special.logit', 'logit', (['score'], {}), '(score)\n', (4994, 5001), False, 'from scipy.special import logit\n'), ((5703, 5715), 'scipy.special.logit', 'logit', (['score'], {}), '(score)\n', (5708, 5715), False, 'from scipy.special import logit\n'), ((13970, 13982), 'scipy.special.logit', 'logit', (['score'], {}), '(score)\n', (13975, 13982), False, 'from scipy.special import logit\n'), ((18179, 18191), 'scipy.special.logit', 'logit', (['score'], {}), '(score)\n', (18184, 18191), False, 'from scipy.special import logit\n'), ((18963, 18975), 'scipy.special.logit', 'logit', (['score'], {}), '(score)\n', (18968, 18975), False, 'from scipy.special import logit\n'), ((10160, 10172), 'scipy.special.logit', 'logit', (['score'], {}), '(score)\n', (10165, 10172), False, 'from scipy.special import logit\n')]
from pypot.primitive import LoopPrimitive from .trajectory import ConstantTrajectory, FootstepTrajectory from .ik import darwin_ik from .ik import PELVIS_HEIGHT_REST, FOOT_SPREAD from numpy import rad2deg class WalkingState(object): SINGLE_SUPPORT = 1 DOUBLE_SUPPORT = 2 class WalkStraight(LoopPrimitive): def __init__(self, robot, distance, step_duration, frequency=50): LoopPrimitive.__init__(self, robot, frequency) self.step_length = 0.1 self.step_height = 0.01 self.pelvis_height = 0.098 self.motors = dict([(m.name, self.get_mockup_motor(m)) for m in self.robot.motors]) self.distance_left = distance self.step_duration = step_duration ssp_ratio = .75 self.ssp_duration = ssp_ratio * step_duration self.dsp_duration = (1 - ssp_ratio) * step_duration self.dt = 1. / frequency self.pos = None @property def stable_side(self): return 'l' if self.swing_side == 'r' else 'r' def setup(self): self.swing_side = 'r' self.x_stable = 0. self.x_swing_start = 0. self.pos = { 'pelvis': [0., 0., PELVIS_HEIGHT_REST], 'l_foot': [0., FOOT_SPREAD, 0.], 'r_foot': [0., -FOOT_SPREAD, 0.], } self.start_step(0) def update(self): t = self.elapsed_time # print(t) if self.state == WalkingState.DOUBLE_SUPPORT: self.run_double_support(t) elif self.state == WalkingState.SINGLE_SUPPORT: self.run_single_support(t) else: raise Exception("Unknown state: {}".format(self.state)) def update_position(self, t): self.pos = self.current_trajectory(t) q = darwin_ik(self.pos) self.goto_position(q) def run_double_support(self, t): t -= self.current_step * self.step_duration if t > self.dsp_duration: self.start_single_support() self.update_position(t) def run_single_support(self, t): step = t // self.step_duration t = t % self.step_duration done = False if step > self.current_step: done = self.check_walking_done() if not done: self.start_next_step(step) if not done: self.update_position(t) def get_next_step_length(self): next_step_max_length = self.step_length if self.current_step > 0 else 0.5 * self.step_length if 2 * self.distance_left > next_step_max_length: next_step_length = next_step_max_length else: next_step_length = 2 * self.distance_left return next_step_length def check_walking_done(self): # the pelvis only moves half of the footstep length self.distance_left = max(0, self.distance_left - 0.5 * self.current_step_length) if self.distance_left < 1e-6: # We have arrived. print('Done!') self.stop() return True return False def start_step(self, step): print('\n*** Start step {} ***'.format(step + 1)) self.current_step = step self.current_step_length = self.get_next_step_length() self.start_double_support() def start_next_step(self, step): self.swing_side = 'l' if self.swing_side == 'r' else 'r' next_swing_start = self.x_stable self.x_stable = self.x_swing_start + self.current_step_length self.x_swing_start = next_swing_start self.start_step(step) def start_single_support(self): print(" >> start single support phase <<") self.current_trajectory = FootstepTrajectory( self.current_step_length, self.step_height, self.x_stable, self.x_swing_start, self.pelvis_height, self.swing_side, self.ssp_duration) self.state = WalkingState.SINGLE_SUPPORT def get_swing_target(self): traj = FootstepTrajectory( self.current_step_length, self.step_height, self.x_stable, self.x_swing_start, self.pelvis_height, self.swing_side, self.ssp_duration) return traj(self.ssp_duration)[self.swing_side + '_foot'] def start_double_support(self): print(" >> start double support phase <<") self.current_trajectory = ConstantTrajectory(self.pos) self.swing_target = self.get_swing_target() self.state = WalkingState.DOUBLE_SUPPORT def goto_position(self, qs): for name, q in qs.items(): m = self.motors[name] m.goal_position = rad2deg(q)
[ "numpy.rad2deg", "pypot.primitive.LoopPrimitive.__init__" ]
[((396, 442), 'pypot.primitive.LoopPrimitive.__init__', 'LoopPrimitive.__init__', (['self', 'robot', 'frequency'], {}), '(self, robot, frequency)\n', (418, 442), False, 'from pypot.primitive import LoopPrimitive\n'), ((4577, 4587), 'numpy.rad2deg', 'rad2deg', (['q'], {}), '(q)\n', (4584, 4587), False, 'from numpy import rad2deg\n')]
''' --------------------------- Licensing and Distribution --------------------------- Program name: Pilgrim Version : 2021.5 License : MIT/x11 Copyright (c) 2021, <NAME> (<EMAIL>) and <NAME> (<EMAIL>) 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. --------------------------- *----------------------------------* | Module : common | | Sub-module : MolGraph | | Last Update: 2020/05/03 (Y/M/D) | | Main Author: <NAME> | *----------------------------------* This module contains the MolGraph class ''' #=============================================# import numpy as np #---------------------------------------------# import common.fncs as fncs import common.internal as intl from common.Ugraph import UGRAPH #=============================================# class MolGraph(UGRAPH): def __init__(self,xcc,symbols,cscal=1.3,nfrags=1,epslin=4.5): # initialize data for UGRAPH self._ugdict = {} self._nnodes = 0 self._nedges = 0 self._cnumber= 0 # calculate connectivity matrix cmatrix = intl.get_adjmatrix(xcc,symbols,cscal,mode="int")[0] # autoconnect cmatrix = intl.link_fragments(xcc,cmatrix,nfrags)[0] # save cmatrix cmatrix = np.matrix(cmatrix) # set graph self.set_from_amatrix(cmatrix) # detect atoms in cycles nodes_cycles = self.nodes_in_cycles() # save data self._xcc = [xi for xi in xcc] self._symbols = symbols self._incycle = nodes_cycles self._cmatrix = cmatrix self._epslin = epslin self._cscal = cscal self._angles = {} # see if dummy is required by checking all atoms with two connections (B-A-C) dummies = [] nodeX = int(self._nnodes) - 1 for nodeA,neighbors in self._ugdict.items(): if len(neighbors) != 2: continue nodeB,nodeC = neighbors # add dummy atom?? if self.islinear( (nodeB,nodeA,nodeC) ): xB = self._xcc[3*nodeB:3*nodeB+3] xA = self._xcc[3*nodeA:3*nodeA+3] # coordinates of dummy atom xX = intl.zmat_thirdatom(xB,xA,dist=1.0,angle=np.pi/2) # save data nodeX += 1 dummies.append( (nodeA,nodeX,xX) ) #---------------------# # Include dummy atoms # #---------------------# nn = int(self._nnodes) nd = len(dummies) if nd > 0: # increase cmatrix zerocols = np.zeros( (nn,nd ) , dtype=int) zerorows = np.zeros( (nd,nn+nd) , dtype=int) self._cmatrix = np.hstack( (self._cmatrix,zerocols) ) self._cmatrix = np.vstack( (self._cmatrix,zerorows) ) # Add dummy atoms!! for nodeA,nodeX,xX in dummies: # add connection in graph self.add_node(nodeX) self.add_edge(nodeX,nodeA) # add connection in cmatrix self._cmatrix[nodeA,nodeX] = 1 self._cmatrix[nodeX,nodeA] = 1 # add dummy to symbols and xcc self._symbols.append("X") self._xcc += [xi for xi in xX] def __str__(self): return "(n,e)=(%i,%i)"%(self._nnodes,self._nedges) def islinear(self,triad): if triad not in self._angles: nodeA,nodeB,nodeC = triad xA = self._xcc[3*nodeA:3*nodeA+3] xB = self._xcc[3*nodeB:3*nodeB+3] xC = self._xcc[3*nodeC:3*nodeC+3] angABC = fncs.angle(xA,xB,xC) # save angles self._angles[(nodeA,nodeB,nodeC)] = angABC self._angles[(nodeC,nodeB,nodeA)] = angABC else: angABC = self._angles[triad] # return boolean (True if linear) return abs(180-np.rad2deg(angABC)) < self._epslin def nonlinearpath(self,start_idx,visited=[],ppoint=None): ''' Get longest path without three connected atoms in a line To do so, it always choose the dummy atom (if not visited yet) ''' # Get neighbors, excluding previously visited ones neighbors = [node for node in self._ugdict[start_idx] if node not in visited] if len(neighbors) == 0: return [start_idx] # see if any neighbor is X (dummy atom), it must be the end of path symbol_neighbors = [self._symbols[node] for node in neighbors] if symbol_neighbors.count("X") != 0: nodeX = neighbors[symbol_neighbors.index("X")] return [start_idx,nodeX] # Get longest from non-visited neighbors length = - float("inf") for neighbor in neighbors: # assert path does not contain linear angles if ppoint is not None and self.islinear( (ppoint,start_idx,neighbor) ): continue # now we now it is not 180, we can continue visited_i = visited + [start_idx,neighbor] path_i = self.nonlinearpath(neighbor,visited=visited_i,ppoint=start_idx) symbol_path = [self._symbols[node] for node in path_i] ppath = [start_idx]+path_i if len(path_i) > length: length = len(path_i) the_path = path_i return [start_idx] + the_path def construct_zmatrix(self,seed=None,visited=set([]),previous=None): ''' Returns $zmatrix and $visited * $zmatrix --> a list of tuples * $visited --> a list of visited nodes Tuples in $zmatrix contains the following elements (at1,at2,at3,at4,boolean1,boolean2) where: * at1 to at4 are node indices * boolean1 is True is the tuple corresponds to a PROPER torsion ''' #---------------------------------------------------------------------------------# # For some reason, Python messes when the following line is not included # # If ommited and construct_zmatrix is inside a loop to analize different graphs, # # the $visited variable DO NOT initialize when calling it as: # # construct_zmatrix(graph) # # I guess this is a Python bug or something.... # #---------------------------------------------------------------------------------# visited = set(visited) # for some reason, this is required #---------------------------------------------------------------------------------# zmatrix = [] # find longest path if seed is None: for node in range(self._nnodes): if len(self.neighbors(node)) == 1: break # DFS to find one end point of longest path path = self.nonlinearpath(node) # DFS to find the actual longest path path = self.nonlinearpath(path[-1]) else: path = self.nonlinearpath(seed,list(visited)) ########################### # for idx in range(1,len(path)-1): # triad = (idx-1,idx,idx+1) # if self.islinear( triad ): print("*linear:",triad) ########################### tovisit = set([]) links = {} zmatrix2 = [] added_as_itor = set([]) for idx,atom in enumerate(path): if idx == 0: atoms = ( atom, -1 , -1 , -1 ,False) elif idx == 1: atoms = ( atom, path[0] , -1 , -1 ,False) elif idx == 2: atoms = ( atom, path[1] , path[0] , -1 ,False) else : atoms = ( atom, path[idx-1], path[idx-2], path[idx-3] ,True ) zmatrix.append(atoms) visited.add(atom) # link rest of bonded atoms to path for vecino in self.neighbors(atom): if vecino in path : continue if vecino in added_as_itor: continue if vecino in visited : continue if idx == 0: # select node in previous such as angle != 180 for prev_i in previous: if not self.islinear( (vecino,atom,prev_i) ): break atoms = (vecino,atom,prev_i ,path[idx+1],False) else: if self.islinear( (vecino,atom,path[idx-1]) ): atoms = (vecino,atom,path[idx+1],path[idx-1],False) else: atoms = (vecino,atom,path[idx-1],path[idx+1],False) zmatrix2.append( atoms ) tovisit.add(vecino) added_as_itor.add(vecino) # save link (if X, save X) link1 = path[idx-1] link2 = path[idx-1] if idx+1 != len(path): link2 = path[idx+1] if self._symbols[link2] == "X": links[vecino] = (atom,link2,link1) else : links[vecino] = (atom,link1,link2) zmatrix += zmatrix2 # now work with neighbors while len(tovisit) != 0: node3 = tovisit.pop() # update visited visited.add(node3) # recurrence!! zmatrix_i, visited_i = self.construct_zmatrix(node3,visited,links[node3]) # update visited and tovisit visited = visited.union(visited_i) tovisit = tovisit.difference(visited) # update zmatrix with torsions in ramifications for torsion in zmatrix_i: numnegs = torsion.count(-1) if numnegs == 3: continue # requires connection to main path elif numnegs == 2: atom,link1,link2 = links[node3] triad1 = (node3,atom,link1) triad2 = (node3,atom,link2) if self.islinear( triad1 ): torsion = [torsion[0],node3,atom,link2,True] else: torsion = [torsion[0],node3,atom,link1,True] # requires connection to main path elif numnegs == 1: torsion = torsion[0:3] + links[node3][0:1]+(True,) zmatrix.append(torsion) return zmatrix, visited
[ "numpy.matrix", "common.fncs.angle", "common.internal.zmat_thirdatom", "numpy.zeros", "numpy.hstack", "numpy.rad2deg", "common.internal.get_adjmatrix", "numpy.vstack", "common.internal.link_fragments" ]
[((2281, 2299), 'numpy.matrix', 'np.matrix', (['cmatrix'], {}), '(cmatrix)\n', (2290, 2299), True, 'import numpy as np\n'), ((2097, 2148), 'common.internal.get_adjmatrix', 'intl.get_adjmatrix', (['xcc', 'symbols', 'cscal'], {'mode': '"""int"""'}), "(xcc, symbols, cscal, mode='int')\n", (2115, 2148), True, 'import common.internal as intl\n'), ((2193, 2234), 'common.internal.link_fragments', 'intl.link_fragments', (['xcc', 'cmatrix', 'nfrags'], {}), '(xcc, cmatrix, nfrags)\n', (2212, 2234), True, 'import common.internal as intl\n'), ((3670, 3699), 'numpy.zeros', 'np.zeros', (['(nn, nd)'], {'dtype': 'int'}), '((nn, nd), dtype=int)\n', (3678, 3699), True, 'import numpy as np\n'), ((3733, 3767), 'numpy.zeros', 'np.zeros', (['(nd, nn + nd)'], {'dtype': 'int'}), '((nd, nn + nd), dtype=int)\n', (3741, 3767), True, 'import numpy as np\n'), ((3796, 3832), 'numpy.hstack', 'np.hstack', (['(self._cmatrix, zerocols)'], {}), '((self._cmatrix, zerocols))\n', (3805, 3832), True, 'import numpy as np\n'), ((3863, 3899), 'numpy.vstack', 'np.vstack', (['(self._cmatrix, zerorows)'], {}), '((self._cmatrix, zerorows))\n', (3872, 3899), True, 'import numpy as np\n'), ((4745, 4767), 'common.fncs.angle', 'fncs.angle', (['xA', 'xB', 'xC'], {}), '(xA, xB, xC)\n', (4755, 4767), True, 'import common.fncs as fncs\n'), ((3265, 3319), 'common.internal.zmat_thirdatom', 'intl.zmat_thirdatom', (['xB', 'xA'], {'dist': '(1.0)', 'angle': '(np.pi / 2)'}), '(xB, xA, dist=1.0, angle=np.pi / 2)\n', (3284, 3319), True, 'import common.internal as intl\n'), ((5019, 5037), 'numpy.rad2deg', 'np.rad2deg', (['angABC'], {}), '(angABC)\n', (5029, 5037), True, 'import numpy as np\n')]
# %% import seaborn as sns import torch import matplotlib import numpy as np import matplotlib.pyplot as plt import torch.nn.functional as F from perturb_pca import compute_dot_products from mpl_toolkits.axes_grid1 import make_axes_locatable # matplotlib.style.use('seaborn-white') plt.rcParams['font.family'] = 'Calibri' def format_axes( ax: plt.Axes, ticklabels, patch_size, total_size, block_size, ): robust_models = [1, 2] ax_mm_ticks = np.arange(0, total_size, block_size) ax.set_xticks(ax_mm_ticks-0.5) ax.set_yticks(ax_mm_ticks-0.5) ax.set_xticklabels(ax_mm_ticks) ax.set_yticklabels(ax_mm_ticks) ax.grid(which='major', axis='both', lw=1, color='k', alpha=0.5, ls='-') ax.set_xticks(ax_mm_ticks + block_size/2, minor=True) ax.set_yticks(ax_mm_ticks + block_size/2, minor=True) ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_xticklabels(ticklabels, minor=True, fontsize=12, weight='light') ax.set_yticklabels(ticklabels, minor=True, fontsize=12, weight='light') plt.setp( ax.get_yticklabels(minor=True), rotation=90, ha="center", va="bottom", rotation_mode="anchor") # ax.set_title(f'Patch Size {patch_size}', fontsize=1, pad=10) ax.set_xlabel('Models', fontsize=14) ax.set_ylabel('Models', fontsize=14) ax.xaxis.labelpad = 7 ax.yaxis.labelpad = 7 # for rm in robust_models: # plt.setp( # ax.get_yticklabels(minor=True)[rm], # style='italic', # weight='bold') # plt.setp( # ax.get_xticklabels(minor=True)[rm], # style='italic', # weight='bold') # %% patch_size_configs = [5, 15, 28] max_pool_kernel = [1, 3, 14] attacker = 'fw' models = [ 'Model1', 'Model2', 'Model4', 'MNIST_DNN', 'VGG16BN', 'VITB' ] ticklabels = [ 'R34', 'R18', 'WRN', 'DNN', 'VGG', 'ViT', 'RND', 'SQR' ] fig, axs = plt.subplots(1, 3, figsize=(18, 6)) for idx, p_size in enumerate(patch_size_configs): ax = axs[idx] dot_product = compute_dot_products(models, attacker, p_size) downsample = max_pool_kernel[idx] if downsample > 1: pooled = F.max_pool2d( torch.Tensor(dot_product).unsqueeze(0).unsqueeze(0), downsample) dot_product = pooled.squeeze(0).squeeze(0).numpy() imobj = ax.imshow(dot_product, cmap='YlGn') format_axes( ax, ticklabels, p_size, dot_product.shape[0], p_size ** 2 // downsample ) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.1) fig.colorbar( imobj, cax=cax, ticks=[0, 1] # aspect=40, fraction=0.07, ) fig.savefig('./figs/dot_product_trinity.pdf', bbox_inches='tight') # %% models = [ 'Model2', 'MNIST_RMDENSE', 'MNIST_RPDENSE', 'RMCONV', 'RPCONV', ] ticklabels = [ 'R18', 'RMDNN', 'RPDNN', 'RMCNN', 'RPCNN', ] fig, ax = plt.subplots() dot_product = compute_dot_products(models, 'fw', 5) imobj = ax.imshow(dot_product, cmap='YlGn') format_axes(ax, ticklabels, 5, 125, 25) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.1) fig.colorbar( imobj, cax=cax, ticks=[0, 1] # aspect=40, fraction=0.07, ) fig.savefig('./figs/dot_product_MNIST_NEW.pdf', bbox_inches='tight') # %% sns.set_theme(context='paper', font='Calibri', font_scale=1.25) x = [1, 2, 4, 7, 10, 13] mnist_lenet_eps_0_3 = [45.5921, 50.5076, 54.9649, 69.1903, 69.3305, 79.3606] imagenet_inception_eps_0_05 = [91.08, 88.42, 101.39, 107.70, 128.35, 140.05] fig, ax = plt.subplots() ax = sns.lineplot(x=x, y=mnist_lenet_eps_0_3, label='MNIST LeNet', ax=ax) ax = sns.lineplot(x=x, y=imagenet_inception_eps_0_05, ax=ax, label='ImageNet InceptionV3') sns.despine() ax.set_xlabel('Threshold $\\tau$') ax.set_ylabel('Avg. Queries') fig.savefig('./figs/batch_threshold.pdf', bbox_inches='tight')
[ "mpl_toolkits.axes_grid1.make_axes_locatable", "seaborn.lineplot", "perturb_pca.compute_dot_products", "seaborn.despine", "torch.Tensor", "numpy.arange", "matplotlib.pyplot.subplots", "seaborn.set_theme" ]
[((1989, 2024), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(3)'], {'figsize': '(18, 6)'}), '(1, 3, figsize=(18, 6))\n', (2001, 2024), True, 'import matplotlib.pyplot as plt\n'), ((3038, 3052), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (3050, 3052), True, 'import matplotlib.pyplot as plt\n'), ((3068, 3105), 'perturb_pca.compute_dot_products', 'compute_dot_products', (['models', '"""fw"""', '(5)'], {}), "(models, 'fw', 5)\n", (3088, 3105), False, 'from perturb_pca import compute_dot_products\n'), ((3200, 3223), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), '(ax)\n', (3219, 3223), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((3437, 3500), 'seaborn.set_theme', 'sns.set_theme', ([], {'context': '"""paper"""', 'font': '"""Calibri"""', 'font_scale': '(1.25)'}), "(context='paper', font='Calibri', font_scale=1.25)\n", (3450, 3500), True, 'import seaborn as sns\n'), ((3691, 3705), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (3703, 3705), True, 'import matplotlib.pyplot as plt\n'), ((3712, 3780), 'seaborn.lineplot', 'sns.lineplot', ([], {'x': 'x', 'y': 'mnist_lenet_eps_0_3', 'label': '"""MNIST LeNet"""', 'ax': 'ax'}), "(x=x, y=mnist_lenet_eps_0_3, label='MNIST LeNet', ax=ax)\n", (3724, 3780), True, 'import seaborn as sns\n'), ((3786, 3876), 'seaborn.lineplot', 'sns.lineplot', ([], {'x': 'x', 'y': 'imagenet_inception_eps_0_05', 'ax': 'ax', 'label': '"""ImageNet InceptionV3"""'}), "(x=x, y=imagenet_inception_eps_0_05, ax=ax, label=\n 'ImageNet InceptionV3')\n", (3798, 3876), True, 'import seaborn as sns\n'), ((3872, 3885), 'seaborn.despine', 'sns.despine', ([], {}), '()\n', (3883, 3885), True, 'import seaborn as sns\n'), ((474, 510), 'numpy.arange', 'np.arange', (['(0)', 'total_size', 'block_size'], {}), '(0, total_size, block_size)\n', (483, 510), True, 'import numpy as np\n'), ((2112, 2158), 'perturb_pca.compute_dot_products', 'compute_dot_products', (['models', 'attacker', 'p_size'], {}), '(models, attacker, p_size)\n', (2132, 2158), False, 'from perturb_pca import compute_dot_products\n'), ((2596, 2619), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), '(ax)\n', (2615, 2619), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((2263, 2288), 'torch.Tensor', 'torch.Tensor', (['dot_product'], {}), '(dot_product)\n', (2275, 2288), False, 'import torch\n')]
import json from collections.__init__ import OrderedDict import numpy as np from PIL import Image from annotation_predictor.util.class_reader import ClassReader from annotation_predictor.util.oid_classcode_reader import OIDClassCodeReader from settings import known_class_ids_annotation_predictor, path_to_model_evaluation_record def compute_feature_vector(detection: dict) -> list: """ Compute a feature vector for a detection with the following features: (compare https://arxiv.org/abs/1712.08087): - score: score of the detection (i.e.: certainty of the object-detector) - rel_size: ratio of size of the bounding box of the detection over size of the image - avg: average score of all detections for the class of the object - avg-dif: difference of score (first feature) and avg (third feature) - max_dif: difference of highest score of the class and current score (first feature) - one_hot_encoding: vector with one entry for each class contained in a dataset which has a one for the class of the current detections and zeros everywhere else, uniquely defining the class. Args: detection: a object detection Returns: feature vector with the above features """ class_reader = ClassReader(known_class_ids_annotation_predictor) score = float(detection['Confidence']) rel_size = get_rel_size(detection) avg = get_avg_score(detection) avg_dif = score - avg max_dif = get_max_score(detection) - score class_index = class_reader.get_index_of_class_from_label(detection['LabelName']) # number of classes in oid dataset which is used for base training one_hot_encoding = np.zeros(1000) one_hot_encoding[class_index] = 1 feature_vector = [score, rel_size, avg, avg_dif, max_dif] feature_vector.extend(one_hot_encoding) return feature_vector def get_rel_size(detection: dict) -> float: """ Args: detection: a object detection Returns: relative size of a bounding box in an image """ return round((float(detection['XMax']) - float(detection['XMin'])) * ( float(detection['YMax']) - float(detection['YMin'])), 10) def get_avg_score(detection: dict) -> float: """ Args: detection: a object detection Returns: average score of all detections for this class. """ oid_classcode_reader = OIDClassCodeReader() cls = detection['LabelName'] if detection['LabelName'] in oid_classcode_reader.cc_to_human_readable_dict: cls = oid_classcode_reader.get_human_readable_label_for_code(cls) with open(path_to_model_evaluation_record, 'r') as f: evaluation_record = json.load(f) avg_score = evaluation_record[cls][0] return avg_score def get_max_score(detection: dict) -> float: """ Args: detection: a object detection Returns: maximum of all scores of those detections. """ oid_classcode_reader = OIDClassCodeReader() cls = detection['LabelName'] if detection['LabelName'] in oid_classcode_reader.cc_to_human_readable_dict: cls = oid_classcode_reader.get_human_readable_label_for_code(cls) with open(path_to_model_evaluation_record, 'r') as f: evaluation_record = json.load(f) max_score = evaluation_record[cls][1] return max_score def compute_iou(det_a: dict, det_b: dict) -> float: """ Args: det_a: First detection det_b: Second detection Returns: 'Intersection over Union' of two detections which equals the ratio of the intersected area of both detection-bounding-boxes over the union of both. """ bbA = [float(det_a['XMin']), float(det_a['YMin']), float(det_a['XMax']), float(det_a['YMax'])] bbB = [float(det_b['XMin']), float(det_b['YMin']), float(det_b['XMax']), float(det_b['YMax'])] x_min = max(bbA[0], bbB[0]) y_min = max(bbA[1], bbB[1]) x_max = min(bbA[2], bbB[2]) y_max = min(bbA[3], bbB[3]) intersection_area = max(0.0, x_max - x_min) * max(0.0, y_max - y_min) a_area = (bbA[0] - bbA[2]) * (bbA[1] - bbA[3]) b_area = (bbB[0] - bbB[2]) * (bbB[1] - bbB[3]) iou = round(intersection_area / float(a_area + b_area - intersection_area), 5) return iou def evaluate_prediction_record(pred: np.ndarray, label: np.ndarray): """ Evaluates the performance of an acceptance-predictor created by accept_prob_predictor.py Args: pred: Array of acceptance-predictions for a set of images label: Ground-truth data for those predictions. Returns: acc: percentage of correct predictions acc_ann: percentage of correct predictions with label 0 acc_ver: percentage of correct predictions with label 1 """ correct = 0 correct_ver = 0 correct_ann = 0 nr_ann = 0 nr_ver = 0 for i, prediction in enumerate(pred): if label[i] == 1: nr_ver += 1 if prediction > 0.5: correct += 1 correct_ver += 1 else: nr_ann += 1 if prediction < 0.5: correct += 1 correct_ann += 1 acc = round(correct / len(pred), 5) if nr_ann == 0: acc_ann = 0 else: acc_ann = round(correct_ann / nr_ann, 5) if nr_ver == 0: acc_ver = 0 else: acc_ver = round(correct_ver / nr_ver, 5) return acc, acc_ann, acc_ver def compute_label(detection: OrderedDict, ground_truth: list, alpha: float) -> float: """ Args: detection: object-detection on an image ground_truth: ground-truth values for this image alpha: required value for IoU (Intersection over Union) for the detection and a ground-truth value (of the same class) Returns: '0' if no ground-truth-box matches the detection, '1' else. """ for i in ground_truth: if i['LabelName'] == detection['LabelName'] and compute_iou(i, detection) >= alpha: return 1.0 return 0.0 def load_image(path_to_image: str): """ Args: path_to_image: Path to an image-file. Returns: Image-data in numpy format which is required for the object-detector. """ img = Image.open(path_to_image).convert('RGB') img.load() data = np.asarray(img, dtype='uint8') data = np.expand_dims(data, 0) return data
[ "json.load", "numpy.asarray", "numpy.zeros", "numpy.expand_dims", "PIL.Image.open", "annotation_predictor.util.oid_classcode_reader.OIDClassCodeReader", "annotation_predictor.util.class_reader.ClassReader" ]
[((1247, 1296), 'annotation_predictor.util.class_reader.ClassReader', 'ClassReader', (['known_class_ids_annotation_predictor'], {}), '(known_class_ids_annotation_predictor)\n', (1258, 1296), False, 'from annotation_predictor.util.class_reader import ClassReader\n'), ((1666, 1680), 'numpy.zeros', 'np.zeros', (['(1000)'], {}), '(1000)\n', (1674, 1680), True, 'import numpy as np\n'), ((2362, 2382), 'annotation_predictor.util.oid_classcode_reader.OIDClassCodeReader', 'OIDClassCodeReader', ([], {}), '()\n', (2380, 2382), False, 'from annotation_predictor.util.oid_classcode_reader import OIDClassCodeReader\n'), ((2931, 2951), 'annotation_predictor.util.oid_classcode_reader.OIDClassCodeReader', 'OIDClassCodeReader', ([], {}), '()\n', (2949, 2951), False, 'from annotation_predictor.util.oid_classcode_reader import OIDClassCodeReader\n'), ((6256, 6286), 'numpy.asarray', 'np.asarray', (['img'], {'dtype': '"""uint8"""'}), "(img, dtype='uint8')\n", (6266, 6286), True, 'import numpy as np\n'), ((6298, 6321), 'numpy.expand_dims', 'np.expand_dims', (['data', '(0)'], {}), '(data, 0)\n', (6312, 6321), True, 'import numpy as np\n'), ((2659, 2671), 'json.load', 'json.load', (['f'], {}), '(f)\n', (2668, 2671), False, 'import json\n'), ((3228, 3240), 'json.load', 'json.load', (['f'], {}), '(f)\n', (3237, 3240), False, 'import json\n'), ((6189, 6214), 'PIL.Image.open', 'Image.open', (['path_to_image'], {}), '(path_to_image)\n', (6199, 6214), False, 'from PIL import Image\n')]
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn import datasets from sklearn.decomposition import PCA import pandas as pd from urllib.request import urlretrieve import numpy as np from sklearn.linear_model import LogisticRegression # for Logistic Regression Algorithm from sklearn.model_selection import train_test_split # to split the dataset for training and testing from sklearn.neighbors import KNeighborsClassifier # KNN classifier from sklearn import metrics # for checking the model accuracy from sklearn.tree import DecisionTreeClassifier # for using DTA from sklearn import tree import seaborn as sns from sklearn.metrics import confusion_matrix from sklearn.model_selection import KFold from sklearn.externals.six import StringIO from IPython.display import Image from sklearn.tree import export_graphviz import pydotplus df = pd.read_csv('googleplaystore.csv') # let's do some cleaning df = df.rename(index=str, columns={"Content Rating": "Content_rating", "Last Updated": "Last_updated", "Current Ver":"Current_ver", "Android Ver":"Android_ver"}) df['Price'] = df.Price.str.replace('Everyone','0') df['Price'] = df.Price.str.replace('$','') df['Android_ver'] = df.Android_ver.str.replace('[^\d.]','') df['Installs'] = df.Installs.str.replace('[^\d.]','') df.mask((df == "Varies with device") | (df == "Unrated"), inplace=True) # removing a parasite row df = df.drop(df.index[[10472]]) # convert the continuous features to float df.Rating = df.Rating.astype(float) df['Reviews'] = df['Reviews'].str.extract('(\d*\.?\d*)', expand=False).astype(float) df['Installs'] = pd.to_numeric(df.Installs.str.replace('[^\d.]', ''), errors='coerce') df['Price'] = df['Price'].str.extract('(\d*\.?\d*)', expand=False).astype(float) # the feature size required more tedious work def preprocess_Size(df_size): df_size = (df_size.replace(r'[kM]+$', '', regex=True).astype(float) * \ df_size.str.extract(r'[\d\.]+([kM]+)', expand=False) .fillna(1) .replace(['k','M'], [10**3, 10**6]).astype(int)) return(df_size) df['Size'] = preprocess_Size(df['Size']) # Calculate the means of the continuous features avg_rating = df["Rating"].mean() avg_size = df["Size"].mean() avg_reviews = df["Reviews"].mean() avg_install = df["Installs"].mean() avg_price = df["Price"].mean() # Put the averages in a list avg_list = [avg_rating, avg_reviews, avg_size, avg_install, avg_price] # Print the means print("~ The features Avg ~") print("avg_rating: ", avg_rating) print("avg_reviews: ", avg_reviews) print("avg_install: ", avg_install) print("avg_price: ", avg_price) print("avg_size: ", avg_size) # print("Rating avg: ", avg_rating) # Calculate the SD sd_rating = df["Rating"].std() sd_review = df["Reviews"].std() sd_size = df["Size"].std() sd_install = df["Installs"].std() sd_price = df["Price"].std() # Put them in a list std_list = [sd_rating, sd_review, sd_size, sd_install, sd_price] # print the SDs print("~ The SD of the features ~") print("Rating: ", sd_rating) print("Reviews: ", sd_review) print("Size: ", sd_size) print("Installs: ", sd_install) print("Price: ", sd_price) x_pos = [1, 2, 3, 4, 5] att = ["Rating", "Reviews", "Size", "Installs", "Price"] # show the mean and SD fig, ax = plt.subplots() ax.bar(x_pos, avg_list, yerr=std_list, align='center', alpha=0.5, ecolor='black', capsize=10) ax.set_ylabel('Y axis') ax.set_xticks(x_pos) ax.set_xticklabels(att) ax.set_title('Mean and Standard deviation of the continuous features') ax.yaxis.grid(True) plt.tight_layout() plt.show() # Value count values_count = [df["Rating"].sum(), df["Reviews"].sum(), df["Size"].sum(), df["Installs"].sum(), df["Price"].sum()] fig1, ax1 = plt.subplots() ax1.bar(x_pos, values_count, align='center', alpha=0.5, ecolor='black', capsize=10) ax1.set_ylabel('Counts') ax1.set_xticks(x_pos) ax1.set_xticklabels(att) ax1.set_title('Plot of the values count of the continuous features') ax1.yaxis.grid(True) plt.tight_layout() plt.show() # Preprocess all the data (from categorical to continuous) from sklearn import preprocessing from sklearn.pipeline import Pipeline def handle_non_numerical_data(df): columns = df.columns.values for column in columns: text_digit_vals = {} def convert_to_int(val): return text_digit_vals[val] if df[column].dtype != np.int64 and df[column].dtype!= np.float64: column_contents = df[column].values.tolist() unique_elements = set(column_contents) x = 0 for unique in unique_elements: if unique not in text_digit_vals: text_digit_vals[unique]=x x+=1 df[column]= list(map(convert_to_int,df[column])) return df df = handle_non_numerical_data(df) # Check correlation # plt.figure(figsize=(8,4)) # sns.heatmap(df.corr(), annot=True, cmap='cubehelix_r') # draws heatmap with input as correlation matrix calculated by iris.corr() # plt.show() # Delete useless column del df["App"] # Since we will use Category as target, put it as the last column df = df[['Rating', 'Reviews', 'Size', 'Installs', 'Type', 'Price', 'Content_rating', 'Genres', 'Last_updated', 'Current_ver', 'Android_ver', 'Category']] features = ['Rating', 'Reviews', 'Size', 'Installs', 'Type', 'Price', 'Content_rating', 'Genres', 'Last_updated', 'Current_ver', 'Android_ver'] # Reconvert to csv for Random Forest algo df_preprocessed = df.to_csv('googleplaystore_preprocessed.csv', index=False) # Preprocessing data = np.array(df) X = np.delete(data, 11, axis=1) X = np.nan_to_num(X) y = data[:,-1] # Splitting train_X, test_X, train_y, test_y = train_test_split(X, y, test_size=0.25) # Decision tree model = DecisionTreeClassifier() model.fit(train_X, train_y) prediction = model.predict(test_X) accuracy = metrics.accuracy_score(prediction, test_y) print("Accuracy of DT : ", accuracy) # plot DT dot_data = tree.export_graphviz(model, out_file=None, feature_names=features) # Draw graph graph = pydotplus.graph_from_dot_data(dot_data) # Show graph Image(graph.create_png()) # Create PDF and PNG graph.write_pdf("googleplaystore_tree.pdf") graph.write_png("googleplaystore_tree.png") # Confusion Matrix print ("The Confusion matrix: ") print (confusion_matrix(test_y, prediction)) def perf_measure(y_actual, y_hat): TP = 0 FP = 0 TN = 0 FN = 0 for i in range(len(y_hat)): if y_actual[i]==y_hat[i]==1: TP += 1 if y_hat[i]==1 and y_actual[i]!=y_hat[i]: FP += 1 if y_actual[i]==y_hat[i]==0: TN += 1 if y_hat[i]==0 and y_actual[i]!=y_hat[i]: FN += 1 return(print("TP, FP, TN, FN: ",TP, FP, TN, FN)) print(perf_measure(test_y, prediction)) # Kfold kf = KFold(n_splits=4) kf.get_n_splits(X) for train_index, test_index in kf.split(X): print("KFold train-test cross validation") print("TRAIN:", train_index, "TEST:", test_index) X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] # resubstitution validation prediction_identical = model.predict(train_X) print('The accuracy resubstitution: ', metrics.accuracy_score(prediction_identical, train_y))
[ "matplotlib.pyplot.show", "numpy.nan_to_num", "pandas.read_csv", "sklearn.model_selection.train_test_split", "sklearn.metrics.accuracy_score", "matplotlib.pyplot.subplots", "sklearn.tree.DecisionTreeClassifier", "sklearn.tree.export_graphviz", "pydotplus.graph_from_dot_data", "sklearn.model_selection.KFold", "numpy.array", "sklearn.metrics.confusion_matrix", "matplotlib.pyplot.tight_layout", "numpy.delete" ]
[((881, 915), 'pandas.read_csv', 'pd.read_csv', (['"""googleplaystore.csv"""'], {}), "('googleplaystore.csv')\n", (892, 915), True, 'import pandas as pd\n'), ((3249, 3263), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (3261, 3263), True, 'import matplotlib.pyplot as plt\n'), ((3518, 3536), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (3534, 3536), True, 'import matplotlib.pyplot as plt\n'), ((3537, 3547), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3545, 3547), True, 'import matplotlib.pyplot as plt\n'), ((3691, 3705), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (3703, 3705), True, 'import matplotlib.pyplot as plt\n'), ((3952, 3970), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (3968, 3970), True, 'import matplotlib.pyplot as plt\n'), ((3971, 3981), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3979, 3981), True, 'import matplotlib.pyplot as plt\n'), ((5410, 5422), 'numpy.array', 'np.array', (['df'], {}), '(df)\n', (5418, 5422), True, 'import numpy as np\n'), ((5427, 5454), 'numpy.delete', 'np.delete', (['data', '(11)'], {'axis': '(1)'}), '(data, 11, axis=1)\n', (5436, 5454), True, 'import numpy as np\n'), ((5459, 5475), 'numpy.nan_to_num', 'np.nan_to_num', (['X'], {}), '(X)\n', (5472, 5475), True, 'import numpy as np\n'), ((5539, 5577), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.25)'}), '(X, y, test_size=0.25)\n', (5555, 5577), False, 'from sklearn.model_selection import train_test_split\n'), ((5603, 5627), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {}), '()\n', (5625, 5627), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((5702, 5744), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['prediction', 'test_y'], {}), '(prediction, test_y)\n', (5724, 5744), False, 'from sklearn import metrics\n'), ((5804, 5870), 'sklearn.tree.export_graphviz', 'tree.export_graphviz', (['model'], {'out_file': 'None', 'feature_names': 'features'}), '(model, out_file=None, feature_names=features)\n', (5824, 5870), False, 'from sklearn import tree\n'), ((5926, 5965), 'pydotplus.graph_from_dot_data', 'pydotplus.graph_from_dot_data', (['dot_data'], {}), '(dot_data)\n', (5955, 5965), False, 'import pydotplus\n'), ((6685, 6702), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': '(4)'}), '(n_splits=4)\n', (6690, 6702), False, 'from sklearn.model_selection import KFold\n'), ((6178, 6214), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['test_y', 'prediction'], {}), '(test_y, prediction)\n', (6194, 6214), False, 'from sklearn.metrics import confusion_matrix\n'), ((7081, 7134), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['prediction_identical', 'train_y'], {}), '(prediction_identical, train_y)\n', (7103, 7134), False, 'from sklearn import metrics\n')]
import argparse import os from collections import defaultdict from typing import Dict, List import ipdb import torch import torchvision.transforms as T import torchvision.transforms.functional as F from torch import nn from torch.utils.data import DataLoader, Dataset from tqdm import tqdm from yacs.config import CfgNode from maskrcnn_benchmark.config import cfg from maskrcnn_benchmark.modeling.detector import build_detection_model from maskrcnn_benchmark.structures.bounding_box import BoxList from maskrcnn_benchmark.structures.image_list import ImageList, to_image_list from maskrcnn_benchmark.utils.checkpoint import DetectronCheckpointer from utils.data import VideoDataset from utils.io import dump_pickle, load_image, load_pickle import numpy as np # MSVD = True # class Args(TypedArgs): # def __init__(self): # parser = argparse.ArgumentParser() # self.frame_path = parser.add_argument( # '-f', '--frame-path', # ) # self.output = parser.add_argument( # '-o', '--output' # ) # self.batch_size = parser.add_argument( # '-b', '--batch-size', type=int, default=16 # ) # self.num_workers = parser.add_argument( # '-n', '--num-workers', type=int, default=4 # ) # self.parse_args_from(parser) parser = argparse.ArgumentParser() parser.add_argument('-f', '--frame-path', help='path to frames') parser.add_argument('-o', '--output', help='path to output pt file') parser.add_argument('-b', '--batch-size', default=16) parser.add_argument('-n', '--num-workers', type=int, default=4) parser.add_argument('--msvd', action='store_true', help='for MSVD-QA') parser.add_argument( '-c', '--config', help='path to e2e_mask_rcnn_R_101_FPN_1x_caffe2.yaml') class Resize(object): def __init__(self, min_size, max_size): self.min_size = min_size self.max_size = max_size # modified from torchvision to add support for max size def get_size(self, image_size): w, h = image_size size = self.min_size max_size = self.max_size if max_size is not None: min_original_size = float(min((w, h))) max_original_size = float(max((w, h))) if max_original_size / min_original_size * size > max_size: size = int( round(max_size * min_original_size / max_original_size)) if (w <= h and w == size) or (h <= w and h == size): return (h, w) if w < h: ow = size oh = int(size * h / w) else: oh = size ow = int(size * w / h) return (oh, ow) def __call__(self, image): size = self.get_size(image.size) image = F.resize(image, size) return image class FrameDataset(Dataset): def __init__(self, cfg: CfgNode, samples: List[str]): self.cfg = cfg self.transform = self.build_transform() self.samples: List[str] = samples def __len__(self): return len(self.samples) def __getitem__(self, index): sample = self.samples[index] image = load_image(sample) image = self.transform(image) return image def build_transform(self): cfg = self.cfg to_bgr = T.Lambda(lambda x: x[[2, 1, 0]] * 255) normalize = T.Normalize( cfg.INPUT.PIXEL_MEAN, cfg.INPUT.PIXEL_STD ) transform = T.Compose([ Resize(cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MAX_SIZE_TEST), T.ToTensor(), to_bgr, normalize ]) return transform # def set_samples(self, samples): # self.samples = samples class GIFDataset(Dataset): def __init__(self, cfg: CfgNode, args): self.cfg = cfg self.args = args self.samples: List[str] = load_pickle(args.frame_path) self.video_dict: Dict[str, List[str]] = defaultdict(list) self.videos = [] for sample in tqdm(self.samples): gif_name = sample.split('/')[-1] self.videos.append(gif_name) num_frames = len(os.listdir(sample)) # if MSVD: if args.msvd: selected_frames = np.linspace( 0, num_frames, 20 + 2)[1:20+1].astype(np.int) + 1 for n in selected_frames: self.video_dict[gif_name].append( # os.path.join(sample, f'{n}.jpg') # For TGIF-QA os.path.join(sample, f'{n + 1:06}.jpg') # For MSVD-QA ) else: for n in range(num_frames): self.video_dict[gif_name].append( os.path.join(sample, f'{n}.jpg') # For TGIF-QA # os.path.join(sample, f'{n + 1:06}.jpg') # For MSVD-QA ) # self.frame_dataset = FrameDataset(cfg) def __getitem__(self, index): gif_name = self.videos[index] # self.frame_dataset.set_samples(self.video_dict[gif_name]) dataset = FrameDataset(self.cfg, self.video_dict[gif_name]) loader = DataLoader( dataset, batch_size=self.args.batch_size, shuffle=False, num_workers=self.args.num_workers, pin_memory=True, collate_fn=collate_fn ) return loader, gif_name def __len__(self): return len(self.samples) def collate_fn(batch: List[torch.Tensor]) -> ImageList: return to_image_list(batch, size_divisible=cfg.DATALOADER.SIZE_DIVISIBILITY) class Extractor: def __init__(self, cfg: CfgNode, args): self.args = args self.cfg = cfg.clone() self.model: nn.Module = build_detection_model(cfg) self.model.eval() self.device = torch.device(cfg.MODEL.DEVICE) self.model.to(self.device) # Load weight save_dir = cfg.OUTPUT_DIR checkpointer = DetectronCheckpointer( cfg, self.model, save_dir=save_dir ) _ = checkpointer.load(cfg.MODEL.WEIGHT) self.cpu_device = torch.device('cpu') # Keep all result self.confidence_threshold = 0. self.datasets = GIFDataset(cfg, args) self.results: Dict[str, List] = defaultdict(list) @torch.no_grad() def compute_predictions(self, image_list: ImageList) -> List[BoxList]: image_list = image_list.to(self.device) predictions = self.model(image_list) return predictions def run_once(self): for dataset, gif_name in self.datasets: # ipdb.set_trace() loader = DataLoader( dataset, batch_size=self.args.batch_size, shuffle=False, num_workers=0, pin_memory=True, collate_fn=collate_fn ) for image_list in loader: predictions = self.compute_predictions(image_list) self.save_predictions(gif_name, predictions) ipdb.set_trace() break break self.dump_result() def run(self): dataset_loader = DataLoader( self.datasets, batch_size=1, collate_fn=lambda x: x[0] ) for loader, gif_name in tqdm(dataset_loader): # ipdb.set_trace() for image_list in tqdm(loader): predictions = self.compute_predictions(image_list) self.save_predictions(gif_name, predictions) self.dump_result() def save_predictions(self, gif_name: str, predictions: List[BoxList]): # preds = [ # { # 'bbox': pred.bbox, # 'scores': pred.scores, # 'labels': pred.labels, # } # for pred in predictions # ] for pred in predictions: pred: BoxList = pred.to(self.cpu_device).resize((1, 1)) self.results[gif_name].append( { 'bbox': pred.bbox, 'scores': pred.get_field('scores'), 'labels': pred.get_field('labels'), } ) def dump_result(self): torch.save(self.results, self.args.output) def load_config(config_file='/home/huangdeng/Code/python/maskrcnn/maskrcnn-benchmark/configs/caffe2/e2e_mask_rcnn_R_101_FPN_1x_caffe2.yaml') -> CfgNode: cfg.merge_from_file(config_file) cfg.merge_from_list(["MODEL.MASK_ON", False]) return cfg def main(args): cfg = load_config(args.config) extractor = Extractor(cfg, args) # extractor.run_once() extractor.run() if __name__ == "__main__": # args = Args() args = parser.parse_args() main(args)
[ "argparse.ArgumentParser", "ipdb.set_trace", "collections.defaultdict", "maskrcnn_benchmark.config.cfg.merge_from_list", "maskrcnn_benchmark.modeling.detector.build_detection_model", "torch.device", "torchvision.transforms.Normalize", "maskrcnn_benchmark.structures.image_list.to_image_list", "torch.no_grad", "os.path.join", "torch.utils.data.DataLoader", "torchvision.transforms.Lambda", "utils.io.load_image", "maskrcnn_benchmark.config.cfg.merge_from_file", "numpy.linspace", "tqdm.tqdm", "maskrcnn_benchmark.config.cfg.clone", "torchvision.transforms.functional.resize", "os.listdir", "maskrcnn_benchmark.utils.checkpoint.DetectronCheckpointer", "utils.io.load_pickle", "torch.save", "torchvision.transforms.ToTensor" ]
[((1350, 1375), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1373, 1375), False, 'import argparse\n'), ((5589, 5658), 'maskrcnn_benchmark.structures.image_list.to_image_list', 'to_image_list', (['batch'], {'size_divisible': 'cfg.DATALOADER.SIZE_DIVISIBILITY'}), '(batch, size_divisible=cfg.DATALOADER.SIZE_DIVISIBILITY)\n', (5602, 5658), False, 'from maskrcnn_benchmark.structures.image_list import ImageList, to_image_list\n'), ((6384, 6399), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6397, 6399), False, 'import torch\n'), ((8554, 8586), 'maskrcnn_benchmark.config.cfg.merge_from_file', 'cfg.merge_from_file', (['config_file'], {}), '(config_file)\n', (8573, 8586), False, 'from maskrcnn_benchmark.config import cfg\n'), ((8591, 8636), 'maskrcnn_benchmark.config.cfg.merge_from_list', 'cfg.merge_from_list', (["['MODEL.MASK_ON', False]"], {}), "(['MODEL.MASK_ON', False])\n", (8610, 8636), False, 'from maskrcnn_benchmark.config import cfg\n'), ((2777, 2798), 'torchvision.transforms.functional.resize', 'F.resize', (['image', 'size'], {}), '(image, size)\n', (2785, 2798), True, 'import torchvision.transforms.functional as F\n'), ((3168, 3186), 'utils.io.load_image', 'load_image', (['sample'], {}), '(sample)\n', (3178, 3186), False, 'from utils.io import dump_pickle, load_image, load_pickle\n'), ((3319, 3357), 'torchvision.transforms.Lambda', 'T.Lambda', (['(lambda x: x[[2, 1, 0]] * 255)'], {}), '(lambda x: x[[2, 1, 0]] * 255)\n', (3327, 3357), True, 'import torchvision.transforms as T\n'), ((3379, 3433), 'torchvision.transforms.Normalize', 'T.Normalize', (['cfg.INPUT.PIXEL_MEAN', 'cfg.INPUT.PIXEL_STD'], {}), '(cfg.INPUT.PIXEL_MEAN, cfg.INPUT.PIXEL_STD)\n', (3390, 3433), True, 'import torchvision.transforms as T\n'), ((3903, 3931), 'utils.io.load_pickle', 'load_pickle', (['args.frame_path'], {}), '(args.frame_path)\n', (3914, 3931), False, 'from utils.io import dump_pickle, load_image, load_pickle\n'), ((3981, 3998), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (3992, 3998), False, 'from collections import defaultdict\n'), ((4047, 4065), 'tqdm.tqdm', 'tqdm', (['self.samples'], {}), '(self.samples)\n', (4051, 4065), False, 'from tqdm import tqdm\n'), ((5206, 5352), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset'], {'batch_size': 'self.args.batch_size', 'shuffle': '(False)', 'num_workers': 'self.args.num_workers', 'pin_memory': '(True)', 'collate_fn': 'collate_fn'}), '(dataset, batch_size=self.args.batch_size, shuffle=False,\n num_workers=self.args.num_workers, pin_memory=True, collate_fn=collate_fn)\n', (5216, 5352), False, 'from torch.utils.data import DataLoader, Dataset\n'), ((5767, 5778), 'maskrcnn_benchmark.config.cfg.clone', 'cfg.clone', ([], {}), '()\n', (5776, 5778), False, 'from maskrcnn_benchmark.config import cfg\n'), ((5811, 5837), 'maskrcnn_benchmark.modeling.detector.build_detection_model', 'build_detection_model', (['cfg'], {}), '(cfg)\n', (5832, 5837), False, 'from maskrcnn_benchmark.modeling.detector import build_detection_model\n'), ((5886, 5916), 'torch.device', 'torch.device', (['cfg.MODEL.DEVICE'], {}), '(cfg.MODEL.DEVICE)\n', (5898, 5916), False, 'import torch\n'), ((6032, 6089), 'maskrcnn_benchmark.utils.checkpoint.DetectronCheckpointer', 'DetectronCheckpointer', (['cfg', 'self.model'], {'save_dir': 'save_dir'}), '(cfg, self.model, save_dir=save_dir)\n', (6053, 6089), False, 'from maskrcnn_benchmark.utils.checkpoint import DetectronCheckpointer\n'), ((6187, 6206), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (6199, 6206), False, 'import torch\n'), ((6360, 6377), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (6371, 6377), False, 'from collections import defaultdict\n'), ((7271, 7337), 'torch.utils.data.DataLoader', 'DataLoader', (['self.datasets'], {'batch_size': '(1)', 'collate_fn': '(lambda x: x[0])'}), '(self.datasets, batch_size=1, collate_fn=lambda x: x[0])\n', (7281, 7337), False, 'from torch.utils.data import DataLoader, Dataset\n'), ((7416, 7436), 'tqdm.tqdm', 'tqdm', (['dataset_loader'], {}), '(dataset_loader)\n', (7420, 7436), False, 'from tqdm import tqdm\n'), ((8352, 8394), 'torch.save', 'torch.save', (['self.results', 'self.args.output'], {}), '(self.results, self.args.output)\n', (8362, 8394), False, 'import torch\n'), ((6721, 6847), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset'], {'batch_size': 'self.args.batch_size', 'shuffle': '(False)', 'num_workers': '(0)', 'pin_memory': '(True)', 'collate_fn': 'collate_fn'}), '(dataset, batch_size=self.args.batch_size, shuffle=False,\n num_workers=0, pin_memory=True, collate_fn=collate_fn)\n', (6731, 6847), False, 'from torch.utils.data import DataLoader, Dataset\n'), ((7500, 7512), 'tqdm.tqdm', 'tqdm', (['loader'], {}), '(loader)\n', (7504, 7512), False, 'from tqdm import tqdm\n'), ((3582, 3594), 'torchvision.transforms.ToTensor', 'T.ToTensor', ([], {}), '()\n', (3592, 3594), True, 'import torchvision.transforms as T\n'), ((4182, 4200), 'os.listdir', 'os.listdir', (['sample'], {}), '(sample)\n', (4192, 4200), False, 'import os\n'), ((7139, 7155), 'ipdb.set_trace', 'ipdb.set_trace', ([], {}), '()\n', (7153, 7155), False, 'import ipdb\n'), ((4561, 4600), 'os.path.join', 'os.path.join', (['sample', 'f"""{n + 1:06}.jpg"""'], {}), "(sample, f'{n + 1:06}.jpg')\n", (4573, 4600), False, 'import os\n'), ((4779, 4811), 'os.path.join', 'os.path.join', (['sample', 'f"""{n}.jpg"""'], {}), "(sample, f'{n}.jpg')\n", (4791, 4811), False, 'import os\n'), ((4285, 4319), 'numpy.linspace', 'np.linspace', (['(0)', 'num_frames', '(20 + 2)'], {}), '(0, num_frames, 20 + 2)\n', (4296, 4319), True, 'import numpy as np\n')]
""" Generative Adversarial Network for fitting tuning curve generator. This module implements Wasserstein GAN (`BPTTWassersteinGAN`) to fit `TuningCurveGenerator`. It is composed of the following components: - `BPTTWassersteinGAN` - `.TuningCurveGenerator`: generator - `UnConditionalDiscriminator`: discriminator - `GeneratorTrainer`: generator-trainer - `CriticTrainer`: discriminator (critic)-trainer Generator and Discriminator only define the symbolic expression of the forward-pass and gradients (backward-pass) are calculated in their trainer. `BPTTWassersteinGAN` is responsible for bundling them together, managing numeric data, and looping through the learning argorithm. """ import itertools import lasagne import numpy as np from .. import ssnode from ..core import BaseComponent, consume_subdict from ..gradient_expressions.utils import sample_sites_from_stim_space from ..lasagne_toppings.rechack import largerrecursionlimit from ..utils import ( cached_property, cartesian_product, random_minibatches, StopWatch, theano_function, log_timing, Namespace, ) from .ssn import make_tuning_curve_generator, maybe_mixin_noise, is_heteroin DEFAULT_PARAMS = dict( bandwidths=ssnode.DEFAULT_PARAMS['bandwidths'], contrasts=ssnode.DEFAULT_PARAMS['contrast'], smoothness=ssnode.DEFAULT_PARAMS['smoothness'], sample_sites=[0], # Stimulator: num_sites=ssnode.DEFAULT_PARAMS['N'], # Model / SSN: k=ssnode.DEFAULT_PARAMS['k'], n=ssnode.DEFAULT_PARAMS['n'], io_type='asym_tanh', tau_E=10, tau_I=1, dt=0.1, seqlen=1200, batchsize=1, skip_steps=1000, gen=dict( rate_cost=0.01, rate_penalty_threshold=200.0, ), disc=dict( rate_penalty_bound=-1.0, ), ) class UnConditionalDiscriminator(BaseComponent): def __init__(self, shape, loss_type, layers, normalization, nonlinearity, net_options=None): from .simple_discriminator import make_net self.l_out = make_net( shape, loss_type, layers, normalization, nonlinearity, options=net_options, ) from theano import tensor as T self.xg = xg = T.matrix() # \tilde x -- "fake image" self.xd = xd = T.matrix() # x -- ground truth Dg = self.get_output(xg) Dd = self.get_output(xd) self.accuracy_expr = Dg.mean() - Dd.mean() @cached_property def accuracy(self): return theano_function([self.xg, self.xd], self.accuracy_expr) def get_all_params(self): return lasagne.layers.get_all_params(self.l_out, trainable=True) def get_output(self, inputs=None): return lasagne.layers.get_output(self.l_out, inputs=inputs) def prepare(self): """ Force compile Theano functions. """ self.accuracy def apply_l2_decay(updates, params, decay): for var in params: updates[var] -= decay * var def apply_l1_decay(updates, params, decay): from theano.tensor import sgn for var in params: updates[var] -= decay * sgn(var) class Updater(BaseComponent): _named_update_configs = { # Values recommended by Gulrajani et al. (2017) # -- http://arxiv.org/abs/1704.00028: 'adam-wgan': ('adam', dict(beta1=0.5, beta2=0.9)), } def __init__(self, learning_rate=0.001, update_name='adam-wgan', update_config={}, reg_l2_penalty=0.0, reg_l2_decay=0.0, reg_l1_penalty=0.0, reg_l1_decay=0.0): self.learning_rate = learning_rate self.update_name = update_name self.update_config = update_config self.reg_l2_penalty = reg_l2_penalty self.reg_l1_penalty = reg_l1_penalty self.reg_l2_decay = reg_l2_decay # Loshchilov & Hutter (2017) self.reg_l1_decay = reg_l1_decay def _get_updater(self): name, default = self._named_update_configs.get( self.update_name, (self.update_name, {})) updater = getattr(lasagne.updates, name) config = dict(default, **self.update_config) return updater, config def __call__(self, loss, params): updater, config = self._get_updater() # Add L2/L1 regularizatio penalty to `loss`: if self.reg_l2_penalty: loss += lasagne.regularization.apply_penalty( params, lasagne.regularization.l2, ) * self.reg_l2_penalty if self.reg_l1_penalty: loss += lasagne.regularization.apply_penalty( params, lasagne.regularization.l1, ) * self.reg_l1_penalty # Compute gradient & update formulae: updates = updater( loss, params, learning_rate=self.learning_rate, **config) # Add L2/L1 weight decay to the update: learning_rate = self.learning_rate if self.reg_l2_decay: apply_l2_decay(updates, params, learning_rate * self.reg_l2_decay) if self.reg_l1_decay: apply_l1_decay(updates, params, learning_rate * self.reg_l1_decay) return updates class BaseTrainer(BaseComponent): @classmethod def consume_kwargs(self, *args, **kwargs): updater, rest = Updater.consume_kwargs(**kwargs) return super(BaseTrainer, self).consume_kwargs( *args, updater=updater, **rest) def get_updates(self): with log_timing("{}.update()".format(self.__class__.__name__)): return self.updater(self.loss, self.target.get_all_params()) @cached_property def train_impl(self): with log_timing("compiling {}.train_impl" .format(self.__class__.__name__)): return theano_function(self.inputs, self.loss, updates=self.get_updates()) train = property(lambda self: self.train_impl) def prepare(self): """ Force compile Theano functions. """ self.train_impl class CriticTrainer(BaseTrainer): """ Discriminator/Critic trainer for WGAN. """ def __init__(self, disc, updater): self.target = disc self.updater = updater from theano import tensor as T self.lmd = lmd = T.scalar() self.xg = xg = T.matrix() # \tilde x -- "fake image" self.xd = xd = T.matrix() # x -- ground truth self.xp = xp = T.matrix() # \hat x -- interpolated sample self.disc_gene = disc.get_output(xg).mean() self.disc_data = disc.get_output(xd).mean() self.disc_intp = disc.get_output(xp)[:, 0] self.dgrad = T.jacobian(self.disc_intp, xp) self.penalty = ((self.dgrad.norm(2, axis=(1, 2)) - 1)**2).mean() self.loss = self.disc_gene - self.disc_data + lmd * self.penalty self.inputs = (xg, xd, xp, lmd) class GeneratorTrainer(BaseTrainer): def __init__(self, gen, disc, dynamics_cost, rate_cost, J_min, J_max, D_min, D_max, S_min, S_max, updater): self.target = self.gen = gen self.disc = disc self.dynamics_cost = dynamics_cost self.rate_cost = rate_cost self.J_min = J_min self.J_max = J_max self.D_min = D_min self.D_max = D_max self.S_min = S_min self.S_max = S_max self.updater = updater self.post_init() def post_init(self): gen = self.gen disc = self.disc self.loss = - disc.get_output(gen.get_output()).mean() self.loss += self.dynamics_cost * gen.model.dynamics_penalty self.loss += self.rate_cost * gen.model.rate_penalty self.inputs = gen.inputs def clip_params(self, updates): for var in self.gen.get_all_params(): p_min = getattr(self, var.name + '_min') p_max = getattr(self, var.name + '_max') p_min = np.array(p_min, dtype=updates[var].dtype) p_max = np.array(p_max, dtype=updates[var].dtype) updates[var] = updates[var].clip(p_min, p_max) return updates def get_updates(self): return self.clip_params(super(GeneratorTrainer, self).get_updates()) def train(self, rng=None, **kwargs): kwargs = maybe_mixin_noise(self.gen, rng, kwargs) values = [kwargs.pop(k) for k in self.gen._input_names] assert not kwargs return self.train_impl(*values) class HeteroInGeneratorTrainer(GeneratorTrainer): def __init__(self, gen, disc, dynamics_cost, rate_cost, J_min, J_max, D_min, D_max, S_min, S_max, updater, V_min=0, V_max=1): self.target = self.gen = gen self.disc = disc self.dynamics_cost = dynamics_cost self.rate_cost = rate_cost self.J_min = J_min self.J_max = J_max self.D_min = D_min self.D_max = D_max self.S_min = S_min self.S_max = S_max self.V_min = V_min self.V_max = V_max self.updater = updater self.post_init() def emit_generator_trainer(gen, *args, **kwargs): if is_heteroin(gen): trainer_class = HeteroInGeneratorTrainer else: trainer_class = GeneratorTrainer return trainer_class.consume_kwargs(gen, *args, **kwargs) def grid_stimulator_inputs(contrasts, bandwidths, batchsize): product = cartesian_product(contrasts, bandwidths) return np.tile(product.reshape((1,) + product.shape), (batchsize,) + (1,) * product.ndim).swapaxes(0, 1) class BPTTWassersteinGAN(BaseComponent): def __init__(self, gen, disc, gen_trainer, disc_trainer, bandwidths, contrasts, include_inhibitory_neurons, rate_penalty_threshold, critic_iters_init, critic_iters, lipschitz_cost, disc_rate_penalty_bound, seed=0): self.gen = gen self.disc = disc self.gen_trainer = gen_trainer self.disc_trainer = disc_trainer self.critic_iters_init = critic_iters_init self.critic_iters = critic_iters self.lipschitz_cost = lipschitz_cost self.disc_rate_penalty_bound = disc_rate_penalty_bound self.rng = np.random.RandomState(seed) self.bandwidths = bandwidths self.contrasts = contrasts self.stimulator_contrasts, self.stimulator_bandwidths \ = grid_stimulator_inputs(contrasts, bandwidths, self.batchsize) self.include_inhibitory_neurons = include_inhibitory_neurons # As of writing, this variable is not required for learning. # This is only used from `sample_sites` property which is only # used from bptt_wgan.learn. self.rate_penalty_threshold = rate_penalty_threshold batchsize = property(lambda self: self.gen.batchsize) num_neurons = property(lambda self: self.gen.num_neurons) @property def sample_sites(self): probes = list(self.gen.prober.probes) if self.include_inhibitory_neurons: return probes[:len(probes) // 2] else: return probes # To be compatible with GANDriver: loss_type = 'WD' discriminator = property(lambda self: self.disc.l_out) NZ = property(lambda self: self.batchsize) def get_gen_param(self): # To be called from GANDriver return [ self.gen.model.J.get_value(), self.gen.model.D.get_value(), self.gen.model.S.get_value(), ] def set_dataset(self, data, **kwargs): kwargs.setdefault('seed', self.rng) self.dataset = random_minibatches(self.batchsize, data, **kwargs) def next_minibatch(self): return next(self.dataset) def prepare(self): """ Force compile Theano functions. """ with largerrecursionlimit(self.gen.model.unroll_scan, self.gen.model.seqlen): self.gen.prepare() self.gen_trainer.prepare() self.disc.prepare() self.disc_trainer.prepare() def gen_forward(self): return self.gen.forward( rng=self.rng, stimulator_bandwidths=self.stimulator_bandwidths, stimulator_contrasts=self.stimulator_contrasts, model_rate_penalty_threshold=self.rate_penalty_threshold, ) def train_discriminator(self, info): xd = self.next_minibatch() eps = self.rng.rand(self.batchsize).reshape((-1, 1)) with self.gen_forward_watch: gen_out = self.gen_forward() xg = gen_out.prober_tuning_curve xp = eps * xd + (1 - eps) * xg info.gen_out = gen_out info.dynamics_penalty = gen_out.model_dynamics_penalty info.rate_penalty = gen_out.model_rate_penalty info.xd = xd info.xg = xg info.xp = xp info.gen_time = self.gen_forward_watch.times[-1] bound = self.disc_rate_penalty_bound if bound > 0 and gen_out.model_rate_penalty > bound: info.disc_loss = np.nan info.accuracy = np.nan info.disc_time = np.nan return info with self.disc_train_watch: info.disc_loss = self.disc_trainer.train( xg, xd, xp, self.lipschitz_cost, ) info.accuracy = self.disc.accuracy(xg, xd) info.disc_time = self.disc_train_watch.times[-1] return info def train_generator(self, info): with self.gen_train_watch: info.gen_loss = self.gen_trainer.train( rng=self.rng, stimulator_bandwidths=self.stimulator_bandwidths, stimulator_contrasts=self.stimulator_contrasts, model_rate_penalty_threshold=self.rate_penalty_threshold, ) info.gen_forward_time = self.gen_forward_watch.sum() info.gen_train_time = self.gen_train_watch.sum() info.gen_time = info.gen_train_time + info.gen_forward_time info.disc_time = self.disc_train_watch.sum() return info def _single_gen_step(self, gen_step, critic_iters): self.gen_forward_watch = StopWatch() self.gen_train_watch = StopWatch() self.disc_train_watch = StopWatch() for disc_step in range(critic_iters): info = Namespace(is_discriminator=True, gen_step=gen_step, disc_step=disc_step) yield self.train_discriminator(info) info = Namespace(is_discriminator=False, gen_step=gen_step) yield self.train_generator(info) def learning(self): for info in self._single_gen_step(0, self.critic_iters_init): yield info for gen_step in itertools.count(1): for info in self._single_gen_step(gen_step, self.critic_iters): yield info def probes_from_stim_space(stim_locs, num_sites, include_inhibitory_neurons): probes = sample_sites_from_stim_space(stim_locs, num_sites) if include_inhibitory_neurons: probes.extend(np.array(probes) + num_sites) return probes def make_gan(config): """make_gan(config: dict) -> (GAN, dict) Initialize a GAN given `config` and return unconsumed part of `config`. """ kwargs = dict(DEFAULT_PARAMS, **config) kwargs['gen'] = dict(DEFAULT_PARAMS['gen'], **config.get('gen', {})) kwargs['disc'] = dict(DEFAULT_PARAMS['disc'], **config.get('disc', {})) return _make_gan_from_kwargs(**kwargs) def _make_gan_from_kwargs( J0, S0, D0, num_sites, bandwidths, contrasts, sample_sites, include_inhibitory_neurons, consume_union=True, **rest): probes = probes_from_stim_space(sample_sites, num_sites, include_inhibitory_neurons) if 'V0' in rest: rest['V'] = rest.pop('V0') rate_penalty_threshold = rest['gen'].pop('rate_penalty_threshold') # FIXME disc_rate_penalty_bound = rest['disc'].pop('rate_penalty_bound') # FIXME gen, rest = make_tuning_curve_generator( rest, consume_union=consume_union, # Stimulator: num_tcdom=len(bandwidths) * len(contrasts), num_sites=num_sites, # Model / SSN: J=J0, D=D0, S=S0, # Prober: probes=probes, ) disc, rest = consume_subdict( UnConditionalDiscriminator.consume_kwargs, 'disc', rest, shape=gen.output_shape, loss_type='WD', ) gen_trainer, rest = consume_subdict( emit_generator_trainer, 'gen', rest, gen, disc, ) disc_trainer, rest = consume_subdict( CriticTrainer.consume_kwargs, 'disc', rest, disc, ) if consume_union: for key in ['V_min', 'V_max']: rest.pop(key, None) return BPTTWassersteinGAN.consume_kwargs( gen, disc, gen_trainer, disc_trainer, bandwidths, contrasts, include_inhibitory_neurons=include_inhibitory_neurons, rate_penalty_threshold=rate_penalty_threshold, disc_rate_penalty_bound=disc_rate_penalty_bound, **rest)
[ "lasagne.regularization.apply_penalty", "lasagne.layers.get_all_params", "numpy.random.RandomState", "itertools.count", "lasagne.layers.get_output", "numpy.array", "theano.tensor.jacobian", "theano.tensor.sgn", "theano.tensor.scalar", "theano.tensor.matrix" ]
[((2229, 2239), 'theano.tensor.matrix', 'T.matrix', ([], {}), '()\n', (2237, 2239), True, 'from theano import tensor as T\n'), ((2293, 2303), 'theano.tensor.matrix', 'T.matrix', ([], {}), '()\n', (2301, 2303), True, 'from theano import tensor as T\n'), ((2614, 2671), 'lasagne.layers.get_all_params', 'lasagne.layers.get_all_params', (['self.l_out'], {'trainable': '(True)'}), '(self.l_out, trainable=True)\n', (2643, 2671), False, 'import lasagne\n'), ((2727, 2779), 'lasagne.layers.get_output', 'lasagne.layers.get_output', (['self.l_out'], {'inputs': 'inputs'}), '(self.l_out, inputs=inputs)\n', (2752, 2779), False, 'import lasagne\n'), ((6280, 6290), 'theano.tensor.scalar', 'T.scalar', ([], {}), '()\n', (6288, 6290), True, 'from theano import tensor as T\n'), ((6314, 6324), 'theano.tensor.matrix', 'T.matrix', ([], {}), '()\n', (6322, 6324), True, 'from theano import tensor as T\n'), ((6378, 6388), 'theano.tensor.matrix', 'T.matrix', ([], {}), '()\n', (6386, 6388), True, 'from theano import tensor as T\n'), ((6442, 6452), 'theano.tensor.matrix', 'T.matrix', ([], {}), '()\n', (6450, 6452), True, 'from theano import tensor as T\n'), ((6666, 6696), 'theano.tensor.jacobian', 'T.jacobian', (['self.disc_intp', 'xp'], {}), '(self.disc_intp, xp)\n', (6676, 6696), True, 'from theano import tensor as T\n'), ((10303, 10330), 'numpy.random.RandomState', 'np.random.RandomState', (['seed'], {}), '(seed)\n', (10324, 10330), True, 'import numpy as np\n'), ((14800, 14818), 'itertools.count', 'itertools.count', (['(1)'], {}), '(1)\n', (14815, 14818), False, 'import itertools\n'), ((3114, 3122), 'theano.tensor.sgn', 'sgn', (['var'], {}), '(var)\n', (3117, 3122), False, 'from theano.tensor import sgn\n'), ((7937, 7978), 'numpy.array', 'np.array', (['p_min'], {'dtype': 'updates[var].dtype'}), '(p_min, dtype=updates[var].dtype)\n', (7945, 7978), True, 'import numpy as np\n'), ((7999, 8040), 'numpy.array', 'np.array', (['p_max'], {'dtype': 'updates[var].dtype'}), '(p_max, dtype=updates[var].dtype)\n', (8007, 8040), True, 'import numpy as np\n'), ((4372, 4443), 'lasagne.regularization.apply_penalty', 'lasagne.regularization.apply_penalty', (['params', 'lasagne.regularization.l2'], {}), '(params, lasagne.regularization.l2)\n', (4408, 4443), False, 'import lasagne\n'), ((4549, 4620), 'lasagne.regularization.apply_penalty', 'lasagne.regularization.apply_penalty', (['params', 'lasagne.regularization.l1'], {}), '(params, lasagne.regularization.l1)\n', (4585, 4620), False, 'import lasagne\n'), ((15124, 15140), 'numpy.array', 'np.array', (['probes'], {}), '(probes)\n', (15132, 15140), True, 'import numpy as np\n')]
import numpy as np import os import shutil import random from model_mask_cond import MaskNN import torch import sklearn.utils from torch.nn import functional as F vector_num = 256 cond_num = 12 rest_pitch = 129 hold_pitch = 128 cpath = "processed_data" train_path = cpath + "/vae_train_data.npy" validate_path = cpath + "/vae_validate_data.npy" test_path = cpath + "/vae_test_data.npy" total_len = 256 # 32.0 s known_len = 128 # 16.0 s shift_len = 32 # 4.0 s total_epoch = 20000 batch_size = 64 learning_rate = 1e-4 train_data = np.load(train_path,allow_pickle = True) test_data = np.load(test_path,allow_pickle = True) validate_data = np.load(validate_path,allow_pickle = True) print(train_data.shape) print(test_data.shape) print(validate_data.shape) def create_mask(data): data_x = [] data_gd = [] for x in data: temp_gd = x[0].numpy() temp_x = np.concatenate((x[0].numpy(),x[1]),axis = 1) temp_x[4:,:128] = 0 data_x.append(temp_x) data_gd.append(temp_gd) # print(data_x[0]) # print(data_gd[0]) return np.array(data_x),np.array(data_gd) train_x,train_gd = create_mask(train_data) print(train_x.shape) print(train_gd.shape) test_x,test_gd = create_mask(test_data) print(test_x.shape) print(test_gd.shape) validate_x,validate_gd = create_mask(validate_data) print(validate_x.shape) print(validate_gd.shape) # train model = MaskNN(input_dims = vector_num , hidden_dims = vector_num + 128,output_dims = 128,time_steps = total_len) optimizer = torch.optim.Adam(model.parameters(), lr = learning_rate) if torch.cuda.is_available(): print("Using:", torch.cuda.get_device_name(torch.cuda.current_device()),flush = True) model.cuda() else: print("Using CPU",flush = True) model.train() for epoch in range(total_epoch): print("epoch: %d\n_________________________________" % epoch,flush = True) train_x, train_gd = sklearn.utils.shuffle(train_x, train_gd) train_batches_x = np.split(train_x, range(batch_size, train_x.shape[0] // batch_size * batch_size, batch_size)) train_batches_gd = np.split(train_gd, range(batch_size, train_gd.shape[0] // batch_size * batch_size, batch_size)) validate_x, validate_gd = sklearn.utils.shuffle(validate_x, validate_gd) validate_batches_x = np.split(validate_x, range(batch_size, validate_x.shape[0] // batch_size * batch_size, batch_size)) validate_batches_gd = np.split(validate_gd, range(batch_size, validate_gd.shape[0] // batch_size * batch_size, batch_size)) for i in range(len(train_batches_x)): x = torch.from_numpy(train_batches_x[i]).float() gd = torch.from_numpy(train_batches_gd[i]).float() j = i % len(validate_batches_x) v_x = torch.from_numpy(validate_batches_x[j]).float() v_gd = torch.from_numpy(validate_batches_gd[j]).float() if torch.cuda.is_available(): x = x.cuda() gd = gd.cuda() v_x = v_x.cuda() v_gd = v_gd.cuda() optimizer.zero_grad() x_out = model(x) loss = F.mse_loss(x_out, gd.float()) loss.backward() optimizer.step() v_loss = 0.0 with torch.no_grad(): v_x_out = model(v_x) v_loss = F.mse_loss(v_x_out, v_gd.float()) print("batch %d loss: %.5f | val loss %.5f" % (i,loss.item(),v_loss.item()),flush = True) if (epoch + 1) % 100 == 0: torch.save(model.cpu().state_dict(), "model_v5_" + str(epoch) + ".pt") model.cuda()
[ "numpy.load", "model_mask_cond.MaskNN", "torch.cuda.is_available", "numpy.array", "torch.cuda.current_device", "torch.no_grad", "torch.from_numpy" ]
[((530, 568), 'numpy.load', 'np.load', (['train_path'], {'allow_pickle': '(True)'}), '(train_path, allow_pickle=True)\n', (537, 568), True, 'import numpy as np\n'), ((582, 619), 'numpy.load', 'np.load', (['test_path'], {'allow_pickle': '(True)'}), '(test_path, allow_pickle=True)\n', (589, 619), True, 'import numpy as np\n'), ((637, 678), 'numpy.load', 'np.load', (['validate_path'], {'allow_pickle': '(True)'}), '(validate_path, allow_pickle=True)\n', (644, 678), True, 'import numpy as np\n'), ((1390, 1492), 'model_mask_cond.MaskNN', 'MaskNN', ([], {'input_dims': 'vector_num', 'hidden_dims': '(vector_num + 128)', 'output_dims': '(128)', 'time_steps': 'total_len'}), '(input_dims=vector_num, hidden_dims=vector_num + 128, output_dims=128,\n time_steps=total_len)\n', (1396, 1492), False, 'from model_mask_cond import MaskNN\n'), ((1577, 1602), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1600, 1602), False, 'import torch\n'), ((1070, 1086), 'numpy.array', 'np.array', (['data_x'], {}), '(data_x)\n', (1078, 1086), True, 'import numpy as np\n'), ((1087, 1104), 'numpy.array', 'np.array', (['data_gd'], {}), '(data_gd)\n', (1095, 1104), True, 'import numpy as np\n'), ((2942, 2967), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2965, 2967), False, 'import torch\n'), ((1651, 1678), 'torch.cuda.current_device', 'torch.cuda.current_device', ([], {}), '()\n', (1676, 1678), False, 'import torch\n'), ((3264, 3279), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3277, 3279), False, 'import torch\n'), ((2661, 2697), 'torch.from_numpy', 'torch.from_numpy', (['train_batches_x[i]'], {}), '(train_batches_x[i])\n', (2677, 2697), False, 'import torch\n'), ((2719, 2756), 'torch.from_numpy', 'torch.from_numpy', (['train_batches_gd[i]'], {}), '(train_batches_gd[i])\n', (2735, 2756), False, 'import torch\n'), ((2819, 2858), 'torch.from_numpy', 'torch.from_numpy', (['validate_batches_x[j]'], {}), '(validate_batches_x[j])\n', (2835, 2858), False, 'import torch\n'), ((2882, 2922), 'torch.from_numpy', 'torch.from_numpy', (['validate_batches_gd[j]'], {}), '(validate_batches_gd[j])\n', (2898, 2922), False, 'import torch\n')]
import sys print(sys.path) sys.path.append('./') print(sys.path) from modeling import build_model from data.datasets.cuhk_sysu import CUHK_SYSU from data.datasets.transformer import get_transform from tools.util import ship_data_to_cuda,draw_box_in_image from torch.utils.data import DataLoader import torch from tqdm import tqdm import os import numpy as np import matplotlib.pyplot as plt def visual(model_path,cfg=None): # model=build_model.build(cfg) # checkpoint=torch.load(model_path) # model.load_state_dict(checkpoint.state_dict()) model=torch.load(model_path) model=model.cuda() model.eval() testset=CUHK_SYSU('/root/dataset', transform=get_transform(True,0.5), test_size=50, mode='test') loader = DataLoader(testset, batch_size=1, shuffle=False, collate_fn=testset.collate_fn) for i,(img,target) in enumerate(loader): img, target = ship_data_to_cuda(img, target, 'cuda') result = model(img, target) scores=result[0]['scores'].cpu() ind_over_thresh=np.where(scores>0) pre_boxes=result[0]['boxes'][ind_over_thresh] img=(img[0]*255).permute([1,2,0]).cpu().numpy().astype(int) for box in target[0]['boxes']: draw_box_in_image(img,box) for box in pre_boxes: draw_box_in_image(img,box,False) plt.imshow(img) plt.show() plt.ioff() if __name__=='__main__': visual('/root/proj/JMS_OIM/outputs/Dec 13 10:59:13 2020/ep16.pth')
[ "sys.path.append", "data.datasets.transformer.get_transform", "matplotlib.pyplot.show", "torch.utils.data.DataLoader", "matplotlib.pyplot.ioff", "matplotlib.pyplot.imshow", "torch.load", "numpy.where", "tools.util.draw_box_in_image", "tools.util.ship_data_to_cuda" ]
[((27, 48), 'sys.path.append', 'sys.path.append', (['"""./"""'], {}), "('./')\n", (42, 48), False, 'import sys\n'), ((563, 585), 'torch.load', 'torch.load', (['model_path'], {}), '(model_path)\n', (573, 585), False, 'import torch\n'), ((740, 819), 'torch.utils.data.DataLoader', 'DataLoader', (['testset'], {'batch_size': '(1)', 'shuffle': '(False)', 'collate_fn': 'testset.collate_fn'}), '(testset, batch_size=1, shuffle=False, collate_fn=testset.collate_fn)\n', (750, 819), False, 'from torch.utils.data import DataLoader\n'), ((888, 926), 'tools.util.ship_data_to_cuda', 'ship_data_to_cuda', (['img', 'target', '"""cuda"""'], {}), "(img, target, 'cuda')\n", (905, 926), False, 'from tools.util import ship_data_to_cuda, draw_box_in_image\n'), ((1028, 1048), 'numpy.where', 'np.where', (['(scores > 0)'], {}), '(scores > 0)\n', (1036, 1048), True, 'import numpy as np\n'), ((1330, 1345), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {}), '(img)\n', (1340, 1345), True, 'import matplotlib.pyplot as plt\n'), ((1354, 1364), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1362, 1364), True, 'import matplotlib.pyplot as plt\n'), ((1373, 1383), 'matplotlib.pyplot.ioff', 'plt.ioff', ([], {}), '()\n', (1381, 1383), True, 'import matplotlib.pyplot as plt\n'), ((675, 699), 'data.datasets.transformer.get_transform', 'get_transform', (['(True)', '(0.5)'], {}), '(True, 0.5)\n', (688, 699), False, 'from data.datasets.transformer import get_transform\n'), ((1220, 1247), 'tools.util.draw_box_in_image', 'draw_box_in_image', (['img', 'box'], {}), '(img, box)\n', (1237, 1247), False, 'from tools.util import ship_data_to_cuda, draw_box_in_image\n'), ((1289, 1323), 'tools.util.draw_box_in_image', 'draw_box_in_image', (['img', 'box', '(False)'], {}), '(img, box, False)\n', (1306, 1323), False, 'from tools.util import ship_data_to_cuda, draw_box_in_image\n')]
from pathlib import Path import json import sys import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader import numpy as np import matplotlib.pyplot as plt from sklearn.dummy import DummyClassifier from sklearn.metrics import accuracy_score from src import DataProcessor, Model, EarlyStopping from src import binary_accuracy, draw_det, draw_prc, draw_roc, draw_cm, compute_f1_prec_rec # # Loading arguments # if len(sys.argv) <= 1: print(""" ======= JSON config helper ======= `mode` (str): Choose ``train'', ``test'' or ``random''. `seed` (int): Random seed. `batch_size` (int): Specify the size of a batch. `epochs` (int): Maximum number of epochs to train. `hidden_dim` (int): The number of units for the first hidden layer. `drop_rate` (float) [0.0, 1.0): Specify a dropout rate. `patience` (int): Number of epochs to terminate the training process if validation loss does not improve. `loss_correction` (bool): Whether to apply class weight correction. `gpu` (bool): Whether you want to use a GPU. `gpu_number` (int): When gpu is `true`, which gpu you want to use?. `save_model` (bool): Whether you want to save weights (train mode only). `weight_name` (str): Specify a path where weights are saved (test mode only). `split_rate` (float) [0.0, 1.0): The proportion of validation set. `data_ratio` (float) (0.0, 1.0]: The proportion of training data with an even label being preserved. """) raise Exception('Please give a json file path!') args_p = Path(sys.argv[1]) if args_p.exists() is False: raise Exception('Path not found. Please check an argument again!') with args_p.open(mode='r') as f: true = True false = False null = None args = json.load(f) # # Logger # import datetime run_start_time = datetime.datetime.today().strftime('%Y-%m-%d_%H-%M-%S') import logging logfile = str('log/log-{}.txt'.format(run_start_time)) logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO, handlers=[ logging.FileHandler(logfile), logging.StreamHandler(sys.stdout) ]) logger = logging.getLogger(__name__) # # Settings # torch.manual_seed(args['seed']) if args["gpu"] is True: torch.cuda.manual_seed_all(args['seed']) if args["save_model"] is True: save_path = Path(f'./weights/{run_start_time}.pth') fig_path = Path('fig') / run_start_time if fig_path.exists(): raise Exception('Path already exists!') else: fig_path.mkdir() def train(): logger.info("***** Setup *****") logger.info(f"Configs: {args}") # make iterators data_proceessor = DataProcessor() train_data, val_data, pos_weight = data_proceessor.get_data(args['split_rate'], args['data_ratio'], args['seed']) train_iterator = DataLoader(train_data, batch_size=args["batch_size"], shuffle=True) val_iterator = DataLoader(val_data, batch_size=args["batch_size"], shuffle=True) # build a model model = Model(input_dim=28 * 28, hidden_dim=args['hidden_dim'], drop_rate=args['drop_rate']) # define an optimizer optimizer = optim.Adam(model.parameters()) if args['loss_correction'] is True: pos_weight = torch.tensor(pos_weight) criterion = nn.BCEWithLogitsLoss(pos_weight=pos_weight) else: criterion = nn.BCEWithLogitsLoss() # additional settings (e.g., early stopping) early_stopping = EarlyStopping(logger, patience=args['patience'], verbose=True) # for gpu environment if args['gpu'] is True and args['gpu_number'] is not None: torch.cuda.set_device(args['gpu_number']) device = torch.device('cuda') model = model.to(device) criterion = criterion.to(device) else: device = torch.device('cpu') model = model.to(device) criterion = criterion.to(device) logger.info(f"Number of training samples: {len(train_iterator.dataset)}") logger.info(f"Number of validation samples: {len(val_iterator.dataset)}") logger.info("***** Training *****") _history = [] for epoch in range(args['epochs']): train_loss, train_acc = train_run(model, train_iterator, optimizer, criterion, device) logger.info(f'| Epoch: {epoch+1:02} | Train Loss: {train_loss:.3f} | Train Acc: {train_acc*100:.3f}% |') val_loss, val_acc = eval_run(model, val_iterator, criterion, device) logger.info(f'| Val. Loss: {val_loss:.3f} | Val. Acc: {val_acc*100:.3f}% |') _history.append([train_loss, train_acc, val_loss, val_acc]) # early stopping early_stopping(val_loss) if early_stopping.early_stop: logger.info(f'\tEarly stopping at {epoch+1:02}') if args['save_model'] is True: save_model(model) break else: # end of the for loop if args['save_model'] is True: save_model(model) logger.info("***** Evaluation *****") # plot loss _history = np.array(_history) plt.figure() plt.plot(np.arange(len(_history)), _history[:, 0], label="train") plt.plot(np.arange(len(_history)), _history[:, 2], label='validation') plt.grid(True) plt.legend() plt.title("Training Monitoring") plt.xlabel("Epoch") plt.ylabel("Loss") plt.savefig('./fig/{}/loss.png'.format(run_start_time), bbox_inches="tight", pad_inches=0.1) # draw figures for evaluation _, _, val_auc, val_ap, val_eer, val_prec, val_rec, val_f1 = test_run(model, val_iterator, criterion, device) logger.info(f'| Val. AUC: {val_auc:.3f} | Val. AP: {val_ap:.3f} | Val. EER: {val_eer:.3f} | Val. Precision: {val_prec:.3f} | Val. Recall: {val_rec:.3f} | Val. F1: {val_f1:.3f} |') def test(): logger.info("***** Setup *****") logger.info(f"Configs: {args}") # make iterators data_proceessor = DataProcessor() test_data = data_proceessor.get_test_data(args['data_ratio']) test_iterator = DataLoader(test_data, batch_size=args["batch_size"], shuffle=True) # build a model model = Model(input_dim=28 * 28, hidden_dim=args['hidden_dim'], drop_rate=args['drop_rate']) # load weights model_dict = model.state_dict() weights_dict = torch.load(args["weight_name"]) model.load_state_dict(weights_dict) # define an optimizer optimizer = optim.Adam(model.parameters()) criterion = nn.BCEWithLogitsLoss() # for gpu environment if args['gpu'] is True and args['gpu_number'] is not None: torch.cuda.set_device(args['gpu_number']) device = torch.device('cuda') model = model.to(device) criterion = criterion.to(device) else: device = torch.device('cpu') model = model.to(device) criterion = criterion.to(device) logger.info(f"Number of testing samples: {len(test_iterator.dataset)}") logger.info("***** Testing *****") _, test_acc, test_auc, test_ap, test_eer, test_prec, test_rec, test_f1 = test_run(model, test_iterator, criterion, device) logger.info(f'| Test Accuracy: {test_acc:.3f} | Test AUC: {test_auc:.3f} | Test AP: {test_ap:.3f} | Test EER: {test_eer:.3f} | Test Precision: {test_prec:.3f} | Test Recall: {test_rec:.3f} | Test F1: {test_f1:.3f} |') def train_run(model, iterator, optimizer, criterion, device): epoch_loss = 0 epoch_acc = 0 model.train() for batch in iterator: batch = tuple(t.to(device) for t in batch) optimizer.zero_grad() output = model(batch[0]) loss = criterion(output, batch[1]) acc = binary_accuracy(output, batch[1]) loss.backward() optimizer.step() epoch_loss += loss.item() epoch_acc += acc.item() return epoch_loss / len(iterator), epoch_acc / len(iterator) def eval_run(model, iterator, criterion, device): epoch_loss = 0 epoch_acc = 0 model.eval() with torch.no_grad(): for batch in iterator: batch = tuple(t.to(device) for t in batch) predictions = model(batch[0]) loss = criterion(predictions, batch[1]) acc = binary_accuracy(predictions, batch[1]) epoch_loss += loss.item() epoch_acc += acc.item() return epoch_loss / len(iterator), epoch_acc / len(iterator) def test_run(model, iterator, criterion, device): epoch_loss = 0 epoch_acc = 0 model.eval() y_pred_list = np.array([]) y_true_list = np.array([]) with torch.no_grad(): for batch in iterator: batch = tuple(t.to(device) for t in batch) predictions = model(batch[0]) loss = criterion(predictions, batch[1]) acc = binary_accuracy(predictions, batch[1]) epoch_loss += loss.item() epoch_acc += acc.item() y_pred_list = np.append(y_pred_list, predictions.sigmoid().cpu().numpy()) y_true_list = np.append(y_true_list, batch[1].float().cpu().numpy()) draw_cm(y_pred_list, y_true_list, run_start_time) auc = draw_roc(y_pred_list, y_true_list, run_start_time) ap = draw_prc(y_pred_list, y_true_list, run_start_time) eer = draw_det(y_pred_list, y_true_list, run_start_time) f1, prec, rec = compute_f1_prec_rec(y_pred_list, y_true_list) return epoch_loss / len(iterator), epoch_acc / len(iterator), auc, ap, eer, prec, rec, f1 def random(): logger.info("***** Setup *****") logger.info(f"Configs: {args}") # make iterators data_proceessor = DataProcessor() train_data, val_data, pos_weight = data_proceessor.get_data(args['split_rate'], args['data_ratio'], args['seed']) test_data = data_proceessor.get_test_data(args['data_ratio']) train_iterator = DataLoader(train_data, batch_size=args["batch_size"], shuffle=True) val_iterator = DataLoader(val_data, batch_size=args["batch_size"], shuffle=True) test_iterator = DataLoader(test_data, batch_size=args["batch_size"], shuffle=True) logger.info(f"Number of training samples: {len(train_iterator.dataset)}") logger.info(f"Number of validation samples: {len(val_iterator.dataset)}") logger.info(f"Number of testing samples: {len(test_iterator.dataset)}") # create a naive classifier # https://scikit-learn.org/stable/modules/generated/sklearn.dummy.DummyClassifier.html y_true_list = np.array([]) with torch.no_grad(): for batch in train_iterator: y_true_list = np.append(y_true_list, batch[1].float().cpu().numpy()) model = DummyClassifier(strategy="stratified") # "most_frequent" or 'stratified' X = np.zeros_like(y_true_list).reshape(-1, 1) model.fit(X, y_true_list) logger.info("***** Testing *****") val_acc, val_auc, val_ap, val_eer, val_prec, val_rec, val_f1 = random_run(model, val_iterator) test_acc, test_auc, test_ap, test_eer, test_prec, test_rec, test_f1 = random_run(model, test_iterator) logger.info(f'| Val. Accuracy: {test_acc:.3f} | Val. AUC: {test_auc:.3f} | Val. AP: {test_ap:.3f} | Val. EER: {test_eer:.3f} | Val. Precision: {test_prec:.3f} | Val. Recall: {test_rec:.3f} | Val. F1: {test_f1:.3f} |') logger.info(f'| Test Accuracy: {test_acc:.3f} | Test AUC: {test_auc:.3f} | Test AP: {test_ap:.3f} | Test EER: {test_eer:.3f} | Test Precision: {test_prec:.3f} | Test Recall: {test_rec:.3f} | Test F1: {test_f1:.3f} |') def random_run(model, iterator): y_true_list = [] # combine data with torch.no_grad(): for batch in iterator: y_true_list = np.append(y_true_list, batch[1].float().numpy()) # predict X = np.zeros_like(y_true_list).reshape(-1, 1) preds = model.predict(X) # compute metrics acc = accuracy_score(y_true_list, (preds >= 0.5).astype(int)) draw_cm(preds, y_true_list, run_start_time) auc = draw_roc(preds, y_true_list, run_start_time) ap = draw_prc(preds, y_true_list, run_start_time) eer = draw_det(preds, y_true_list, run_start_time) f1, prec, rec = compute_f1_prec_rec(preds, y_true_list) return acc, auc, ap, eer, prec, rec, f1 def save_model(model): torch.save(model.state_dict(), save_path) def main(): if args['mode'] == 'train': train() elif args['mode'] == 'test': test() elif args['mode'] == 'random': random() else: raise NotImplementedError('Check the mode argument!') if __name__ == '__main__': main()
[ "matplotlib.pyplot.title", "pathlib.Path", "matplotlib.pyplot.figure", "torch.device", "torch.no_grad", "sklearn.dummy.DummyClassifier", "numpy.zeros_like", "logging.FileHandler", "torch.utils.data.DataLoader", "src.binary_accuracy", "torch.load", "torch.cuda.set_device", "src.Model", "src.draw_prc", "torch.nn.BCEWithLogitsLoss", "datetime.datetime.today", "torch.manual_seed", "matplotlib.pyplot.legend", "src.draw_roc", "logging.StreamHandler", "src.DataProcessor", "matplotlib.pyplot.ylabel", "src.compute_f1_prec_rec", "src.draw_det", "src.EarlyStopping", "matplotlib.pyplot.grid", "json.load", "torch.cuda.manual_seed_all", "numpy.array", "src.draw_cm", "torch.tensor", "matplotlib.pyplot.xlabel", "logging.getLogger" ]
[((1604, 1621), 'pathlib.Path', 'Path', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (1608, 1621), False, 'from pathlib import Path\n'), ((2354, 2381), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (2371, 2381), False, 'import logging\n'), ((2399, 2430), 'torch.manual_seed', 'torch.manual_seed', (["args['seed']"], {}), "(args['seed'])\n", (2416, 2430), False, 'import torch\n'), ((1817, 1829), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1826, 1829), False, 'import json\n'), ((2459, 2499), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (["args['seed']"], {}), "(args['seed'])\n", (2485, 2499), False, 'import torch\n'), ((2547, 2586), 'pathlib.Path', 'Path', (['f"""./weights/{run_start_time}.pth"""'], {}), "(f'./weights/{run_start_time}.pth')\n", (2551, 2586), False, 'from pathlib import Path\n'), ((2598, 2609), 'pathlib.Path', 'Path', (['"""fig"""'], {}), "('fig')\n", (2602, 2609), False, 'from pathlib import Path\n'), ((2856, 2871), 'src.DataProcessor', 'DataProcessor', ([], {}), '()\n', (2869, 2871), False, 'from src import DataProcessor, Model, EarlyStopping\n'), ((3011, 3078), 'torch.utils.data.DataLoader', 'DataLoader', (['train_data'], {'batch_size': "args['batch_size']", 'shuffle': '(True)'}), "(train_data, batch_size=args['batch_size'], shuffle=True)\n", (3021, 3078), False, 'from torch.utils.data import DataLoader\n'), ((3098, 3163), 'torch.utils.data.DataLoader', 'DataLoader', (['val_data'], {'batch_size': "args['batch_size']", 'shuffle': '(True)'}), "(val_data, batch_size=args['batch_size'], shuffle=True)\n", (3108, 3163), False, 'from torch.utils.data import DataLoader\n'), ((3197, 3286), 'src.Model', 'Model', ([], {'input_dim': '(28 * 28)', 'hidden_dim': "args['hidden_dim']", 'drop_rate': "args['drop_rate']"}), "(input_dim=28 * 28, hidden_dim=args['hidden_dim'], drop_rate=args[\n 'drop_rate'])\n", (3202, 3286), False, 'from src import DataProcessor, Model, EarlyStopping\n'), ((3630, 3692), 'src.EarlyStopping', 'EarlyStopping', (['logger'], {'patience': "args['patience']", 'verbose': '(True)'}), "(logger, patience=args['patience'], verbose=True)\n", (3643, 3692), False, 'from src import DataProcessor, Model, EarlyStopping\n'), ((5190, 5208), 'numpy.array', 'np.array', (['_history'], {}), '(_history)\n', (5198, 5208), True, 'import numpy as np\n'), ((5213, 5225), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (5223, 5225), True, 'import matplotlib.pyplot as plt\n'), ((5375, 5389), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (5383, 5389), True, 'import matplotlib.pyplot as plt\n'), ((5394, 5406), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (5404, 5406), True, 'import matplotlib.pyplot as plt\n'), ((5411, 5443), 'matplotlib.pyplot.title', 'plt.title', (['"""Training Monitoring"""'], {}), "('Training Monitoring')\n", (5420, 5443), True, 'import matplotlib.pyplot as plt\n'), ((5448, 5467), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epoch"""'], {}), "('Epoch')\n", (5458, 5467), True, 'import matplotlib.pyplot as plt\n'), ((5472, 5490), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Loss"""'], {}), "('Loss')\n", (5482, 5490), True, 'import matplotlib.pyplot as plt\n'), ((6052, 6067), 'src.DataProcessor', 'DataProcessor', ([], {}), '()\n', (6065, 6067), False, 'from src import DataProcessor, Model, EarlyStopping\n'), ((6154, 6220), 'torch.utils.data.DataLoader', 'DataLoader', (['test_data'], {'batch_size': "args['batch_size']", 'shuffle': '(True)'}), "(test_data, batch_size=args['batch_size'], shuffle=True)\n", (6164, 6220), False, 'from torch.utils.data import DataLoader\n'), ((6254, 6343), 'src.Model', 'Model', ([], {'input_dim': '(28 * 28)', 'hidden_dim': "args['hidden_dim']", 'drop_rate': "args['drop_rate']"}), "(input_dim=28 * 28, hidden_dim=args['hidden_dim'], drop_rate=args[\n 'drop_rate'])\n", (6259, 6343), False, 'from src import DataProcessor, Model, EarlyStopping\n'), ((6414, 6445), 'torch.load', 'torch.load', (["args['weight_name']"], {}), "(args['weight_name'])\n", (6424, 6445), False, 'import torch\n'), ((6576, 6598), 'torch.nn.BCEWithLogitsLoss', 'nn.BCEWithLogitsLoss', ([], {}), '()\n', (6596, 6598), True, 'import torch.nn as nn\n'), ((8628, 8640), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (8636, 8640), True, 'import numpy as np\n'), ((8659, 8671), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (8667, 8671), True, 'import numpy as np\n'), ((9200, 9249), 'src.draw_cm', 'draw_cm', (['y_pred_list', 'y_true_list', 'run_start_time'], {}), '(y_pred_list, y_true_list, run_start_time)\n', (9207, 9249), False, 'from src import binary_accuracy, draw_det, draw_prc, draw_roc, draw_cm, compute_f1_prec_rec\n'), ((9260, 9310), 'src.draw_roc', 'draw_roc', (['y_pred_list', 'y_true_list', 'run_start_time'], {}), '(y_pred_list, y_true_list, run_start_time)\n', (9268, 9310), False, 'from src import binary_accuracy, draw_det, draw_prc, draw_roc, draw_cm, compute_f1_prec_rec\n'), ((9320, 9370), 'src.draw_prc', 'draw_prc', (['y_pred_list', 'y_true_list', 'run_start_time'], {}), '(y_pred_list, y_true_list, run_start_time)\n', (9328, 9370), False, 'from src import binary_accuracy, draw_det, draw_prc, draw_roc, draw_cm, compute_f1_prec_rec\n'), ((9381, 9431), 'src.draw_det', 'draw_det', (['y_pred_list', 'y_true_list', 'run_start_time'], {}), '(y_pred_list, y_true_list, run_start_time)\n', (9389, 9431), False, 'from src import binary_accuracy, draw_det, draw_prc, draw_roc, draw_cm, compute_f1_prec_rec\n'), ((9452, 9497), 'src.compute_f1_prec_rec', 'compute_f1_prec_rec', (['y_pred_list', 'y_true_list'], {}), '(y_pred_list, y_true_list)\n', (9471, 9497), False, 'from src import binary_accuracy, draw_det, draw_prc, draw_roc, draw_cm, compute_f1_prec_rec\n'), ((9726, 9741), 'src.DataProcessor', 'DataProcessor', ([], {}), '()\n', (9739, 9741), False, 'from src import DataProcessor, Model, EarlyStopping\n'), ((9947, 10014), 'torch.utils.data.DataLoader', 'DataLoader', (['train_data'], {'batch_size': "args['batch_size']", 'shuffle': '(True)'}), "(train_data, batch_size=args['batch_size'], shuffle=True)\n", (9957, 10014), False, 'from torch.utils.data import DataLoader\n'), ((10034, 10099), 'torch.utils.data.DataLoader', 'DataLoader', (['val_data'], {'batch_size': "args['batch_size']", 'shuffle': '(True)'}), "(val_data, batch_size=args['batch_size'], shuffle=True)\n", (10044, 10099), False, 'from torch.utils.data import DataLoader\n'), ((10120, 10186), 'torch.utils.data.DataLoader', 'DataLoader', (['test_data'], {'batch_size': "args['batch_size']", 'shuffle': '(True)'}), "(test_data, batch_size=args['batch_size'], shuffle=True)\n", (10130, 10186), False, 'from torch.utils.data import DataLoader\n'), ((10566, 10578), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (10574, 10578), True, 'import numpy as np\n'), ((10735, 10773), 'sklearn.dummy.DummyClassifier', 'DummyClassifier', ([], {'strategy': '"""stratified"""'}), "(strategy='stratified')\n", (10750, 10773), False, 'from sklearn.dummy import DummyClassifier\n'), ((11975, 12018), 'src.draw_cm', 'draw_cm', (['preds', 'y_true_list', 'run_start_time'], {}), '(preds, y_true_list, run_start_time)\n', (11982, 12018), False, 'from src import binary_accuracy, draw_det, draw_prc, draw_roc, draw_cm, compute_f1_prec_rec\n'), ((12029, 12073), 'src.draw_roc', 'draw_roc', (['preds', 'y_true_list', 'run_start_time'], {}), '(preds, y_true_list, run_start_time)\n', (12037, 12073), False, 'from src import binary_accuracy, draw_det, draw_prc, draw_roc, draw_cm, compute_f1_prec_rec\n'), ((12083, 12127), 'src.draw_prc', 'draw_prc', (['preds', 'y_true_list', 'run_start_time'], {}), '(preds, y_true_list, run_start_time)\n', (12091, 12127), False, 'from src import binary_accuracy, draw_det, draw_prc, draw_roc, draw_cm, compute_f1_prec_rec\n'), ((12138, 12182), 'src.draw_det', 'draw_det', (['preds', 'y_true_list', 'run_start_time'], {}), '(preds, y_true_list, run_start_time)\n', (12146, 12182), False, 'from src import binary_accuracy, draw_det, draw_prc, draw_roc, draw_cm, compute_f1_prec_rec\n'), ((12203, 12242), 'src.compute_f1_prec_rec', 'compute_f1_prec_rec', (['preds', 'y_true_list'], {}), '(preds, y_true_list)\n', (12222, 12242), False, 'from src import binary_accuracy, draw_det, draw_prc, draw_roc, draw_cm, compute_f1_prec_rec\n'), ((1878, 1903), 'datetime.datetime.today', 'datetime.datetime.today', ([], {}), '()\n', (1901, 1903), False, 'import datetime\n'), ((3417, 3441), 'torch.tensor', 'torch.tensor', (['pos_weight'], {}), '(pos_weight)\n', (3429, 3441), False, 'import torch\n'), ((3462, 3505), 'torch.nn.BCEWithLogitsLoss', 'nn.BCEWithLogitsLoss', ([], {'pos_weight': 'pos_weight'}), '(pos_weight=pos_weight)\n', (3482, 3505), True, 'import torch.nn as nn\n'), ((3536, 3558), 'torch.nn.BCEWithLogitsLoss', 'nn.BCEWithLogitsLoss', ([], {}), '()\n', (3556, 3558), True, 'import torch.nn as nn\n'), ((3791, 3832), 'torch.cuda.set_device', 'torch.cuda.set_device', (["args['gpu_number']"], {}), "(args['gpu_number'])\n", (3812, 3832), False, 'import torch\n'), ((3850, 3870), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (3862, 3870), False, 'import torch\n'), ((3972, 3991), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (3984, 3991), False, 'import torch\n'), ((6697, 6738), 'torch.cuda.set_device', 'torch.cuda.set_device', (["args['gpu_number']"], {}), "(args['gpu_number'])\n", (6718, 6738), False, 'import torch\n'), ((6756, 6776), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (6768, 6776), False, 'import torch\n'), ((6878, 6897), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (6890, 6897), False, 'import torch\n'), ((7762, 7795), 'src.binary_accuracy', 'binary_accuracy', (['output', 'batch[1]'], {}), '(output, batch[1])\n', (7777, 7795), False, 'from src import binary_accuracy, draw_det, draw_prc, draw_roc, draw_cm, compute_f1_prec_rec\n'), ((8097, 8112), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (8110, 8112), False, 'import torch\n'), ((8682, 8697), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (8695, 8697), False, 'import torch\n'), ((10588, 10603), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (10601, 10603), False, 'import torch\n'), ((11665, 11680), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (11678, 11680), False, 'import torch\n'), ((2234, 2262), 'logging.FileHandler', 'logging.FileHandler', (['logfile'], {}), '(logfile)\n', (2253, 2262), False, 'import logging\n'), ((2288, 2321), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (2309, 2321), False, 'import logging\n'), ((8312, 8350), 'src.binary_accuracy', 'binary_accuracy', (['predictions', 'batch[1]'], {}), '(predictions, batch[1])\n', (8327, 8350), False, 'from src import binary_accuracy, draw_det, draw_prc, draw_roc, draw_cm, compute_f1_prec_rec\n'), ((8897, 8935), 'src.binary_accuracy', 'binary_accuracy', (['predictions', 'batch[1]'], {}), '(predictions, batch[1])\n', (8912, 8935), False, 'from src import binary_accuracy, draw_det, draw_prc, draw_roc, draw_cm, compute_f1_prec_rec\n'), ((10816, 10842), 'numpy.zeros_like', 'np.zeros_like', (['y_true_list'], {}), '(y_true_list)\n', (10829, 10842), True, 'import numpy as np\n'), ((11811, 11837), 'numpy.zeros_like', 'np.zeros_like', (['y_true_list'], {}), '(y_true_list)\n', (11824, 11837), True, 'import numpy as np\n')]
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import paddle.fluid.framework as framework from paddle.fluid.optimizer import Optimizer import paddle.fluid.core as core import numpy as np registerd_op = { "elementwise_add": "AddParser", "matmul": "MatMulParser", "mul": "MulParser", "relu": "ReluParser", "softmax_with_cross_entropy": "SoftmaxWithCrossEntropyParser", "shape": "ShapeParser", "fill_constant": "FillConstantParser", "reduce_sum": "ReduceSumParser", "reduce_sum_grad": "ReduceSumGradParser", "matmul_grad": "MatMulGradParser", "mul_grad": "MulGradParser", "reshape2": "ReshapeParser", "scale": "ScaleParser", "relu_grad": "ReluGradParser", "softmax_with_cross_entropy_grad": "SoftmaxWithCrossEntropyGradParser", "truncated_gaussian_random": "TruncatedNormalParser", "sgd": "SGDParser" } global_cnt = -1 global_input_cnt = -1 class AscendHelper(object): def __init__(self): self.dtype2ge_map = { 0: core.GEDataType.DT_BOOL, 1: core.GEDataType.DT_INT16, 2: core.GEDataType.DT_INT32, 3: core.GEDataType.DT_INT64, 4: core.GEDataType.DT_FLOAT16, 5: core.GEDataType.DT_FLOAT, 6: core.GEDataType.DT_DOUBLE } self.dtype2np_map = { 0: "bool", 1: "int16", 2: "int32", 3: "int64", 4: "float16", 5: "float32", 6: "float64" } def dtype2ge(self, dtype): assert dtype in self.dtype2ge_map, "dtype[%d] is not supported %d" % ( dtype) return self.dtype2ge_map[dtype] def dtype2np(self, index): assert index in self.dtype2np_map, "index[%d] is not supported %d" % ( dtype) return self.dtype2np_map[index] class AscendParserFactory(object): def __init__(self, graph, var2geop): self.graph = graph self.var2geop = var2geop def create_parse(self, parser_class): try: parser = globals()[parser_class](self.graph, self.var2geop) return parser except: raise ValueError("parser class %s does not exist" % parser_class) class AscendParserBase(object): def __init__(self, graph, var2geop): self.graph = graph self.var2geop = var2geop self.op = None self.ascend_helper = AscendHelper() def _get_ge_input(self, input_var_name): assert input_var_name in self.var2geop, "var %s not created before" % ( input_var_name) return self.var2geop[input_var_name] def update_output(self, geop_list, index_list): output_num = len(self.op.output_names) assert output_num == len( index_list ), "Parser[%s]'s output number[%d] is not equal to parameters number[%d]" % ( self.parser_name, len(index_list), output_num) for output_id in range(output_num): arguments = self.op.output(self.op.output_names[output_id]) print("%d argument: %s" % (output_id, str(arguments))) if len(arguments) > 0: assert len(arguments) == len( index_list[output_id] ), "Parser[%s]'s %dth argument number[%d] is not equal to paddle's number[%d]" % ( self.parser_name, output_id, len(index_list[output_id]), len(arguments)) for i in range(len(arguments)): print("assgin index_list[%d][%d] to %s" % (output_id, i, arguments[i])) self.var2geop[arguments[i]] = geop_list[index_list[ output_id][i]] for geop in geop_list: self.graph.add_op(geop) def apply(self, op): self.op = op assert self.op.type == self.parser_name, "op [%s] != parser_name[%s]" % ( self.op.type, self.parser_name) print("begin to parse op %s" % (self.parser_name)) geop_list, index_list = self._apply() self.update_output(geop_list, index_list) def _mark_as_input(self, ge_tensor): global global_input_cnt global_input_cnt += 1 self.var2geop["geinput." + str(global_input_cnt)] = ge_tensor def _accumulated_op_id(self): global global_cnt global_cnt += 1 return "." + str(global_cnt) def _create_ge_tensor(self, shape, dtype, value): tensor_desc = core.GETensorDesc( core.GEShape(shape), core.GEFormat.FORMAT_ND, self.ascend_helper.dtype2ge(dtype)) tensor = core.GETensor(tensor_desc) data = (value * np.ones(( shape))).reshape(shape).astype(self.ascend_helper.dtype2np(dtype)) buf = data.tobytes() data_8 = np.frombuffer(buf, dtype=np.uint8) tensor.set_data(data_8) return tensor class AddParser(AscendParserBase): def __init__(self, graph, var2geop): super(AddParser, self).__init__(graph, var2geop) self.parser_name = "elementwise_add" def _apply(self): x = self._get_ge_input(self.op.input_arg_names[0]) y = self._get_ge_input(self.op.input_arg_names[1]) add = core.GEOperatorFactory.create_operator( "add" + self._accumulated_op_id(), "Add").set_input( "x1", x).set_input("x2", y) return [add], [[0]] class ReduceSumParser(AscendParserBase): def __init__(self, graph, var2geop): super(ReduceSumParser, self).__init__(graph, var2geop) self.parser_name = "reduce_sum" def _apply(self): x = self._get_ge_input(self.op.input_arg_names[0]) axes = self.op.attr("dim") keep_dims = self.op.attr("keep_dim") reduce_sum = core.GEOperatorFactory.create_operator( "reduce_sum" + self._accumulated_op_id(), "ReduceSumD").set_input( "x", x, 0).set_attr_vec_int32("axes", axes).set_attr_bool( "keep_dims", keep_dims) return [reduce_sum], [[0]] class ReduceSumGradParser(AscendParserBase): def __init__(self, graph, var2geop): super(ReduceSumGradParser, self).__init__(graph, var2geop) self.parser_name = "reduce_sum_grad" def _apply(self): x = self._get_ge_input(self.op.input_arg_names[0]) input = self._get_ge_input(self.op.input_arg_names[1]) shape_tensor = core.GEOperatorFactory.create_operator( "shape" + self._accumulated_op_id(), "Shape").set_input("x", input, 0) axis_const = core.GEOperatorFactory.create_operator( "const" + self._accumulated_op_id(), "Const").set_attr_tensor( "value", self._create_ge_tensor([1], 2, -1)) self._mark_as_input(axis_const) broadcast = core.GEOperatorFactory.create_operator( "broadcast_to_d" + self._accumulated_op_id(), "BroadcastTo").set_input("x", x).set_input("shape", shape_tensor) # unsqueeze cannot get right result, but ExpandDims seems have the same functionality. reduce_sum_grad = core.GEOperatorFactory.create_operator( "expand" + self._accumulated_op_id(), "ExpandDims").set_input( "x", broadcast).set_input("axis", axis_const) return [shape_tensor, axis_const, broadcast, reduce_sum_grad], [[3]] class MatMulParser(AscendParserBase): def __init__(self, graph, var2geop): super(MatMulParser, self).__init__(graph, var2geop) self.parser_name = "matmul" def _apply(self): x1 = self._get_ge_input(self.op.input_arg_names[0]) x2 = self._get_ge_input(self.op.input_arg_names[1]) matmul = core.GEOperatorFactory.create_operator( "matmul" + self._accumulated_op_id(), "MatMul").set_input( "x1", x1).set_input("x2", x2) return [matmul], [[0]] class MatMulGradParser(AscendParserBase): def __init__(self, graph, var2geop): super(MatMulGradParser, self).__init__(graph, var2geop) self.parser_name = "matmul_grad" def _apply(self): out_grad = self._get_ge_input(self.op.input_arg_names[0]) x = self._get_ge_input(self.op.input_arg_names[1]) y = self._get_ge_input(self.op.input_arg_names[2]) x_grad = core.GEOperatorFactory.create_operator( self.parser_name + self._accumulated_op_id(), "MatMul").set_input( "x1", out_grad).set_input("x2", y).set_attr_bool( "transpose_x1", False).set_attr_bool("transpose_x2", True) y_grad = core.GEOperatorFactory.create_operator( self.parser_name + self._accumulated_op_id(), "MatMul").set_input( "x1", x).set_input("x2", out_grad).set_attr_bool( "transpose_x1", True).set_attr_bool("transpose_x2", False) return [x_grad, y_grad], [[0], [1]] class MulGradParser(AscendParserBase): def __init__(self, graph, var2geop): super(MulGradParser, self).__init__(graph, var2geop) self.parser_name = "mul_grad" def _apply(self): out_grad = self._get_ge_input(self.op.input_arg_names[0]) x = self._get_ge_input(self.op.input_arg_names[1]) y = self._get_ge_input(self.op.input_arg_names[2]) x_grad = core.GEOperatorFactory.create_operator( self.parser_name + self._accumulated_op_id(), "MatMul").set_input( "x1", out_grad).set_input("x2", y).set_attr_bool( "transpose_x1", False).set_attr_bool("transpose_x2", True) y_grad = core.GEOperatorFactory.create_operator( self.parser_name + self._accumulated_op_id(), "MatMul").set_input( "x1", x).set_input("x2", out_grad).set_attr_bool( "transpose_x1", True).set_attr_bool("transpose_x2", False) return [x_grad, y_grad], [[0], [1]] class MulParser(AscendParserBase): def __init__(self, graph, var2geop): super(MulParser, self).__init__(graph, var2geop) self.parser_name = "mul" def _apply(self): x = self._get_ge_input(self.op.input_arg_names[0]) y = self._get_ge_input(self.op.input_arg_names[1]) matmul = core.GEOperatorFactory.create_operator( "mul" + self._accumulated_op_id(), "MatMul").set_input( "x1", x).set_input("x2", y) return [matmul], [[0]] class ReluParser(AscendParserBase): def __init__(self, graph, var2geop): super(ReluParser, self).__init__(graph, var2geop) self.parser_name = "relu" def _apply(self): x = self._get_ge_input(self.op.input_arg_names[0]) relu = core.GEOperatorFactory.create_operator( "relu" + self._accumulated_op_id(), "Relu").set_input("x", x) return [relu], [[0]] class ReluGradParser(AscendParserBase): def __init__(self, graph, var2geop): super(ReluGradParser, self).__init__(graph, var2geop) self.parser_name = "relu_grad" def _apply(self): out = self._get_ge_input(self.op.input_arg_names[0]) out_grad = self._get_ge_input(self.op.input_arg_names[1]) relu_grad = core.GEOperatorFactory.create_operator( self.parser_name + self._accumulated_op_id(), "ReluGrad").set_input( "gradients", out_grad).set_input("features", out) return [relu_grad], [[0]] class SoftmaxWithCrossEntropyParser(AscendParserBase): def __init__(self, graph, var2geop): super(SoftmaxWithCrossEntropyParser, self).__init__(graph, var2geop) self.parser_name = "softmax_with_cross_entropy" def _apply(self): label = self._get_ge_input(self.op.input_arg_names[0]) logits = self._get_ge_input(self.op.input_arg_names[1]) cls_num = self.op.block.var(self.op.input_arg_names[1]).shape[1] softmax = core.GEOperatorFactory.create_operator( "softmax" + self._accumulated_op_id(), "SoftmaxV2").set_input( "x", logits) label = core.GEOperatorFactory.create_operator( "cast" + self._accumulated_op_id(), "Cast").set_input( "x", label).set_attr_int32("dst_type", 3) tensoron = self._create_ge_tensor([1], 5, 1) on_const = core.GEOperatorFactory.create_operator( "const" + self._accumulated_op_id(), "Const").set_attr_tensor( "value", tensoron) self._mark_as_input(on_const) tensoroff = self._create_ge_tensor([1], 5, 0) off_const = core.GEOperatorFactory.create_operator( "const" + self._accumulated_op_id(), "Const").set_attr_tensor( "value", tensoroff) self._mark_as_input(off_const) onehot = core.GEOperatorFactory.create_operator( "onehot" + self._accumulated_op_id(), "OneHotD").set_input( "x", label).set_input("on_value", on_const).set_input( "off_value", off_const).set_attr_int32("depth", cls_num) squeeze = core.GEOperatorFactory.create_operator( "mul" + self._accumulated_op_id(), "Squeeze").set_input("x", onehot) loss = core.GEOperatorFactory.create_operator( "loss" + self._accumulated_op_id(), "SoftmaxCrossEntropyWithLogits").set_input( "features", logits).set_input("labels", squeeze) return [label, softmax, on_const, off_const, onehot, squeeze, loss], [[6], [1]] class SoftmaxWithCrossEntropyGradParser(AscendParserBase): def __init__(self, graph, var2geop): super(SoftmaxWithCrossEntropyGradParser, self).__init__(graph, var2geop) self.parser_name = "softmax_with_cross_entropy_grad" def _apply(self): label = self._get_ge_input(self.op.input_arg_names[0]) loss_grad = self._get_ge_input(self.op.input_arg_names[1]) softmax = self._get_ge_input(self.op.input_arg_names[2]) cls_num = self.op.block.var(self.op.input_arg_names[2]).shape[1] tensoron = self._create_ge_tensor([1], 5, 1) on_const = core.GEOperatorFactory.create_operator( "const" + self._accumulated_op_id(), "Const").set_attr_tensor( "value", tensoron) self._mark_as_input(on_const) tensoroff = self._create_ge_tensor([1], 5, 0) off_const = core.GEOperatorFactory.create_operator( "const" + self._accumulated_op_id(), "Const").set_attr_tensor( "value", tensoroff) self._mark_as_input(off_const) label = core.GEOperatorFactory.create_operator( "cast" + self._accumulated_op_id(), "Cast").set_input( "x", label).set_attr_int32("dst_type", 3) onehot = core.GEOperatorFactory.create_operator( "onehot" + self._accumulated_op_id(), "OneHotD").set_input( "x", label).set_input("on_value", on_const).set_input( "off_value", off_const).set_attr_int32("depth", cls_num) # the fuck onehot will add a demension, so must call squeeze afterward squeeze = core.GEOperatorFactory.create_operator( "mul" + self._accumulated_op_id(), "Squeeze").set_input("x", onehot) sub = core.GEOperatorFactory.create_operator( "sub" + self._accumulated_op_id(), "Sub").set_input( "x1", softmax).set_input("x2", squeeze) grad = core.GEOperatorFactory.create_operator( "mul" + self._accumulated_op_id(), "Mul").set_input( "x1", loss_grad).set_input("x2", sub) return [on_const, off_const, label, onehot, squeeze, sub, grad], [[-1]] class ShapeParser(AscendParserBase): def __init__(self, graph, var2geop): super(ShapeParser, self).__init__(graph, var2geop) self.parser_name = "shape" def _apply(self): x = self._get_ge_input(self.op.input_arg_names[0]) shape = core.GEOperatorFactory.create_operator( "shape" + self._accumulated_op_id(), "Shape").set_input("x", x) return [shape], [[0]] class FillConstantParser(AscendParserBase): def __init__(self, graph, var2geop): super(FillConstantParser, self).__init__(graph, var2geop) self.parser_name = "fill_constant" def _apply(self): shape = self.op.attr("shape") dtype = self.op.attr("dtype") value = self.op.attr("value") print("shape: ", shape) print("dtype: ", dtype) print("value: ", value) tensor = self._create_ge_tensor(shape, dtype, value) const = core.GEOperatorFactory.create_operator( "const" + self._accumulated_op_id(), "Const").set_attr_tensor( "value", tensor) self._mark_as_input(const) if self.op.block.var(self.op.output('Out')[0]).persistable: print("%s fill_constant" % (self.op.output('Out')[0])) var = core.GEOperatorFactory.create_operator( self.op.output('Out')[0], "Variable") var.update_output_desc("y", core.GETensorDesc( core.GEShape(shape), core.GEFormat.FORMAT_ND, core.GEDataType.DT_FLOAT)) assign = core.GEOperatorFactory.create_operator( "assign" + self._accumulated_op_id(), "Assign").set_input( "value", const).set_input("ref", var) return [const], [[0]] else: print( "self.op.output('Out')[0] is not persistable in fill_constant") return [const], [[0]] class SGDParser(AscendParserBase): def __init__(self, graph, var2geop): super(SGDParser, self).__init__(graph, var2geop) self.parser_name = "sgd" def _apply(self): grad = self._get_ge_input(self.op.input_arg_names[0]) lr = self._get_ge_input(self.op.input_arg_names[1]) param = self._get_ge_input(self.op.input_arg_names[2]) sgd = core.GEOperatorFactory.create_operator( "momentum" + self._accumulated_op_id(), "ApplyGradientDescent").set_input("var", param).set_input( "alpha", lr).set_input("delta", grad) return [sgd], [[0]] class TruncatedNormalParser(AscendParserBase): def __init__(self, graph, var2geop): super(TruncatedNormalParser, self).__init__(graph, var2geop) self.parser_name = "truncated_gaussian_random" def _apply(self): shape = self.op.attr("shape") dtype = self.op.attr("dtype") mean = self.op.attr("mean") std = self.op.attr("std") seed = self.op.attr("seed") tensor1 = self._create_ge_tensor([len(shape)], 2, shape) shape_tensor = core.GEOperatorFactory.create_operator( "const" + self._accumulated_op_id(), "Const").set_attr_tensor( "value", tensor1) tensor2 = self._create_ge_tensor([1], dtype, mean) mean_tensor = core.GEOperatorFactory.create_operator( "const" + self._accumulated_op_id(), "Const").set_attr_tensor( "value", tensor2) tensor3 = self._create_ge_tensor([1], dtype, std) std_tensor = core.GEOperatorFactory.create_operator( "const" + self._accumulated_op_id(), "Const").set_attr_tensor( "value", tensor3) tensor4 = self._create_ge_tensor([1], dtype, mean - 2 * std) min_tensor = core.GEOperatorFactory.create_operator( "const" + self._accumulated_op_id(), "Const").set_attr_tensor( "value", tensor4) tensor5 = self._create_ge_tensor([1], dtype, mean + 2 * std) max_tensor = core.GEOperatorFactory.create_operator( "const" + self._accumulated_op_id(), "Const").set_attr_tensor( "value", tensor5) self._mark_as_input(shape_tensor) self._mark_as_input(mean_tensor) self._mark_as_input(std_tensor) self._mark_as_input(min_tensor) self._mark_as_input(max_tensor) truncated_normal = core.GEOperatorFactory.create_operator( "truncated_normal" + self._accumulated_op_id(), "ParameterizedTruncatedNormal").set_input( "shape", shape_tensor).set_input( "means", mean_tensor).set_input( "stdevs", std_tensor).set_input( "min", min_tensor).set_input( "max", max_tensor).set_attr_int32("seed", 0) ## wirte the output of truncatedNormal from startup_program to main_program if self.op.block.var(self.op.output('Out')[0]).persistable: print("%s is Persistable in truncated_normal" % (self.op.output('Out')[0])) #var = core.GEOperatorFactory.create_operator(self.op.output('Out')[0], "Variable").set_input("x", truncated_normal) var = core.GEOperatorFactory.create_operator( self.op.output('Out')[0], "Variable") var.update_output_desc("y", core.GETensorDesc( core.GEShape(shape), core.GEFormat.FORMAT_ND, core.GEDataType.DT_FLOAT)) assign = core.GEOperatorFactory.create_operator( "assign" + self._accumulated_op_id(), "Assign").set_input( "value", truncated_normal).set_input("ref", var) return [ shape_tensor, mean_tensor, std_tensor, min_tensor, max_tensor, truncated_normal ], [[-1]] else: print( "self.op.output('Out')[0] is not persistable in truncated_noraml" ) return [truncated_normal], [[0]] #[assign] class ScaleParser(AscendParserBase): def __init__(self, graph, var2geop): super(ScaleParser, self).__init__(graph, var2geop) self.parser_name = "scale" def _apply(self): x = self._get_ge_input(self.op.input_arg_names[0]) scale = self.op.attr( "scale") #self.get_ge_input(self.op.input_arg_names[1]) bias = self.op.attr("bias") bias_after_scale = self.op.attr("bias_after_scale") if bias_after_scale: scale_value = core.GEOperatorFactory.create_operator( "scale" + self._accumulated_op_id(), "Power").set_input( "x", x).set_attr_float("power", 1.0).set_attr_float( "scale", scale).set_attr_float("shift", bias) else: x_add_bias = core.GEOperatorFactory.create_operator( "adds" + self._accumulated_op_id(), "Adds").set_input( "x", x).set_attr_float("value", bias) #set_input("x2", bias) scale_value = core.GEOperatorFactory.create_operator( "scale" + self._accumulated_op_id(), "Power").set_input( "x", x_add_bias).set_attr_float( "power", 1.0).set_attr_float( "scale", scale).set_attr_float("shift", 0.0) #tensor_zeros = core.GEOperatorFactory.create_operator("zeroslike" + self.getid(), "ZerosLike").set_input("x", x) #bias_ = self.create_ge_tensor([1], 5, bias) #const_bias = core.GEOperatorFactory.create_operator("const" + self.getid(), "Const").set_attr_tensor("value", tensor_bias) return [scale_value], [[0]] class ReshapeParser(AscendParserBase): def __init__(self, graph, var2geop): super(ReshapeParser, self).__init__(graph, var2geop) self.parser_name = "reshape2" def _apply(self): print("swbuf:", self.op.input_arg_names) shape = self.op.attr("shape") axis = 0 if shape[0] == -1: axis = 1 shape = shape[1:] print("shape: ", shape) data_x1_shape = self._get_ge_input(self.op.input_arg_names[0]) tensor = self._create_ge_tensor([len(shape)], 2, shape) const_shape = core.GEOperatorFactory.create_operator( "shape" + self._accumulated_op_id(), "Const").set_attr_tensor( "value", tensor) reshape = core.GEOperatorFactory.create_operator( "reshape" + self._accumulated_op_id(), "Reshape").set_input( "x", data_x1_shape).set_input( "shape", const_shape).set_attr_int32("axis", axis) return [reshape, reshape], [[0], [1]]
[ "numpy.frombuffer", "paddle.fluid.core.GETensor", "paddle.fluid.core.GEShape", "numpy.ones" ]
[((5204, 5230), 'paddle.fluid.core.GETensor', 'core.GETensor', (['tensor_desc'], {}), '(tensor_desc)\n', (5217, 5230), True, 'import paddle.fluid.core as core\n'), ((5391, 5425), 'numpy.frombuffer', 'np.frombuffer', (['buf'], {'dtype': 'np.uint8'}), '(buf, dtype=np.uint8)\n', (5404, 5425), True, 'import numpy as np\n'), ((5093, 5112), 'paddle.fluid.core.GEShape', 'core.GEShape', (['shape'], {}), '(shape)\n', (5105, 5112), True, 'import paddle.fluid.core as core\n'), ((17745, 17764), 'paddle.fluid.core.GEShape', 'core.GEShape', (['shape'], {}), '(shape)\n', (17757, 17764), True, 'import paddle.fluid.core as core\n'), ((21817, 21836), 'paddle.fluid.core.GEShape', 'core.GEShape', (['shape'], {}), '(shape)\n', (21829, 21836), True, 'import paddle.fluid.core as core\n'), ((5256, 5270), 'numpy.ones', 'np.ones', (['shape'], {}), '(shape)\n', (5263, 5270), True, 'import numpy as np\n')]
""" A class that is responsible for detecting a barcode and extracting information from said barcode. """ import numpy as np import cv2 import zbar.misc __author__ = "<NAME>" __copyright__ = "Copyright 2017, Java the Hutts" __license__ = "BSD" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Development" # The minimum area a rectangle must be to be considered a barcode. BOUNDING_RECTANGLE_THRESHOLD = 200 class BarCodeManager: """ The BarCode Manager is responsible for: 1. Detecting the barcode. 2. Extracting any information on the detected barcode. 3. Applying blurring to the detected barcode to reduce noise. """ def __init__(self): self.scanner = zbar.Scanner() def detect(self, image): """ This function detects a region containing a barcode if a barcode is present in the image passed. Barcodes supported: - EAN - UPC - Code 39 - Code 93 - Code 128 - ITF For more information on Barcode types: https://www.scandit.com/types-barcodes-choosing-right-barcode/. :param image (obj): Image containing the potential barcode. Returns: - (boolean): Indicates whether a barcode was detected or not. - (obj): Return the detected barcode or the original image, based on whether the barcode was found. - (int list): This list contains the box coordinates for the region in which the barcode resides. Raises: - TypeError: If a none numpy array value has been passed. """ if type(image) is not np.ndarray: raise TypeError( 'Bad type for arg image - expected image in numpy array. Received type "%s".' % type(image).__name__ ) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) grad_x = cv2.Sobel(gray, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=-1) grad_y = cv2.Sobel(gray, ddepth=cv2.CV_32F, dx=0, dy=1, ksize=-1) gradient = cv2.subtract(grad_x, grad_y) gradient = cv2.convertScaleAbs(gradient) blurred = cv2.blur(gradient, (7, 7)) (_, thresh) = cv2.threshold(blurred, 225, 255, cv2.THRESH_BINARY) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (27, 7)) closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel) eroded = cv2.erode(closed, None, iterations=4) dilated = cv2.dilate(eroded, None, iterations=4) (_, contours, _) = cv2.findContours(dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) c = sorted(contours, key=cv2.contourArea, reverse=True)[0] rectangle = cv2.minAreaRect(c) box = cv2.boxPoints(rectangle) box = np.int0(box) (x, y, w, h) = cv2.boundingRect(box) # The Difference between the upper and lower Y-value is calculated to ensure a Barcode is detected. # This reduces the chance of a false positive detection. diff = y - (y+h) if abs(diff) < BOUNDING_RECTANGLE_THRESHOLD: return True, image[y:y + h, x:x + w], box else: return False, image, box def get_barcode_info(self, image): """ This function returns scanned barcode information. :param image (obj): Image containing a Barcode. Returns: - (boolean): Whether the function was able to extract information from the barcode. - (str): A UTF-8 String of the data extracted from the barcode (empty if nothing was extracted). - (obj): A copy of the original image. """ (detection, detected_image, box) = self.detect(image.copy()) if detection: gray = cv2.cvtColor(detected_image, cv2.COLOR_BGR2GRAY) results = self.scanner.scan(gray) if not results: return False, "", image else: image = self.apply_barcode_blur(image, box) return True, results[0].data, image else: return False, "", image def apply_barcode_blur(self, image, box, dilation_intensity=2): """ This function applies blurring to a detected barcode region to reduce noise in the image. The barcode region is first extracted, then blurring is applied, after blurring is applied the blurred out barcode is reapplied to the original image. :param image (obj): Image containing a Barcode. :param box (int list): The box is an integer list containing the box region coordinates of the barcode location. :param dilation_intensity (int): Indicates the intensity by which the barcode should be dilated. The greater the intensity the greater the extent of dilation. Returns: (obj): The original image with blurring applied to the barcode region in the image. """ (x, y, w, h) = cv2.boundingRect(box) sub_bar_code = image[y:y + h, x:x + w] sub_bar_code = cv2.dilate(sub_bar_code, None, iterations=dilation_intensity) sub_bar_code = cv2.GaussianBlur(sub_bar_code, (31, 31), 0) image[y:y + sub_bar_code.shape[0], x:x + sub_bar_code.shape[1]] = sub_bar_code return image
[ "cv2.GaussianBlur", "cv2.subtract", "numpy.int0", "cv2.dilate", "cv2.cvtColor", "cv2.getStructuringElement", "cv2.threshold", "cv2.morphologyEx", "cv2.blur", "cv2.boxPoints", "cv2.convertScaleAbs", "cv2.minAreaRect", "cv2.erode", "cv2.boundingRect", "cv2.Sobel" ]
[((1854, 1893), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2GRAY'], {}), '(image, cv2.COLOR_BGR2GRAY)\n', (1866, 1893), False, 'import cv2\n'), ((1912, 1968), 'cv2.Sobel', 'cv2.Sobel', (['gray'], {'ddepth': 'cv2.CV_32F', 'dx': '(1)', 'dy': '(0)', 'ksize': '(-1)'}), '(gray, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=-1)\n', (1921, 1968), False, 'import cv2\n'), ((1986, 2042), 'cv2.Sobel', 'cv2.Sobel', (['gray'], {'ddepth': 'cv2.CV_32F', 'dx': '(0)', 'dy': '(1)', 'ksize': '(-1)'}), '(gray, ddepth=cv2.CV_32F, dx=0, dy=1, ksize=-1)\n', (1995, 2042), False, 'import cv2\n'), ((2063, 2091), 'cv2.subtract', 'cv2.subtract', (['grad_x', 'grad_y'], {}), '(grad_x, grad_y)\n', (2075, 2091), False, 'import cv2\n'), ((2111, 2140), 'cv2.convertScaleAbs', 'cv2.convertScaleAbs', (['gradient'], {}), '(gradient)\n', (2130, 2140), False, 'import cv2\n'), ((2160, 2186), 'cv2.blur', 'cv2.blur', (['gradient', '(7, 7)'], {}), '(gradient, (7, 7))\n', (2168, 2186), False, 'import cv2\n'), ((2209, 2260), 'cv2.threshold', 'cv2.threshold', (['blurred', '(225)', '(255)', 'cv2.THRESH_BINARY'], {}), '(blurred, 225, 255, cv2.THRESH_BINARY)\n', (2222, 2260), False, 'import cv2\n'), ((2278, 2328), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_RECT', '(27, 7)'], {}), '(cv2.MORPH_RECT, (27, 7))\n', (2303, 2328), False, 'import cv2\n'), ((2346, 2395), 'cv2.morphologyEx', 'cv2.morphologyEx', (['thresh', 'cv2.MORPH_CLOSE', 'kernel'], {}), '(thresh, cv2.MORPH_CLOSE, kernel)\n', (2362, 2395), False, 'import cv2\n'), ((2414, 2451), 'cv2.erode', 'cv2.erode', (['closed', 'None'], {'iterations': '(4)'}), '(closed, None, iterations=4)\n', (2423, 2451), False, 'import cv2\n'), ((2470, 2508), 'cv2.dilate', 'cv2.dilate', (['eroded', 'None'], {'iterations': '(4)'}), '(eroded, None, iterations=4)\n', (2480, 2508), False, 'import cv2\n'), ((2746, 2764), 'cv2.minAreaRect', 'cv2.minAreaRect', (['c'], {}), '(c)\n', (2761, 2764), False, 'import cv2\n'), ((2779, 2803), 'cv2.boxPoints', 'cv2.boxPoints', (['rectangle'], {}), '(rectangle)\n', (2792, 2803), False, 'import cv2\n'), ((2818, 2830), 'numpy.int0', 'np.int0', (['box'], {}), '(box)\n', (2825, 2830), True, 'import numpy as np\n'), ((2854, 2875), 'cv2.boundingRect', 'cv2.boundingRect', (['box'], {}), '(box)\n', (2870, 2875), False, 'import cv2\n'), ((5014, 5035), 'cv2.boundingRect', 'cv2.boundingRect', (['box'], {}), '(box)\n', (5030, 5035), False, 'import cv2\n'), ((5106, 5167), 'cv2.dilate', 'cv2.dilate', (['sub_bar_code', 'None'], {'iterations': 'dilation_intensity'}), '(sub_bar_code, None, iterations=dilation_intensity)\n', (5116, 5167), False, 'import cv2\n'), ((5191, 5234), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['sub_bar_code', '(31, 31)', '(0)'], {}), '(sub_bar_code, (31, 31), 0)\n', (5207, 5234), False, 'import cv2\n'), ((3797, 3845), 'cv2.cvtColor', 'cv2.cvtColor', (['detected_image', 'cv2.COLOR_BGR2GRAY'], {}), '(detected_image, cv2.COLOR_BGR2GRAY)\n', (3809, 3845), False, 'import cv2\n')]
# -*- coding: utf-8 -*- """nnetwork.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1pMeLa_X6bXVDBF07Nf5ISyPfmGEpurvH """ import pandas as pd import numpy as np # first neural network with keras tutorial from numpy import loadtxt from sklearn.model_selection import train_test_split from keras.models import Sequential from keras.layers import Dense import matplotlib.pyplot as plt import tensorflow as tf device_name = tf.test.gpu_device_name() if device_name != '/device:GPU:0': raise SystemError('GPU device not found') print('Found GPU at: {}'.format(device_name)) #data= pd.read_csv('/content/drive/MyDrive/Expert-Opinion.csv') data = pd.read_csv('/content/drive/MyDrive/data_1000.csv',nrows = 1000) #data = pd.read_csv('/content/drive/MyDrive/Expert_opinion_1000.csv') dataset = data.drop(['Title'], axis=1) data #data = loadtxt('/content/drive/MyDrive/Expert-Opinion.csv',delimiter=',') #Expert Opinion on Recipies dataset.head(5) import seaborn as sns dataset['remarks'].value_counts().plot(kind='bar') #input and output variables X = dataset.iloc[:,0:6] Y = dataset.iloc[:,6] X lst = list(dataset['energy']) lst1 = list(dataset['fat']) lst3 = list(dataset['sugars']) lst2 = list(dataset['remarks']) np.random.seed(100) #create array of 50 random integers between 0 and 10 var1 = np.array(lst)+np.array(lst1)+np.array(lst3) #create a positively correlated array with some random noise var2 = var1 + np.array(lst2) #calculate the correlation between the two arrays np.corrcoef(var1, var2) #create train and testing vars X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=.2) print(X_train.shape, Y_train.shape) print(X_test.shape, Y_test.shape) #from sklearn.linear_model import LinearRegression #lr = LinearRegression() #lr.fit(X_train, Y_train) #y_lr_train_pred = lr.predict(X_train) #y_lr_test_pred = lr.predict(X_test) #from sklearn.metrics import mean_squared_error, r2_score #lr_train_mse = mean_squared_error(Y_train, y_lr_train_pred) #lr_train_r2 = r2_score(Y_train, y_lr_train_pred) #lr_test_mse = mean_squared_error(Y_test, y_lr_test_pred) #lr_test_r2 = r2_score(Y_test, y_lr_test_pred) #print(lr_train_mse) # define the keras model layer by layer from tensorflow.keras.layers import Dense from tensorflow.keras.models import Sequential from tensorflow.keras import initializers model = Sequential() model.add(Dense(12, input_dim=6, activation='relu')) model.add(Dense(8, activation='relu')) #model.add(Dense(4,init = 'uniform', activation='relu')) model.add(Dense(1, activation='sigmoid')) # compile the keras model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # fit the keras model on the dataset model.fit(X_train, Y_train, epochs=200, batch_size=32) # evaluate the keras model _, accuracy = model.evaluate(X_train, Y_train) print('Train_Accuracy: %.2f' % (accuracy*100)) y_hat= model.predict(np.array(X_test)) print('Test_Accuracy: %.2f' % (y_hat[0])) model.save('ann-model.model.h5') #from sklearn.metrics import mean_squared_error, r2_score #lr_train_mse = mean_squared_error(Y_train, y_lr_train_pred) #lr_train_r2 = r2_score(Y_train, y_lr_train_pred) #lr_test_mse = mean_squared_error(Y_test, y_lr_test_pred) #lr_test_r2 = r2_score(Y_test, y_lr_test_pred)#test accuracy check #print('Test_Accuracy: %.2f' % (lr_test_r2*100))
[ "numpy.random.seed", "tensorflow.keras.layers.Dense", "pandas.read_csv", "numpy.corrcoef", "sklearn.model_selection.train_test_split", "numpy.array", "tensorflow.keras.models.Sequential", "tensorflow.test.gpu_device_name" ]
[((495, 520), 'tensorflow.test.gpu_device_name', 'tf.test.gpu_device_name', ([], {}), '()\n', (518, 520), True, 'import tensorflow as tf\n'), ((718, 781), 'pandas.read_csv', 'pd.read_csv', (['"""/content/drive/MyDrive/data_1000.csv"""'], {'nrows': '(1000)'}), "('/content/drive/MyDrive/data_1000.csv', nrows=1000)\n", (729, 781), True, 'import pandas as pd\n'), ((1294, 1313), 'numpy.random.seed', 'np.random.seed', (['(100)'], {}), '(100)\n', (1308, 1313), True, 'import numpy as np\n'), ((1561, 1584), 'numpy.corrcoef', 'np.corrcoef', (['var1', 'var2'], {}), '(var1, var2)\n', (1572, 1584), True, 'import numpy as np\n'), ((1652, 1689), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'Y'], {'test_size': '(0.2)'}), '(X, Y, test_size=0.2)\n', (1668, 1689), False, 'from sklearn.model_selection import train_test_split\n'), ((2416, 2428), 'tensorflow.keras.models.Sequential', 'Sequential', ([], {}), '()\n', (2426, 2428), False, 'from tensorflow.keras.models import Sequential\n'), ((1404, 1418), 'numpy.array', 'np.array', (['lst3'], {}), '(lst3)\n', (1412, 1418), True, 'import numpy as np\n'), ((1495, 1509), 'numpy.array', 'np.array', (['lst2'], {}), '(lst2)\n', (1503, 1509), True, 'import numpy as np\n'), ((2439, 2480), 'tensorflow.keras.layers.Dense', 'Dense', (['(12)'], {'input_dim': '(6)', 'activation': '"""relu"""'}), "(12, input_dim=6, activation='relu')\n", (2444, 2480), False, 'from tensorflow.keras.layers import Dense\n'), ((2492, 2519), 'tensorflow.keras.layers.Dense', 'Dense', (['(8)'], {'activation': '"""relu"""'}), "(8, activation='relu')\n", (2497, 2519), False, 'from tensorflow.keras.layers import Dense\n'), ((2588, 2618), 'tensorflow.keras.layers.Dense', 'Dense', (['(1)'], {'activation': '"""sigmoid"""'}), "(1, activation='sigmoid')\n", (2593, 2618), False, 'from tensorflow.keras.layers import Dense\n'), ((2967, 2983), 'numpy.array', 'np.array', (['X_test'], {}), '(X_test)\n', (2975, 2983), True, 'import numpy as np\n'), ((1375, 1388), 'numpy.array', 'np.array', (['lst'], {}), '(lst)\n', (1383, 1388), True, 'import numpy as np\n'), ((1389, 1403), 'numpy.array', 'np.array', (['lst1'], {}), '(lst1)\n', (1397, 1403), True, 'import numpy as np\n')]
#!/usr/bin/python # -*- coding: utf-8 -*- import numpy as np import tensorflow as tf import matplotlib.pyplot as plt # 通过tf.set_random_seed设定种子数,后面定义的全部变量都可以跨会话生成相同的随机数 tf.set_random_seed(1) np.random.seed(1) learn_rate = 0.01 batch_size = 64 xdata = np.linspace(-1, 1, 100)[:, np.newaxis] # shape (100, 1) noise = np.random.normal(0, 0.1, size=xdata.shape) ydata = np.power(xdata, 2) + noise # shape (100, 1) + some noise plt.scatter(xdata, ydata) plt.show() # 定义神经网络 class Net: def __init__(self, opt, **kwargs): self.x = tf.placeholder(tf.float32, [None, 1]) self.y = tf.placeholder(tf.float32, [None, 1]) l1 = tf.layers.dense(self.x, 20, tf.nn.relu) lo = tf.layers.dense(l1, 1) self.loss = tf.losses.mean_squared_error(self.y, lo) self.train = opt(learn_rate, **kwargs).minimize(self.loss) # 定义不同的优化方法 net_SGD = Net(tf.train.GradientDescentOptimizer) net_Momentum = Net(tf.train.MomentumOptimizer, momentum=0.9) net_RMSprop = Net(tf.train.RMSPropOptimizer) net_Adam = Net(tf.train.AdamOptimizer) nets = [net_SGD, net_Momentum, net_RMSprop, net_Adam] sess = tf.Session() sess.run(tf.global_variables_initializer()) losses_ = [[], [], [], []] for step in range(300): index = np.random.randint(0, xdata.shape[0], batch_size) b_x = xdata[index] b_y = ydata[index] for net, l_ in zip(nets, losses_): _, l2 = sess.run([net.train, net.loss], {net.x: b_x, net.y: b_y}) l_.append(l2) labels = ['SGD', 'Momentum', 'RMSprop', 'Adam'] for i, l_his in enumerate(losses_): plt.plot(l_his, label=labels[i]) plt.legend(loc='best') plt.xlabel('Steps') plt.ylabel('Loss') plt.ylim((0, 0.3)) plt.show()
[ "matplotlib.pyplot.show", "numpy.random.seed", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylim", "tensorflow.global_variables_initializer", "matplotlib.pyplot.scatter", "matplotlib.pyplot.legend", "numpy.power", "tensorflow.Session", "tensorflow.layers.dense", "tensorflow.losses.mean_squared_error", "tensorflow.set_random_seed", "tensorflow.placeholder", "numpy.random.randint", "numpy.random.normal", "numpy.linspace", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel" ]
[((171, 192), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(1)'], {}), '(1)\n', (189, 192), True, 'import tensorflow as tf\n'), ((193, 210), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (207, 210), True, 'import numpy as np\n'), ((332, 374), 'numpy.random.normal', 'np.random.normal', (['(0)', '(0.1)'], {'size': 'xdata.shape'}), '(0, 0.1, size=xdata.shape)\n', (348, 374), True, 'import numpy as np\n'), ((465, 490), 'matplotlib.pyplot.scatter', 'plt.scatter', (['xdata', 'ydata'], {}), '(xdata, ydata)\n', (476, 490), True, 'import matplotlib.pyplot as plt\n'), ((491, 501), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (499, 501), True, 'import matplotlib.pyplot as plt\n'), ((1160, 1172), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1170, 1172), True, 'import tensorflow as tf\n'), ((1633, 1655), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (1643, 1655), True, 'import matplotlib.pyplot as plt\n'), ((1656, 1675), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Steps"""'], {}), "('Steps')\n", (1666, 1675), True, 'import matplotlib.pyplot as plt\n'), ((1676, 1694), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Loss"""'], {}), "('Loss')\n", (1686, 1694), True, 'import matplotlib.pyplot as plt\n'), ((1695, 1713), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0, 0.3)'], {}), '((0, 0.3))\n', (1703, 1713), True, 'import matplotlib.pyplot as plt\n'), ((1714, 1724), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1722, 1724), True, 'import matplotlib.pyplot as plt\n'), ((255, 278), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', '(100)'], {}), '(-1, 1, 100)\n', (266, 278), True, 'import numpy as np\n'), ((383, 401), 'numpy.power', 'np.power', (['xdata', '(2)'], {}), '(xdata, 2)\n', (391, 401), True, 'import numpy as np\n'), ((1182, 1215), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (1213, 1215), True, 'import tensorflow as tf\n'), ((1281, 1329), 'numpy.random.randint', 'np.random.randint', (['(0)', 'xdata.shape[0]', 'batch_size'], {}), '(0, xdata.shape[0], batch_size)\n', (1298, 1329), True, 'import numpy as np\n'), ((1600, 1632), 'matplotlib.pyplot.plot', 'plt.plot', (['l_his'], {'label': 'labels[i]'}), '(l_his, label=labels[i])\n', (1608, 1632), True, 'import matplotlib.pyplot as plt\n'), ((580, 617), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 1]'], {}), '(tf.float32, [None, 1])\n', (594, 617), True, 'import tensorflow as tf\n'), ((635, 672), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 1]'], {}), '(tf.float32, [None, 1])\n', (649, 672), True, 'import tensorflow as tf\n'), ((686, 725), 'tensorflow.layers.dense', 'tf.layers.dense', (['self.x', '(20)', 'tf.nn.relu'], {}), '(self.x, 20, tf.nn.relu)\n', (701, 725), True, 'import tensorflow as tf\n'), ((739, 761), 'tensorflow.layers.dense', 'tf.layers.dense', (['l1', '(1)'], {}), '(l1, 1)\n', (754, 761), True, 'import tensorflow as tf\n'), ((782, 822), 'tensorflow.losses.mean_squared_error', 'tf.losses.mean_squared_error', (['self.y', 'lo'], {}), '(self.y, lo)\n', (810, 822), True, 'import tensorflow as tf\n')]
import numpy as np from scipy import linalg from numpy.testing import assert_almost_equal from megamix.online.base import _log_normal_matrix from megamix.online.base import _full_covariance_matrices, _spherical_covariance_matrices from megamix.utils_testing import generate def test_log_normal_matrix_full(): n_points, n_components, n_features = 10,5,2 points = np.random.randn(n_points,n_features) means = np.random.randn(n_components,n_features) cov = generate.generate_covariance_matrices_full(n_components,n_features) cov_chol = np.empty((n_components,n_features,n_features)) for i in range(n_components): cov_chol[i] = linalg.cholesky(cov[i],lower=True) # Beginnig of the test log_det_cov = np.log(np.linalg.det(cov)) precisions = np.linalg.inv(cov) log_prob = np.empty((n_points,n_components)) for i in range(n_components): diff = points - means[i] y = np.dot(diff,np.dot(precisions[i],diff.T)) log_prob[:,i] = np.diagonal(y) expected_log_normal_matrix = -0.5 * (n_features * np.log(2*np.pi) + log_prob + log_det_cov) predected_log_normal_matrix = _log_normal_matrix(points,means,cov_chol,'full') assert_almost_equal(expected_log_normal_matrix,predected_log_normal_matrix) def test_full_covariance_matrices(): n_points, n_components, n_features = 10,5,2 points = np.random.randn(n_points,n_features) means = np.random.randn(n_components,n_features) pi = generate.generate_mixing_coefficients(n_components) resp = generate.generate_resp(n_points,n_components) weights = pi * n_points reg_covar = 1e-6 expected_full_covariance_matrices = np.empty((n_components,n_features,n_features)) for i in range(n_components): diff = points - means[i] diff_weighted = diff*resp[:,i:i+1] cov = 1/weights[i] * np.dot(diff_weighted.T,diff) cov.flat[::n_features+1] += reg_covar expected_full_covariance_matrices[i] = cov predected_full_covariance_matrices = _full_covariance_matrices(points,means,weights,resp,reg_covar) assert_almost_equal(expected_full_covariance_matrices,predected_full_covariance_matrices) def test_spherical_covariance_matrices(): n_points, n_components, n_features = 10,5,2 points = np.random.randn(n_points,n_features) means = np.random.randn(n_components,n_features) pi = generate.generate_mixing_coefficients(n_components) resp = generate.generate_resp(n_points,n_components) weights = pi * n_points reg_covar = 1e-6 expected_full_covariance_matrices = np.empty(n_components) for i in range(n_components): diff = points - means[i] diff_weighted = diff * resp[:,i:i+1] product = diff * diff_weighted expected_full_covariance_matrices[i] = np.sum(product)/weights[i] + reg_covar expected_full_covariance_matrices /= n_features predected_full_covariance_matrices = _spherical_covariance_matrices(points,means,weights,resp,reg_covar) assert_almost_equal(expected_full_covariance_matrices,predected_full_covariance_matrices)
[ "megamix.online.base._full_covariance_matrices", "numpy.sum", "numpy.log", "megamix.online.base._log_normal_matrix", "numpy.random.randn", "numpy.empty", "numpy.testing.assert_almost_equal", "scipy.linalg.cholesky", "megamix.utils_testing.generate.generate_covariance_matrices_full", "numpy.linalg.inv", "megamix.online.base._spherical_covariance_matrices", "megamix.utils_testing.generate.generate_mixing_coefficients", "numpy.dot", "numpy.linalg.det", "megamix.utils_testing.generate.generate_resp", "numpy.diagonal" ]
[((376, 413), 'numpy.random.randn', 'np.random.randn', (['n_points', 'n_features'], {}), '(n_points, n_features)\n', (391, 413), True, 'import numpy as np\n'), ((425, 466), 'numpy.random.randn', 'np.random.randn', (['n_components', 'n_features'], {}), '(n_components, n_features)\n', (440, 466), True, 'import numpy as np\n'), ((476, 544), 'megamix.utils_testing.generate.generate_covariance_matrices_full', 'generate.generate_covariance_matrices_full', (['n_components', 'n_features'], {}), '(n_components, n_features)\n', (518, 544), False, 'from megamix.utils_testing import generate\n'), ((559, 607), 'numpy.empty', 'np.empty', (['(n_components, n_features, n_features)'], {}), '((n_components, n_features, n_features))\n', (567, 607), True, 'import numpy as np\n'), ((791, 809), 'numpy.linalg.inv', 'np.linalg.inv', (['cov'], {}), '(cov)\n', (804, 809), True, 'import numpy as np\n'), ((825, 859), 'numpy.empty', 'np.empty', (['(n_points, n_components)'], {}), '((n_points, n_components))\n', (833, 859), True, 'import numpy as np\n'), ((1204, 1255), 'megamix.online.base._log_normal_matrix', '_log_normal_matrix', (['points', 'means', 'cov_chol', '"""full"""'], {}), "(points, means, cov_chol, 'full')\n", (1222, 1255), False, 'from megamix.online.base import _log_normal_matrix\n'), ((1262, 1338), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['expected_log_normal_matrix', 'predected_log_normal_matrix'], {}), '(expected_log_normal_matrix, predected_log_normal_matrix)\n', (1281, 1338), False, 'from numpy.testing import assert_almost_equal\n'), ((1446, 1483), 'numpy.random.randn', 'np.random.randn', (['n_points', 'n_features'], {}), '(n_points, n_features)\n', (1461, 1483), True, 'import numpy as np\n'), ((1495, 1536), 'numpy.random.randn', 'np.random.randn', (['n_components', 'n_features'], {}), '(n_components, n_features)\n', (1510, 1536), True, 'import numpy as np\n'), ((1545, 1596), 'megamix.utils_testing.generate.generate_mixing_coefficients', 'generate.generate_mixing_coefficients', (['n_components'], {}), '(n_components)\n', (1582, 1596), False, 'from megamix.utils_testing import generate\n'), ((1608, 1654), 'megamix.utils_testing.generate.generate_resp', 'generate.generate_resp', (['n_points', 'n_components'], {}), '(n_points, n_components)\n', (1630, 1654), False, 'from megamix.utils_testing import generate\n'), ((1748, 1796), 'numpy.empty', 'np.empty', (['(n_components, n_features, n_features)'], {}), '((n_components, n_features, n_features))\n', (1756, 1796), True, 'import numpy as np\n'), ((2143, 2209), 'megamix.online.base._full_covariance_matrices', '_full_covariance_matrices', (['points', 'means', 'weights', 'resp', 'reg_covar'], {}), '(points, means, weights, resp, reg_covar)\n', (2168, 2209), False, 'from megamix.online.base import _full_covariance_matrices, _spherical_covariance_matrices\n'), ((2219, 2313), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['expected_full_covariance_matrices', 'predected_full_covariance_matrices'], {}), '(expected_full_covariance_matrices,\n predected_full_covariance_matrices)\n', (2238, 2313), False, 'from numpy.testing import assert_almost_equal\n'), ((2422, 2459), 'numpy.random.randn', 'np.random.randn', (['n_points', 'n_features'], {}), '(n_points, n_features)\n', (2437, 2459), True, 'import numpy as np\n'), ((2471, 2512), 'numpy.random.randn', 'np.random.randn', (['n_components', 'n_features'], {}), '(n_components, n_features)\n', (2486, 2512), True, 'import numpy as np\n'), ((2521, 2572), 'megamix.utils_testing.generate.generate_mixing_coefficients', 'generate.generate_mixing_coefficients', (['n_components'], {}), '(n_components)\n', (2558, 2572), False, 'from megamix.utils_testing import generate\n'), ((2584, 2630), 'megamix.utils_testing.generate.generate_resp', 'generate.generate_resp', (['n_points', 'n_components'], {}), '(n_points, n_components)\n', (2606, 2630), False, 'from megamix.utils_testing import generate\n'), ((2724, 2746), 'numpy.empty', 'np.empty', (['n_components'], {}), '(n_components)\n', (2732, 2746), True, 'import numpy as np\n'), ((3117, 3188), 'megamix.online.base._spherical_covariance_matrices', '_spherical_covariance_matrices', (['points', 'means', 'weights', 'resp', 'reg_covar'], {}), '(points, means, weights, resp, reg_covar)\n', (3147, 3188), False, 'from megamix.online.base import _full_covariance_matrices, _spherical_covariance_matrices\n'), ((3198, 3292), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['expected_full_covariance_matrices', 'predected_full_covariance_matrices'], {}), '(expected_full_covariance_matrices,\n predected_full_covariance_matrices)\n', (3217, 3292), False, 'from numpy.testing import assert_almost_equal\n'), ((662, 697), 'scipy.linalg.cholesky', 'linalg.cholesky', (['cov[i]'], {'lower': '(True)'}), '(cov[i], lower=True)\n', (677, 697), False, 'from scipy import linalg\n'), ((754, 772), 'numpy.linalg.det', 'np.linalg.det', (['cov'], {}), '(cov)\n', (767, 772), True, 'import numpy as np\n'), ((1004, 1018), 'numpy.diagonal', 'np.diagonal', (['y'], {}), '(y)\n', (1015, 1018), True, 'import numpy as np\n'), ((950, 979), 'numpy.dot', 'np.dot', (['precisions[i]', 'diff.T'], {}), '(precisions[i], diff.T)\n', (956, 979), True, 'import numpy as np\n'), ((1934, 1963), 'numpy.dot', 'np.dot', (['diff_weighted.T', 'diff'], {}), '(diff_weighted.T, diff)\n', (1940, 1963), True, 'import numpy as np\n'), ((2945, 2960), 'numpy.sum', 'np.sum', (['product'], {}), '(product)\n', (2951, 2960), True, 'import numpy as np\n'), ((1082, 1099), 'numpy.log', 'np.log', (['(2 * np.pi)'], {}), '(2 * np.pi)\n', (1088, 1099), True, 'import numpy as np\n')]
# ============================================================================= # Copyright 2020 NVIDIA. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= import random import numpy as np from nemo import logging from nemo.collections.nlp.utils.callback_utils import ( get_classification_report, get_f1_scores, list2str, plot_confusion_matrix, tensor2list, ) __all__ = ['eval_iter_callback', 'eval_epochs_done_callback'] def eval_iter_callback(tensors, global_vars): if "all_intent_preds" not in global_vars.keys(): global_vars["all_intent_preds"] = [] if "all_intent_labels" not in global_vars.keys(): global_vars["all_intent_labels"] = [] if "all_slot_preds" not in global_vars.keys(): global_vars["all_slot_preds"] = [] if "all_slot_labels" not in global_vars.keys(): global_vars["all_slot_labels"] = [] if "all_subtokens_mask" not in global_vars.keys(): global_vars["all_subtokens_mask"] = [] all_intent_logits, all_intent_labels = [], [] all_slot_logits, all_slot_labels = [], [] all_subtokens_mask = [] for kv, v in tensors.items(): if kv.startswith('intent_logits'): for v_tensor in v: for logit_tensor in v_tensor: all_intent_logits.append(tensor2list(logit_tensor)) if kv.startswith('intents'): for v_tensor in v: for label_tensor in v_tensor: all_intent_labels.append(tensor2list(label_tensor)) if kv.startswith('slot_logits'): for v_tensor in v: for logit_tensor in v_tensor: all_slot_logits.append(tensor2list(logit_tensor)) if kv.startswith('slots'): for v_tensor in v: for label_tensor in v_tensor: all_slot_labels.extend(tensor2list(label_tensor)) if kv.startswith('subtokens_mask'): for v_tensor in v: for subtokens_mask_tensor in v_tensor: all_subtokens_mask.extend(tensor2list(subtokens_mask_tensor)) all_intent_preds = list(np.argmax(np.asarray(all_intent_logits), 1)) all_slot_preds = list(np.argmax(np.asarray(all_slot_logits), 2).flatten()) global_vars["all_intent_preds"].extend(all_intent_preds) global_vars["all_intent_labels"].extend(all_intent_labels) global_vars["all_slot_preds"].extend(all_slot_preds) global_vars["all_slot_labels"].extend(all_slot_labels) global_vars["all_subtokens_mask"].extend(all_subtokens_mask) def eval_epochs_done_callback(global_vars, intents_label_ids, slots_label_ids, graph_fold=None, normalize_cm=True): intent_labels = np.asarray(global_vars['all_intent_labels']) intent_preds = np.asarray(global_vars['all_intent_preds']) slot_labels = np.asarray(global_vars['all_slot_labels']) slot_preds = np.asarray(global_vars['all_slot_preds']) subtokens_mask = np.asarray(global_vars['all_subtokens_mask']) > 0.5 slot_labels = slot_labels[subtokens_mask] slot_preds = slot_preds[subtokens_mask] # print predictions and labels for a small random subset of data sample_size = 20 i = 0 if intent_preds.shape[0] > sample_size + 1: i = random.randint(0, intent_preds.shape[0] - sample_size - 1) logging.info("Sampled i_preds: [%s]" % list2str(intent_preds[i : i + sample_size])) logging.info("Sampled intents: [%s]" % list2str(intent_labels[i : i + sample_size])) logging.info("Sampled s_preds: [%s]" % list2str(slot_preds[i : i + sample_size])) logging.info("Sampled slots: [%s]" % list2str(slot_labels[i : i + sample_size])) if graph_fold: # calculate, plot and save the confusion_matrix plot_confusion_matrix( intent_labels, intent_preds, graph_fold, intents_label_ids, normalize=normalize_cm, prefix='Intent' ) plot_confusion_matrix( slot_labels, slot_preds, graph_fold, slots_label_ids, normalize=normalize_cm, prefix='Slot' ) logging.info('Slot Prediction Results:') slot_accuracy = np.mean(slot_labels == slot_preds) logging.info(f'Slot Accuracy: {slot_accuracy}') f1_scores = get_f1_scores(slot_labels, slot_preds, average_modes=['weighted', 'macro', 'micro']) for k, v in f1_scores.items(): logging.info(f'{k}: {v}') logging.info(f'\n {get_classification_report(slot_labels, slot_preds, label_ids=slots_label_ids)}') logging.info('Intent Prediction Results:') intent_accuracy = np.mean(intent_labels == intent_preds) logging.info(f'Intent Accuracy: {intent_accuracy}') f1_scores = get_f1_scores(intent_labels, intent_preds, average_modes=['weighted', 'macro', 'micro']) for k, v in f1_scores.items(): logging.info(f'{k}: {v}') logging.info(f'\n {get_classification_report(intent_labels, intent_preds, label_ids=intents_label_ids)}') return dict({'intent_accuracy': intent_accuracy, 'slot_accuracy': slot_accuracy})
[ "random.randint", "numpy.asarray", "nemo.collections.nlp.utils.callback_utils.get_classification_report", "nemo.collections.nlp.utils.callback_utils.plot_confusion_matrix", "nemo.logging.info", "numpy.mean", "nemo.collections.nlp.utils.callback_utils.get_f1_scores", "nemo.collections.nlp.utils.callback_utils.tensor2list", "nemo.collections.nlp.utils.callback_utils.list2str" ]
[((3299, 3343), 'numpy.asarray', 'np.asarray', (["global_vars['all_intent_labels']"], {}), "(global_vars['all_intent_labels'])\n", (3309, 3343), True, 'import numpy as np\n'), ((3363, 3406), 'numpy.asarray', 'np.asarray', (["global_vars['all_intent_preds']"], {}), "(global_vars['all_intent_preds'])\n", (3373, 3406), True, 'import numpy as np\n'), ((3426, 3468), 'numpy.asarray', 'np.asarray', (["global_vars['all_slot_labels']"], {}), "(global_vars['all_slot_labels'])\n", (3436, 3468), True, 'import numpy as np\n'), ((3486, 3527), 'numpy.asarray', 'np.asarray', (["global_vars['all_slot_preds']"], {}), "(global_vars['all_slot_preds'])\n", (3496, 3527), True, 'import numpy as np\n'), ((4639, 4679), 'nemo.logging.info', 'logging.info', (['"""Slot Prediction Results:"""'], {}), "('Slot Prediction Results:')\n", (4651, 4679), False, 'from nemo import logging\n'), ((4700, 4734), 'numpy.mean', 'np.mean', (['(slot_labels == slot_preds)'], {}), '(slot_labels == slot_preds)\n', (4707, 4734), True, 'import numpy as np\n'), ((4739, 4786), 'nemo.logging.info', 'logging.info', (['f"""Slot Accuracy: {slot_accuracy}"""'], {}), "(f'Slot Accuracy: {slot_accuracy}')\n", (4751, 4786), False, 'from nemo import logging\n'), ((4803, 4891), 'nemo.collections.nlp.utils.callback_utils.get_f1_scores', 'get_f1_scores', (['slot_labels', 'slot_preds'], {'average_modes': "['weighted', 'macro', 'micro']"}), "(slot_labels, slot_preds, average_modes=['weighted', 'macro',\n 'micro'])\n", (4816, 4891), False, 'from nemo.collections.nlp.utils.callback_utils import get_classification_report, get_f1_scores, list2str, plot_confusion_matrix, tensor2list\n'), ((5067, 5109), 'nemo.logging.info', 'logging.info', (['"""Intent Prediction Results:"""'], {}), "('Intent Prediction Results:')\n", (5079, 5109), False, 'from nemo import logging\n'), ((5132, 5170), 'numpy.mean', 'np.mean', (['(intent_labels == intent_preds)'], {}), '(intent_labels == intent_preds)\n', (5139, 5170), True, 'import numpy as np\n'), ((5175, 5226), 'nemo.logging.info', 'logging.info', (['f"""Intent Accuracy: {intent_accuracy}"""'], {}), "(f'Intent Accuracy: {intent_accuracy}')\n", (5187, 5226), False, 'from nemo import logging\n'), ((5243, 5335), 'nemo.collections.nlp.utils.callback_utils.get_f1_scores', 'get_f1_scores', (['intent_labels', 'intent_preds'], {'average_modes': "['weighted', 'macro', 'micro']"}), "(intent_labels, intent_preds, average_modes=['weighted',\n 'macro', 'micro'])\n", (5256, 5335), False, 'from nemo.collections.nlp.utils.callback_utils import get_classification_report, get_f1_scores, list2str, plot_confusion_matrix, tensor2list\n'), ((3549, 3594), 'numpy.asarray', 'np.asarray', (["global_vars['all_subtokens_mask']"], {}), "(global_vars['all_subtokens_mask'])\n", (3559, 3594), True, 'import numpy as np\n'), ((3853, 3911), 'random.randint', 'random.randint', (['(0)', '(intent_preds.shape[0] - sample_size - 1)'], {}), '(0, intent_preds.shape[0] - sample_size - 1)\n', (3867, 3911), False, 'import random\n'), ((4344, 4470), 'nemo.collections.nlp.utils.callback_utils.plot_confusion_matrix', 'plot_confusion_matrix', (['intent_labels', 'intent_preds', 'graph_fold', 'intents_label_ids'], {'normalize': 'normalize_cm', 'prefix': '"""Intent"""'}), "(intent_labels, intent_preds, graph_fold,\n intents_label_ids, normalize=normalize_cm, prefix='Intent')\n", (4365, 4470), False, 'from nemo.collections.nlp.utils.callback_utils import get_classification_report, get_f1_scores, list2str, plot_confusion_matrix, tensor2list\n'), ((4497, 4615), 'nemo.collections.nlp.utils.callback_utils.plot_confusion_matrix', 'plot_confusion_matrix', (['slot_labels', 'slot_preds', 'graph_fold', 'slots_label_ids'], {'normalize': 'normalize_cm', 'prefix': '"""Slot"""'}), "(slot_labels, slot_preds, graph_fold, slots_label_ids,\n normalize=normalize_cm, prefix='Slot')\n", (4518, 4615), False, 'from nemo.collections.nlp.utils.callback_utils import get_classification_report, get_f1_scores, list2str, plot_confusion_matrix, tensor2list\n'), ((4931, 4956), 'nemo.logging.info', 'logging.info', (['f"""{k}: {v}"""'], {}), "(f'{k}: {v}')\n", (4943, 4956), False, 'from nemo import logging\n'), ((5375, 5400), 'nemo.logging.info', 'logging.info', (['f"""{k}: {v}"""'], {}), "(f'{k}: {v}')\n", (5387, 5400), False, 'from nemo import logging\n'), ((2742, 2771), 'numpy.asarray', 'np.asarray', (['all_intent_logits'], {}), '(all_intent_logits)\n', (2752, 2771), True, 'import numpy as np\n'), ((3955, 3996), 'nemo.collections.nlp.utils.callback_utils.list2str', 'list2str', (['intent_preds[i:i + sample_size]'], {}), '(intent_preds[i:i + sample_size])\n', (3963, 3996), False, 'from nemo.collections.nlp.utils.callback_utils import get_classification_report, get_f1_scores, list2str, plot_confusion_matrix, tensor2list\n'), ((4043, 4085), 'nemo.collections.nlp.utils.callback_utils.list2str', 'list2str', (['intent_labels[i:i + sample_size]'], {}), '(intent_labels[i:i + sample_size])\n', (4051, 4085), False, 'from nemo.collections.nlp.utils.callback_utils import get_classification_report, get_f1_scores, list2str, plot_confusion_matrix, tensor2list\n'), ((4132, 4171), 'nemo.collections.nlp.utils.callback_utils.list2str', 'list2str', (['slot_preds[i:i + sample_size]'], {}), '(slot_preds[i:i + sample_size])\n', (4140, 4171), False, 'from nemo.collections.nlp.utils.callback_utils import get_classification_report, get_f1_scores, list2str, plot_confusion_matrix, tensor2list\n'), ((4216, 4256), 'nemo.collections.nlp.utils.callback_utils.list2str', 'list2str', (['slot_labels[i:i + sample_size]'], {}), '(slot_labels[i:i + sample_size])\n', (4224, 4256), False, 'from nemo.collections.nlp.utils.callback_utils import get_classification_report, get_f1_scores, list2str, plot_confusion_matrix, tensor2list\n'), ((4981, 5058), 'nemo.collections.nlp.utils.callback_utils.get_classification_report', 'get_classification_report', (['slot_labels', 'slot_preds'], {'label_ids': 'slots_label_ids'}), '(slot_labels, slot_preds, label_ids=slots_label_ids)\n', (5006, 5058), False, 'from nemo.collections.nlp.utils.callback_utils import get_classification_report, get_f1_scores, list2str, plot_confusion_matrix, tensor2list\n'), ((5425, 5513), 'nemo.collections.nlp.utils.callback_utils.get_classification_report', 'get_classification_report', (['intent_labels', 'intent_preds'], {'label_ids': 'intents_label_ids'}), '(intent_labels, intent_preds, label_ids=\n intents_label_ids)\n', (5450, 5513), False, 'from nemo.collections.nlp.utils.callback_utils import get_classification_report, get_f1_scores, list2str, plot_confusion_matrix, tensor2list\n'), ((2813, 2840), 'numpy.asarray', 'np.asarray', (['all_slot_logits'], {}), '(all_slot_logits)\n', (2823, 2840), True, 'import numpy as np\n'), ((1904, 1929), 'nemo.collections.nlp.utils.callback_utils.tensor2list', 'tensor2list', (['logit_tensor'], {}), '(logit_tensor)\n', (1915, 1929), False, 'from nemo.collections.nlp.utils.callback_utils import get_classification_report, get_f1_scores, list2str, plot_confusion_matrix, tensor2list\n'), ((2091, 2116), 'nemo.collections.nlp.utils.callback_utils.tensor2list', 'tensor2list', (['label_tensor'], {}), '(label_tensor)\n', (2102, 2116), False, 'from nemo.collections.nlp.utils.callback_utils import get_classification_report, get_f1_scores, list2str, plot_confusion_matrix, tensor2list\n'), ((2280, 2305), 'nemo.collections.nlp.utils.callback_utils.tensor2list', 'tensor2list', (['logit_tensor'], {}), '(logit_tensor)\n', (2291, 2305), False, 'from nemo.collections.nlp.utils.callback_utils import get_classification_report, get_f1_scores, list2str, plot_confusion_matrix, tensor2list\n'), ((2463, 2488), 'nemo.collections.nlp.utils.callback_utils.tensor2list', 'tensor2list', (['label_tensor'], {}), '(label_tensor)\n', (2474, 2488), False, 'from nemo.collections.nlp.utils.callback_utils import get_classification_report, get_f1_scores, list2str, plot_confusion_matrix, tensor2list\n'), ((2667, 2701), 'nemo.collections.nlp.utils.callback_utils.tensor2list', 'tensor2list', (['subtokens_mask_tensor'], {}), '(subtokens_mask_tensor)\n', (2678, 2701), False, 'from nemo.collections.nlp.utils.callback_utils import get_classification_report, get_f1_scores, list2str, plot_confusion_matrix, tensor2list\n')]
import threading import numpy as np from baselines.common.segment_tree import SumSegmentTree, MinSegmentTree import math from scipy.stats import rankdata import json class ReplayBuffer: def __init__(self, buffer_shapes, size_in_transitions, T, sample_transitions): """Creates a replay buffer. Args: buffer_shapes (dict of ints): the shape for all buffers that are used in the replay buffer size_in_transitions (int): the size of the buffer, measured in transitions T (int): the time horizon for episodes sample_transitions (function): a function that samples from the replay buffer """ self.buffer_shapes = buffer_shapes self.size = size_in_transitions // T self.T = T self.sample_transitions = sample_transitions # self.buffers is {key: array(size_in_episodes x T or T+1 x dim_key)} self.buffers = {key: np.empty([self.size, *shape]) for key, shape in buffer_shapes.items()} # memory management self.current_size = 0 self.n_transitions_stored = 0 self.lock = threading.Lock() @property def full(self): with self.lock: return self.current_size == self.size def sample(self, batch_size): """Returns a dict {key: array(batch_size x shapes[key])} """ buffers = {} with self.lock: assert self.current_size > 0 for key in self.buffers.keys(): buffers[key] = self.buffers[key][:self.current_size] buffers['o_2'] = buffers['o'][:, 1:, :] buffers['ag_2'] = buffers['ag'][:, 1:, :] transitions = self.sample_transitions(buffers, batch_size) for key in (['r', 'o_2', 'ag_2'] + list(self.buffers.keys())): assert key in transitions, "key %s missing from transitions" % key return transitions def store_episode(self, episode_batch): """episode_batch: array(batch_size x (T or T+1) x dim_key) """ batch_sizes = [len(episode_batch[key]) for key in episode_batch.keys()] assert np.all(np.array(batch_sizes) == batch_sizes[0]) batch_size = batch_sizes[0] with self.lock: idxs = self._get_storage_idx(batch_size) # load inputs into buffers for key in self.buffers.keys(): self.buffers[key][idxs] = episode_batch[key] self.n_transitions_stored += batch_size * self.T def get_current_episode_size(self): with self.lock: return self.current_size def get_current_size(self): with self.lock: return self.current_size * self.T def get_transitions_stored(self): with self.lock: return self.n_transitions_stored def clear_buffer(self): with self.lock: self.current_size = 0 def _get_storage_idx(self, inc=None): inc = inc or 1 # size increment assert inc <= self.size, "Batch committed to replay is too large!" # go consecutively until you hit the end, and then go randomly. if self.current_size+inc <= self.size: idx = np.arange(self.current_size, self.current_size+inc) elif self.current_size < self.size: overflow = inc - (self.size - self.current_size) idx_a = np.arange(self.current_size, self.size) idx_b = np.random.randint(0, self.current_size, overflow) idx = np.concatenate([idx_a, idx_b]) else: idx = np.random.randint(0, self.size, inc) # update replay size self.current_size = min(self.size, self.current_size+inc) if inc == 1: idx = idx[0] return idx class ReplayBufferDiversity: def __init__(self, buffer_shapes, size_in_transitions, T, sample_transitions, prioritization, env_name, goal_type): """ Creates a replay buffer for measuring the diversity Args: buffer_shapes (dict of ints): the shape for all buffers that are used in the replay buffer size_in_transitions (int): the size of the buffer, measured in transitions T (int): the time horizon for episodes sample_transitions (function): a function that samples from the replay buffer """ self.buffer_shapes = buffer_shapes self.size = size_in_transitions // T self.T = T self.sample_transitions = sample_transitions self.buffers = {key: np.empty([self.size, *shape]) for key, shape in buffer_shapes.items()} self.buffers['div'] = np.empty([self.size, 1]) # diversity # the prioritization is dpp now self.prioritization = prioritization self.env_name = env_name # memory management self.current_size = 0 self.n_transitions_stored = 0 self.current_size_test = 0 self.n_transitions_stored_test = 0 self.goal_type = goal_type self.lock = threading.Lock() @property def full(self): with self.lock: return self.current_size == self.size def sample(self, batch_size): """Returns a dict {key: array(batch_size x shapes[key])} """ buffers = {} with self.lock: assert self.current_size > 0 for key in self.buffers.keys(): buffers[key] = self.buffers[key][:self.current_size] buffers['o_2'] = buffers['o'][:, 1:, :] buffers['ag_2'] = buffers['ag'][:, 1:, :] transitions = self.sample_transitions(buffers, batch_size) for key in (['r', 'o_2', 'ag_2'] + list(self.buffers.keys())): if not key == 'div': assert key in transitions, "key %s missing from transitions" % key return transitions def store_episode(self, episode_batch, clip_div): """episode_batch: array(batch_size x (T or T+1) x dim_key) """ batch_sizes = [len(episode_batch[key]) for key in episode_batch.keys()] assert np.all(np.array(batch_sizes) == batch_sizes[0]) batch_size = batch_sizes[0] buffers = {} for key in episode_batch.keys(): buffers[key] = episode_batch[key] # start to calculate the diversity if self.prioritization == 'diversity': # we only consider the fetch environment now if self.goal_type == 'full': traj = buffers['ag'].copy().astype(np.float32) elif self.goal_type == 'rotate': # if use the rotate... traj = buffers['ag'][:, :, 3:].copy().astype(np.float32) else: raise NotImplementedError # normalize the vector traj = traj / np.linalg.norm(traj, axis=2, keepdims=True) diversity = [] for i in range(traj.shape[1] - 1): result = np.einsum("ijk, ilk -> ijl" , traj[:, i:i+2, :], traj[:, i:i+2, :]) diversity.append(np.linalg.det(result)) diversity = np.array(diversity) diversity[diversity < 0] = 0 diversity = np.sum(diversity, 0) # calculate the accumulate rewards mean_rewards = np.mean(buffers['info_is_success'].squeeze(), axis=1, keepdims=True) # rewrad gains is useless here... can be removed reward_gain = np.exp(mean_rewards) # clip the diversity - 0.001 episode_batch['div'] = np.clip(diversity.reshape(-1, 1), 0, clip_div) # write the data with self.lock: idxs = self._get_storage_idx(batch_size) # load inputs into buffers for key in self.buffers.keys(): self.buffers[key][idxs] = episode_batch[key] self.n_transitions_stored += batch_size * self.T def get_current_episode_size(self): with self.lock: return self.current_size def get_current_size(self): with self.lock: return self.current_size * self.T def get_transitions_stored(self): with self.lock: return self.n_transitions_stored def clear_buffer(self): with self.lock: self.current_size = 0 def _get_storage_idx(self, inc=None): inc = inc or 1 # size increment assert inc <= self.size, "Batch committed to replay is too large!" # go consecutively until you hit the end, and then go randomly. if self.current_size+inc <= self.size: idx = np.arange(self.current_size, self.current_size+inc) elif self.current_size < self.size: overflow = inc - (self.size - self.current_size) idx_a = np.arange(self.current_size, self.size) idx_b = np.random.randint(0, self.current_size, overflow) idx = np.concatenate([idx_a, idx_b]) else: # here we shouldn't randomly pick the trajectory to replace idx = np.random.randint(0, self.size, inc) # update replay size self.current_size = min(self.size, self.current_size+inc) if inc == 1: idx = idx[0] return idx
[ "numpy.sum", "numpy.empty", "numpy.einsum", "threading.Lock", "numpy.random.randint", "numpy.arange", "numpy.array", "numpy.exp", "numpy.linalg.norm", "numpy.linalg.det", "numpy.concatenate" ]
[((1158, 1174), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (1172, 1174), False, 'import threading\n'), ((4693, 4717), 'numpy.empty', 'np.empty', (['[self.size, 1]'], {}), '([self.size, 1])\n', (4701, 4717), True, 'import numpy as np\n'), ((5077, 5093), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (5091, 5093), False, 'import threading\n'), ((947, 976), 'numpy.empty', 'np.empty', (['[self.size, *shape]'], {}), '([self.size, *shape])\n', (955, 976), True, 'import numpy as np\n'), ((3219, 3272), 'numpy.arange', 'np.arange', (['self.current_size', '(self.current_size + inc)'], {}), '(self.current_size, self.current_size + inc)\n', (3228, 3272), True, 'import numpy as np\n'), ((4568, 4597), 'numpy.empty', 'np.empty', (['[self.size, *shape]'], {}), '([self.size, *shape])\n', (4576, 4597), True, 'import numpy as np\n'), ((7135, 7154), 'numpy.array', 'np.array', (['diversity'], {}), '(diversity)\n', (7143, 7154), True, 'import numpy as np\n'), ((7220, 7240), 'numpy.sum', 'np.sum', (['diversity', '(0)'], {}), '(diversity, 0)\n', (7226, 7240), True, 'import numpy as np\n'), ((7471, 7491), 'numpy.exp', 'np.exp', (['mean_rewards'], {}), '(mean_rewards)\n', (7477, 7491), True, 'import numpy as np\n'), ((8619, 8672), 'numpy.arange', 'np.arange', (['self.current_size', '(self.current_size + inc)'], {}), '(self.current_size, self.current_size + inc)\n', (8628, 8672), True, 'import numpy as np\n'), ((2163, 2184), 'numpy.array', 'np.array', (['batch_sizes'], {}), '(batch_sizes)\n', (2171, 2184), True, 'import numpy as np\n'), ((3396, 3435), 'numpy.arange', 'np.arange', (['self.current_size', 'self.size'], {}), '(self.current_size, self.size)\n', (3405, 3435), True, 'import numpy as np\n'), ((3456, 3505), 'numpy.random.randint', 'np.random.randint', (['(0)', 'self.current_size', 'overflow'], {}), '(0, self.current_size, overflow)\n', (3473, 3505), True, 'import numpy as np\n'), ((3524, 3554), 'numpy.concatenate', 'np.concatenate', (['[idx_a, idx_b]'], {}), '([idx_a, idx_b])\n', (3538, 3554), True, 'import numpy as np\n'), ((3587, 3623), 'numpy.random.randint', 'np.random.randint', (['(0)', 'self.size', 'inc'], {}), '(0, self.size, inc)\n', (3604, 3623), True, 'import numpy as np\n'), ((6129, 6150), 'numpy.array', 'np.array', (['batch_sizes'], {}), '(batch_sizes)\n', (6137, 6150), True, 'import numpy as np\n'), ((6844, 6887), 'numpy.linalg.norm', 'np.linalg.norm', (['traj'], {'axis': '(2)', 'keepdims': '(True)'}), '(traj, axis=2, keepdims=True)\n', (6858, 6887), True, 'import numpy as np\n'), ((6987, 7057), 'numpy.einsum', 'np.einsum', (['"""ijk, ilk -> ijl"""', 'traj[:, i:i + 2, :]', 'traj[:, i:i + 2, :]'], {}), "('ijk, ilk -> ijl', traj[:, i:i + 2, :], traj[:, i:i + 2, :])\n", (6996, 7057), True, 'import numpy as np\n'), ((8796, 8835), 'numpy.arange', 'np.arange', (['self.current_size', 'self.size'], {}), '(self.current_size, self.size)\n', (8805, 8835), True, 'import numpy as np\n'), ((8856, 8905), 'numpy.random.randint', 'np.random.randint', (['(0)', 'self.current_size', 'overflow'], {}), '(0, self.current_size, overflow)\n', (8873, 8905), True, 'import numpy as np\n'), ((8924, 8954), 'numpy.concatenate', 'np.concatenate', (['[idx_a, idx_b]'], {}), '([idx_a, idx_b])\n', (8938, 8954), True, 'import numpy as np\n'), ((9059, 9095), 'numpy.random.randint', 'np.random.randint', (['(0)', 'self.size', 'inc'], {}), '(0, self.size, inc)\n', (9076, 9095), True, 'import numpy as np\n'), ((7088, 7109), 'numpy.linalg.det', 'np.linalg.det', (['result'], {}), '(result)\n', (7101, 7109), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt import matplotlib import mlpredict gpu = 'V100' opt = 'SGD' MLP = mlpredict.import_tools.import_dnn('MLP') MLP.describe() batchsize = 2**np.arange(0,10,1) time_layer = np.zeros([2,10]) time_total = np.zeros(10) for i in range(len(batchsize)): time_total[i], layer, time_layer[:,i] = MLP.predict(gpu = gpu, optimizer = opt, batchsize = batchsize[i]) print ("time_total = " ,time_total[i]) #l_unique = layer.copy() #duplicates = [12,11,9,6] #for d in duplicates: # print(l_unique[d]) # l_unique.pop(d) t_unique = time_layer fig,ax = plt.subplots(1,1,figsize=[8,8]) plt.plot(batchsize,t_unique.transpose(),'o-') ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter()) ax.get_yaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter()) ax.xaxis.set_minor_formatter(plt.NullFormatter()) ax.yaxis.set_minor_formatter(plt.NullFormatter()) matplotlib.rc('xtick', labelsize=25) matplotlib.rc('ytick', labelsize=25) plt.xlabel('batch size',fontsize=25) plt.ylabel('predicted time (ms)',fontsize=25) plt.legend(l_unique,bbox_to_anchor=(1.04,1), loc="upper left",fontsize=20) plt.tight_layout() plt.show()
[ "matplotlib.pyplot.tight_layout", "matplotlib.rc", "matplotlib.pyplot.show", "matplotlib.pyplot.legend", "numpy.zeros", "matplotlib.ticker.ScalarFormatter", "numpy.arange", "matplotlib.pyplot.NullFormatter", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.subplots", "mlpredict.import_tools.import_dnn" ]
[((121, 161), 'mlpredict.import_tools.import_dnn', 'mlpredict.import_tools.import_dnn', (['"""MLP"""'], {}), "('MLP')\n", (154, 161), False, 'import mlpredict\n'), ((225, 242), 'numpy.zeros', 'np.zeros', (['[2, 10]'], {}), '([2, 10])\n', (233, 242), True, 'import numpy as np\n'), ((255, 267), 'numpy.zeros', 'np.zeros', (['(10)'], {}), '(10)\n', (263, 267), True, 'import numpy as np\n'), ((730, 764), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '[8, 8]'}), '(1, 1, figsize=[8, 8])\n', (742, 764), True, 'import matplotlib.pyplot as plt\n'), ((1054, 1090), 'matplotlib.rc', 'matplotlib.rc', (['"""xtick"""'], {'labelsize': '(25)'}), "('xtick', labelsize=25)\n", (1067, 1090), False, 'import matplotlib\n'), ((1091, 1127), 'matplotlib.rc', 'matplotlib.rc', (['"""ytick"""'], {'labelsize': '(25)'}), "('ytick', labelsize=25)\n", (1104, 1127), False, 'import matplotlib\n'), ((1129, 1166), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""batch size"""'], {'fontsize': '(25)'}), "('batch size', fontsize=25)\n", (1139, 1166), True, 'import matplotlib.pyplot as plt\n'), ((1166, 1212), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""predicted time (ms)"""'], {'fontsize': '(25)'}), "('predicted time (ms)', fontsize=25)\n", (1176, 1212), True, 'import matplotlib.pyplot as plt\n'), ((1213, 1290), 'matplotlib.pyplot.legend', 'plt.legend', (['l_unique'], {'bbox_to_anchor': '(1.04, 1)', 'loc': '"""upper left"""', 'fontsize': '(20)'}), "(l_unique, bbox_to_anchor=(1.04, 1), loc='upper left', fontsize=20)\n", (1223, 1290), True, 'import matplotlib.pyplot as plt\n'), ((1289, 1307), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1305, 1307), True, 'import matplotlib.pyplot as plt\n'), ((1309, 1319), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1317, 1319), True, 'import matplotlib.pyplot as plt\n'), ((194, 213), 'numpy.arange', 'np.arange', (['(0)', '(10)', '(1)'], {}), '(0, 10, 1)\n', (203, 213), True, 'import numpy as np\n'), ((844, 879), 'matplotlib.ticker.ScalarFormatter', 'matplotlib.ticker.ScalarFormatter', ([], {}), '()\n', (877, 879), False, 'import matplotlib\n'), ((916, 951), 'matplotlib.ticker.ScalarFormatter', 'matplotlib.ticker.ScalarFormatter', ([], {}), '()\n', (949, 951), False, 'import matplotlib\n'), ((982, 1001), 'matplotlib.pyplot.NullFormatter', 'plt.NullFormatter', ([], {}), '()\n', (999, 1001), True, 'import matplotlib.pyplot as plt\n'), ((1032, 1051), 'matplotlib.pyplot.NullFormatter', 'plt.NullFormatter', ([], {}), '()\n', (1049, 1051), True, 'import matplotlib.pyplot as plt\n')]
import cv2 import time import numpy as np from grabscreen import grab_screen from directkeys import PressKey, ReleaseKey from directkeys import W, A, D from countdown import CountDown ''' Most of the code in this script was taken from Sentdex's Python plays GTA-V ''' def roi(img, vertices): mask = np.zeros_like(img) cv2.fillPoly(mask, vertices, 255) masked = cv2.bitwise_and(img, mask) return masked def straight(): print('straight') PressKey(W) ReleaseKey(A) ReleaseKey(D) def left(): print('left') PressKey(W) PressKey(A) time.sleep(0.05) ReleaseKey(A) def right(): print('right') PressKey(W) PressKey(D) time.sleep(0.05) ReleaseKey(D) def auto_canny(image, sigma=0.33): ''' Reference: https://www.pyimagesearch.com/ ''' v = np.median(image) # apply automatic Canny edge detection using the computed median lower = int(max(0, (1.0 - sigma) * v)) upper = int(min(255, (1.0 + sigma) * v)) edged = cv2.Canny(image, lower, upper) # return the edged image return edged def draw_lanes(img, lines, color=[0, 255, 255], thickness=3): # if this fails, go with some default line try: # finds the maximum y value for a lane marker # (since we cannot assume the horizon will always be at the same point.) ys = [] for i in lines: for ii in i: ys += [ii[1], ii[3]] min_y = min(ys) max_y = 150 new_lines = [] line_dict = {} for idx, i in enumerate(lines): for xyxy in i: # These four lines: # modified from http://stackoverflow.com/questions/21565994/method-to-return-the-equation-of-a-straight-line-given-two-points # Used to calculate the definition of a line, given two sets of coords. x_coords = (xyxy[0], xyxy[2]) y_coords = (xyxy[1], xyxy[3]) A = np.vstack([x_coords, np.ones(len(x_coords))]).T m, b = np.linalg.lstsq(A, y_coords)[0] # Calculating our new, and improved, xs x1 = (min_y - b) / m x2 = (max_y - b) / m line_dict[idx] = [m, b, [int(x1), min_y, int(x2), max_y]] new_lines.append([int(x1), min_y, int(x2), max_y]) final_lanes = {} for idx in line_dict: final_lanes_copy = final_lanes.copy() m = line_dict[idx][0] b = line_dict[idx][1] line = line_dict[idx][2] if len(final_lanes) == 0: final_lanes[m] = [[m, b, line]] else: found_copy = False for other_ms in final_lanes_copy: if not found_copy: if abs(other_ms * 1.2) > abs(m) > abs(other_ms * 0.8): if abs(final_lanes_copy[other_ms][0][1] * 1.2) > abs(b) > abs(final_lanes_copy[other_ms][0][1] * 0.8): final_lanes[other_ms].append([m, b, line]) found_copy = True break else: final_lanes[m] = [[m, b, line]] line_counter = {} for lanes in final_lanes: line_counter[lanes] = len(final_lanes[lanes]) top_lanes = sorted(line_counter.items(), key=lambda item: item[1])[::-1][:2] lane1_id = top_lanes[0][0] lane2_id = top_lanes[1][0] def average_lane(lane_data): x1s = [] y1s = [] x2s = [] y2s = [] for data in lane_data: x1s.append(data[2][0]) y1s.append(data[2][1]) x2s.append(data[2][2]) y2s.append(data[2][3]) return int(np.mean(x1s)), int(np.mean(y1s)), int(np.mean(x2s)), int(np.mean(y2s)) l1_x1, l1_y1, l1_x2, l1_y2 = average_lane(final_lanes[lane1_id]) l2_x1, l2_y1, l2_x2, l2_y2 = average_lane(final_lanes[lane2_id]) return [l1_x1, l1_y1, l1_x2, l1_y2], [l2_x1, l2_y1, l2_x2, l2_y2], lane1_id, lane2_id except Exception: pass def LaneFinder(image): org_image = image # convert to grayscale image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # gaussian blur image = cv2.GaussianBlur(image, (3, 3), 0) # edge detection image = auto_canny(image) # Masking Region of Interest vertices = np.array([[0, 201], [0, 50], [381, 50], [381, 201]], np.int32) image = roi(image, [vertices]) # probabilistic hough transform lines = cv2.HoughLinesP(image, rho=1, theta=(np.pi / 180), threshold=5, minLineLength=20, maxLineGap=5) m1 = 0 m2 = 0 # drawing lines try: l1, l2, m1, m2 = draw_lanes(org_image, lines) cv2.line(org_image, (l1[0], l1[1]), (l1[2], l1[3]), [0, 255, 0], 3) cv2.line(org_image, (l2[0], l2[1]), (l2[2], l2[3]), [0, 255, 0], 3) except Exception: pass try: for coords in lines: coords = coords[0] try: cv2.line(image, (coords[0], coords[1]), (coords[2], coords[3]), [255, 0, 0], 3) except Exception: pass except Exception: pass return image, org_image, m1, m2 if __name__ == '__main__': CountDown(5) while True: screen = grab_screen(region=(270, 250, 650, 450)) new_screen, original_image, m1, m2 = LaneFinder(screen) # cv2.imshow('window', new_screen) # cv2.imshow('window2', cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)) if m1 < 0 and m2 < 0: right() elif m1 > 0 and m2 > 0: left() else: straight() if cv2.waitKey(25) == ord('q'): cv2.destroyAllWindows() break
[ "cv2.GaussianBlur", "cv2.bitwise_and", "cv2.fillPoly", "numpy.mean", "cv2.HoughLinesP", "cv2.line", "numpy.zeros_like", "cv2.cvtColor", "directkeys.ReleaseKey", "directkeys.PressKey", "cv2.destroyAllWindows", "cv2.Canny", "numpy.median", "cv2.waitKey", "countdown.CountDown", "time.sleep", "grabscreen.grab_screen", "numpy.linalg.lstsq", "numpy.array" ]
[((306, 324), 'numpy.zeros_like', 'np.zeros_like', (['img'], {}), '(img)\n', (319, 324), True, 'import numpy as np\n'), ((329, 362), 'cv2.fillPoly', 'cv2.fillPoly', (['mask', 'vertices', '(255)'], {}), '(mask, vertices, 255)\n', (341, 362), False, 'import cv2\n'), ((376, 402), 'cv2.bitwise_and', 'cv2.bitwise_and', (['img', 'mask'], {}), '(img, mask)\n', (391, 402), False, 'import cv2\n'), ((466, 477), 'directkeys.PressKey', 'PressKey', (['W'], {}), '(W)\n', (474, 477), False, 'from directkeys import PressKey, ReleaseKey\n'), ((482, 495), 'directkeys.ReleaseKey', 'ReleaseKey', (['A'], {}), '(A)\n', (492, 495), False, 'from directkeys import PressKey, ReleaseKey\n'), ((500, 513), 'directkeys.ReleaseKey', 'ReleaseKey', (['D'], {}), '(D)\n', (510, 513), False, 'from directkeys import PressKey, ReleaseKey\n'), ((550, 561), 'directkeys.PressKey', 'PressKey', (['W'], {}), '(W)\n', (558, 561), False, 'from directkeys import PressKey, ReleaseKey\n'), ((566, 577), 'directkeys.PressKey', 'PressKey', (['A'], {}), '(A)\n', (574, 577), False, 'from directkeys import PressKey, ReleaseKey\n'), ((582, 598), 'time.sleep', 'time.sleep', (['(0.05)'], {}), '(0.05)\n', (592, 598), False, 'import time\n'), ((603, 616), 'directkeys.ReleaseKey', 'ReleaseKey', (['A'], {}), '(A)\n', (613, 616), False, 'from directkeys import PressKey, ReleaseKey\n'), ((655, 666), 'directkeys.PressKey', 'PressKey', (['W'], {}), '(W)\n', (663, 666), False, 'from directkeys import PressKey, ReleaseKey\n'), ((671, 682), 'directkeys.PressKey', 'PressKey', (['D'], {}), '(D)\n', (679, 682), False, 'from directkeys import PressKey, ReleaseKey\n'), ((687, 703), 'time.sleep', 'time.sleep', (['(0.05)'], {}), '(0.05)\n', (697, 703), False, 'import time\n'), ((708, 721), 'directkeys.ReleaseKey', 'ReleaseKey', (['D'], {}), '(D)\n', (718, 721), False, 'from directkeys import PressKey, ReleaseKey\n'), ((829, 845), 'numpy.median', 'np.median', (['image'], {}), '(image)\n', (838, 845), True, 'import numpy as np\n'), ((1015, 1045), 'cv2.Canny', 'cv2.Canny', (['image', 'lower', 'upper'], {}), '(image, lower, upper)\n', (1024, 1045), False, 'import cv2\n'), ((4318, 4357), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2GRAY'], {}), '(image, cv2.COLOR_BGR2GRAY)\n', (4330, 4357), False, 'import cv2\n'), ((4390, 4424), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['image', '(3, 3)', '(0)'], {}), '(image, (3, 3), 0)\n', (4406, 4424), False, 'import cv2\n'), ((4524, 4586), 'numpy.array', 'np.array', (['[[0, 201], [0, 50], [381, 50], [381, 201]]', 'np.int32'], {}), '([[0, 201], [0, 50], [381, 50], [381, 201]], np.int32)\n', (4532, 4586), True, 'import numpy as np\n'), ((4670, 4768), 'cv2.HoughLinesP', 'cv2.HoughLinesP', (['image'], {'rho': '(1)', 'theta': '(np.pi / 180)', 'threshold': '(5)', 'minLineLength': '(20)', 'maxLineGap': '(5)'}), '(image, rho=1, theta=np.pi / 180, threshold=5, minLineLength\n =20, maxLineGap=5)\n', (4685, 4768), False, 'import cv2\n'), ((5424, 5436), 'countdown.CountDown', 'CountDown', (['(5)'], {}), '(5)\n', (5433, 5436), False, 'from countdown import CountDown\n'), ((4907, 4974), 'cv2.line', 'cv2.line', (['org_image', '(l1[0], l1[1])', '(l1[2], l1[3])', '[0, 255, 0]', '(3)'], {}), '(org_image, (l1[0], l1[1]), (l1[2], l1[3]), [0, 255, 0], 3)\n', (4915, 4974), False, 'import cv2\n'), ((4983, 5050), 'cv2.line', 'cv2.line', (['org_image', '(l2[0], l2[1])', '(l2[2], l2[3])', '[0, 255, 0]', '(3)'], {}), '(org_image, (l2[0], l2[1]), (l2[2], l2[3]), [0, 255, 0], 3)\n', (4991, 5050), False, 'import cv2\n'), ((5470, 5510), 'grabscreen.grab_screen', 'grab_screen', ([], {'region': '(270, 250, 650, 450)'}), '(region=(270, 250, 650, 450))\n', (5481, 5510), False, 'from grabscreen import grab_screen\n'), ((5850, 5865), 'cv2.waitKey', 'cv2.waitKey', (['(25)'], {}), '(25)\n', (5861, 5865), False, 'import cv2\n'), ((5891, 5914), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (5912, 5914), False, 'import cv2\n'), ((5188, 5267), 'cv2.line', 'cv2.line', (['image', '(coords[0], coords[1])', '(coords[2], coords[3])', '[255, 0, 0]', '(3)'], {}), '(image, (coords[0], coords[1]), (coords[2], coords[3]), [255, 0, 0], 3)\n', (5196, 5267), False, 'import cv2\n'), ((2059, 2087), 'numpy.linalg.lstsq', 'np.linalg.lstsq', (['A', 'y_coords'], {}), '(A, y_coords)\n', (2074, 2087), True, 'import numpy as np\n'), ((3884, 3896), 'numpy.mean', 'np.mean', (['x1s'], {}), '(x1s)\n', (3891, 3896), True, 'import numpy as np\n'), ((3903, 3915), 'numpy.mean', 'np.mean', (['y1s'], {}), '(y1s)\n', (3910, 3915), True, 'import numpy as np\n'), ((3922, 3934), 'numpy.mean', 'np.mean', (['x2s'], {}), '(x2s)\n', (3929, 3934), True, 'import numpy as np\n'), ((3941, 3953), 'numpy.mean', 'np.mean', (['y2s'], {}), '(y2s)\n', (3948, 3953), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 21 10:52:40 2019 @author: guido """ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 21 10:30:25 2018 @author: guido """ import os import pandas as pd import numpy as np from oneibl.one import ONE from define_paths import analysis_path from load_mouse_data import get_water_weight, get_behavior import matplotlib.pyplot as plt from scipy.optimize import curve_fit import scipy as sp from os.path import join def pf(x, alpha, beta, gamma): return 0.5 + (1 - 0.5 - gamma) * (1. / (1 + np.exp( -(x-alpha)/beta))) ## CONNECT TO ONE one = ONE() # initialize ac = one._alyxClient # get a list of all mice #subjects = pd.DataFrame(one.alyx.get('/subjects?responsible_user=jeanpaul')) #subjects = pd.DataFrame(one.alyx.get('/subjects?nickname=DY_001')) #subjects = pd.DataFrame(one.alyx.get('/subjects?&alive=True&stock=False')) #subjects = pd.DataFrame(one.alyx.get('/subjects?alive=True?&responsible_user=ines')) subjects = pd.DataFrame(one.alyx.get('/subjects')) # get folder to save plots path = analysis_path() if not os.path.exists(path): os.mkdir(path) print(subjects['nickname'].unique()) learning = pd.DataFrame(columns=['mouse','lab','delay','rise','asymp','date_start']) for i, mouse in enumerate(subjects['nickname']): print('Loading data for ' + mouse) try: # load in data behav = get_behavior(mouse) weight_water, baseline = get_water_weight(mouse) sub = ac.rest('subjects','read',mouse) except: continue if len(np.unique(behav['days'])) < 5: continue # calculate perc correct on easy trials and reaction times behav['correct_easy'] = behav.correct behav.loc[np.abs(behav['signedContrast']) < 50, 'correct_easy'] = np.NaN perf = behav.groupby(['date'])['correct_easy'].mean().reset_index() days = behav.groupby(['date'])['days'].median().reset_index() perf['days'] = days['days'] trial_num = behav.groupby(['date'])['correct_easy'].size().reset_index() perf['trial_num'] = trial_num['correct_easy'] # Remove weird first session if perf['days'][1]-perf['days'][0] > 20: perf = perf[1:] perf['days'] = perf['days'] - perf['days'][1] delay = np.nan rise = np.nan asymp = np.nan if sum(perf['correct_easy'] > 0.75) > 2: # Fit function par0 = sp.array([20, 5, 0]) lms = sp.array([[0,0,0],[100,10,0.5]]) try: par, mcov = curve_fit(pf, perf['days'], perf['correct_easy'], par0, bounds=lms) except: continue vec_x = np.arange(0,max(perf['days'])+2,0.1) fit_x = pf(vec_x, par[0], par[1], par[2]) norm_x = (fit_x-min(fit_x))/max(fit_x-min(fit_x)) delay = vec_x[np.argmin(np.abs(norm_x - 0.2))] rise = vec_x[np.argmin(np.abs(norm_x - 0.8))] asymp = vec_x[np.argmin(np.abs(norm_x - 0.99))] plt.figure() plt.plot(perf['days'], perf['correct_easy'], 'ro') plt.plot(np.arange(0,max(perf['days'])+2,0.1), pf(np.arange(0,max(perf['days'])+2,0.1), par[0], par[1], par[2]), linewidth=2) plt.title(mouse) plt.xlabel('Training sessions (days)') plt.ylabel('Performance (% correct easy trials)') plt.plot([-2,delay], [pf(delay, par[0], par[1], par[2]), pf(delay, par[0], par[1], par[2])], '--' ,color=[0.5,0.5,0.5]) plt.plot([delay,delay], [pf(delay, par[0], par[1], par[2]), 0.4], '--' ,color=[0.5,0.5,0.5]) plt.plot([-2,rise], [pf(rise, par[0], par[1], par[2]), pf(rise, par[0], par[1], par[2])], '--' ,color=[0.5,0.5,0.5]) plt.plot([rise,rise], [pf(rise, par[0], par[1], par[2]), 0.4], '--' ,color=[0.5,0.5,0.5]) plt.plot([-2,asymp], [pf(asymp, par[0], par[1], par[2]), pf(asymp, par[0], par[1], par[2])], '--' ,color=[0.5,0.5,0.5]) plt.plot([asymp,asymp], [pf(asymp, par[0], par[1], par[2]), 0.4], '--' ,color=[0.5,0.5,0.5]) plt.savefig(join(path,'Learning','%s.pdf'%mouse)) #plt.show() plt.close() learning.loc[i] = [mouse, subjects.loc[i,'lab'], delay, rise, asymp, perf.loc[perf.index.values[0],'date']] learning.to_pickle(join(path,'learning_rates'))
[ "matplotlib.pyplot.title", "os.mkdir", "numpy.abs", "matplotlib.pyplot.figure", "numpy.exp", "os.path.join", "numpy.unique", "matplotlib.pyplot.xlabel", "pandas.DataFrame", "matplotlib.pyplot.close", "os.path.exists", "oneibl.one.ONE", "scipy.optimize.curve_fit", "matplotlib.pyplot.ylabel", "load_mouse_data.get_water_weight", "define_paths.analysis_path", "matplotlib.pyplot.plot", "scipy.array", "load_mouse_data.get_behavior" ]
[((635, 640), 'oneibl.one.ONE', 'ONE', ([], {}), '()\n', (638, 640), False, 'from oneibl.one import ONE\n'), ((1096, 1111), 'define_paths.analysis_path', 'analysis_path', ([], {}), '()\n', (1109, 1111), False, 'from define_paths import analysis_path\n'), ((1218, 1296), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['mouse', 'lab', 'delay', 'rise', 'asymp', 'date_start']"}), "(columns=['mouse', 'lab', 'delay', 'rise', 'asymp', 'date_start'])\n", (1230, 1296), True, 'import pandas as pd\n'), ((1119, 1139), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (1133, 1139), False, 'import os\n'), ((1145, 1159), 'os.mkdir', 'os.mkdir', (['path'], {}), '(path)\n', (1153, 1159), False, 'import os\n'), ((4248, 4276), 'os.path.join', 'join', (['path', '"""learning_rates"""'], {}), "(path, 'learning_rates')\n", (4252, 4276), False, 'from os.path import join\n'), ((1429, 1448), 'load_mouse_data.get_behavior', 'get_behavior', (['mouse'], {}), '(mouse)\n', (1441, 1448), False, 'from load_mouse_data import get_water_weight, get_behavior\n'), ((1482, 1505), 'load_mouse_data.get_water_weight', 'get_water_weight', (['mouse'], {}), '(mouse)\n', (1498, 1505), False, 'from load_mouse_data import get_water_weight, get_behavior\n'), ((2437, 2457), 'scipy.array', 'sp.array', (['[20, 5, 0]'], {}), '([20, 5, 0])\n', (2445, 2457), True, 'import scipy as sp\n'), ((2472, 2509), 'scipy.array', 'sp.array', (['[[0, 0, 0], [100, 10, 0.5]]'], {}), '([[0, 0, 0], [100, 10, 0.5]])\n', (2480, 2509), True, 'import scipy as sp\n'), ((2993, 3005), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3003, 3005), True, 'import matplotlib.pyplot as plt\n'), ((3014, 3064), 'matplotlib.pyplot.plot', 'plt.plot', (["perf['days']", "perf['correct_easy']", '"""ro"""'], {}), "(perf['days'], perf['correct_easy'], 'ro')\n", (3022, 3064), True, 'import matplotlib.pyplot as plt\n'), ((3207, 3223), 'matplotlib.pyplot.title', 'plt.title', (['mouse'], {}), '(mouse)\n', (3216, 3223), True, 'import matplotlib.pyplot as plt\n'), ((3232, 3270), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Training sessions (days)"""'], {}), "('Training sessions (days)')\n", (3242, 3270), True, 'import matplotlib.pyplot as plt\n'), ((3279, 3328), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Performance (% correct easy trials)"""'], {}), "('Performance (% correct easy trials)')\n", (3289, 3328), True, 'import matplotlib.pyplot as plt\n'), ((4096, 4107), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (4105, 4107), True, 'import matplotlib.pyplot as plt\n'), ((1600, 1624), 'numpy.unique', 'np.unique', (["behav['days']"], {}), "(behav['days'])\n", (1609, 1624), True, 'import numpy as np\n'), ((2542, 2609), 'scipy.optimize.curve_fit', 'curve_fit', (['pf', "perf['days']", "perf['correct_easy']", 'par0'], {'bounds': 'lms'}), "(pf, perf['days'], perf['correct_easy'], par0, bounds=lms)\n", (2551, 2609), False, 'from scipy.optimize import curve_fit\n'), ((4030, 4070), 'os.path.join', 'join', (['path', '"""Learning"""', "('%s.pdf' % mouse)"], {}), "(path, 'Learning', '%s.pdf' % mouse)\n", (4034, 4070), False, 'from os.path import join\n'), ((1772, 1803), 'numpy.abs', 'np.abs', (["behav['signedContrast']"], {}), "(behav['signedContrast'])\n", (1778, 1803), True, 'import numpy as np\n'), ((2840, 2860), 'numpy.abs', 'np.abs', (['(norm_x - 0.2)'], {}), '(norm_x - 0.2)\n', (2846, 2860), True, 'import numpy as np\n'), ((2894, 2914), 'numpy.abs', 'np.abs', (['(norm_x - 0.8)'], {}), '(norm_x - 0.8)\n', (2900, 2914), True, 'import numpy as np\n'), ((2949, 2970), 'numpy.abs', 'np.abs', (['(norm_x - 0.99)'], {}), '(norm_x - 0.99)\n', (2955, 2970), True, 'import numpy as np\n'), ((583, 610), 'numpy.exp', 'np.exp', (['(-(x - alpha) / beta)'], {}), '(-(x - alpha) / beta)\n', (589, 610), True, 'import numpy as np\n')]
__author__ = "<NAME>" # University of South Carolina # <NAME>-Simpers group # Starting Date: June, 2016 import matplotlib.pyplot as plt import numpy as np from scripts import ternary def plt_ternary_save(data, tertitle='', labelNames=('Species A','Species B','Species C'), scale=100, sv=False, svpth=r"C:/Users/Travis W/Pictures/", svflnm='Unnamed', cbl='Scale', vmin=None, vmax=None, cmap='viridis', cb=True, style='h'): """ Overview ---------- This program makes use of the ternary package and creates a ternary colormap Parameters ---------- data: 4-tup of (a,b,c,i) where a, b, and c are the ternary coordinates and i is the intensity tertitle: chart title labelNames: Names of a, b, and c for chart axes scale: scale of chart (if 0-100, then scale is 100) sv: Boolean, save chart when true, show chart when false svpth: path to save ternary image svflnm: file name for ternary diagram when saving cbl: colorbar label vmin: minimum value of colorbar (leave blank to set to min value in i) vmax: maximum value of colorbar (leave blank to set to max value in i) cmap: determines color map used cb: use colorbar if true style: h = hexagons, d = triangles for point shape Returns ------- """ if sv: font = {'size': 12} # Set font size for **kwargs figsize = (3.4, 2.5) ticksize = 6 lnwdth = 0.5 lnsty = '--' alpha = 0.15 else: font = {'size': 30} # Set font size for **kwargs figsize = (30, 30) ticksize = 20 lnwdth = 2 lnsty = ':' alpha = 0.5 d = dict() x = data[:, 1] y = data[:, 0] if cb: i = data[:, 3] for col in range(1, len(x)): d[(x[col], y[col])] = i[col] else: for col in range(1, len(x)): d[(x[col], y[col])] = 0.5 # Turn off normal axis, set figure size figure, ax = plt.subplots(figsize=figsize) ax.axis("off") # Create ternary axes (tax) figure, tax = ternary.figure(ax=ax, scale=scale) # Axis Labels (bottom corrisponds to x values, left corrisponds to y values) tax.bottom_axis_label(labelNames[1], offset=-0.1, **font) tax.left_axis_label(labelNames[2], offset=0.17, **font) tax.right_axis_label(labelNames[0], offset=0.17, **font) # Plot data, boundary, gridlines, and ticks tax.heatmap(d, style=style, cmap=cmap, cbarlabel=cbl, vmin=vmin, vmax=vmax, colorbar=cb) tax.boundary(linewidth=1) tax.gridlines(multiple=10, linewidth=lnwdth, alpha=alpha, linestyle=lnsty) ticks = [round(i / float(scale), 1) for i in range(0, scale+1, 10)] tax.ticks(ticks=ticks, axis='rlb', linewidth=1, clockwise=False, offset=0.03, textsize=ticksize) # Set chart title tax.set_title(tertitle) # Make chart pretty tax.clear_matplotlib_ticks() tax._redraw_labels() plt.tight_layout() # Save or show if sv: plt.savefig(''.join([svpth, svflnm]), dpi=600) else: tax.show() def plt_tern_scatter(data, tertitle='', labelNames=('Species A','Species B','Species C'), scale=100, sv=False, svpth=r"C:/Users/Tr<NAME>/Pictures/", svflnm='Unnamed', clr='k'): font = {'size': 24} # Turn off normal axis, set figure size figsize = [10,10] figure, ax = plt.subplots(figsize=figsize) ax.axis("off") figure, tax = ternary.figure(scale=scale) tax.set_title(tertitle, fontsize=20) tax.boundary(linewidth=2.0) tax.gridlines(multiple=10, color="k") # Axis Labels (bottom corrisponds to x values, left corrisponds to y values) tax.bottom_axis_label(labelNames[1], offset=0, **font) tax.left_axis_label(labelNames[2], offset=0.12, **font) tax.right_axis_label(labelNames[0], offset=0.12, **font) points = np.array([data[:,1], data[:,0]]).T # for WAXS MG stuff color = data[:, 3] print(color.shape) clrs = list() for i, col in enumerate(color): if col == 0: clrs.append('aqua') elif col == 1: clrs.append('lawngreen') else: clrs.append('yellow') # print(points, clrs) # end wax MG stuff tax.scatter(points, marker='o', color=clrs, s=100) tax.ticks(axis='lbr', linewidth=1, multiple=10, textsize=14) # Set chart title tax.set_title(tertitle) # Make chart pretty tax.clear_matplotlib_ticks() tax._redraw_labels() plt.tight_layout() plt.axis('off') if sv: plt.savefig(''.join([svpth, svflnm]), dpi=600) else: tax.show() # #data = np.genfromtxt('test_data.csv', delimiter=',') ##plt_ternary_save(data, tertitle='', labelNames=('Co','Fe','V'), scale=100, ## sv=False, svpth=r"C:/Users/Travis W/Pictures/", svflnm='Unnamed', ## cbl='Scale', vmin=1, vmax=5, cmap='viridis', cb=True, style='h') #
[ "scripts.ternary.figure", "matplotlib.pyplot.axis", "matplotlib.pyplot.subplots", "numpy.array", "matplotlib.pyplot.tight_layout" ]
[((2008, 2037), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (2020, 2037), True, 'import matplotlib.pyplot as plt\n'), ((2108, 2142), 'scripts.ternary.figure', 'ternary.figure', ([], {'ax': 'ax', 'scale': 'scale'}), '(ax=ax, scale=scale)\n', (2122, 2142), False, 'from scripts import ternary\n'), ((2970, 2988), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2986, 2988), True, 'import matplotlib.pyplot as plt\n'), ((3437, 3466), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (3449, 3466), True, 'import matplotlib.pyplot as plt\n'), ((3505, 3532), 'scripts.ternary.figure', 'ternary.figure', ([], {'scale': 'scale'}), '(scale=scale)\n', (3519, 3532), False, 'from scripts import ternary\n'), ((4556, 4574), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (4572, 4574), True, 'import matplotlib.pyplot as plt\n'), ((4579, 4594), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (4587, 4594), True, 'import matplotlib.pyplot as plt\n'), ((3924, 3958), 'numpy.array', 'np.array', (['[data[:, 1], data[:, 0]]'], {}), '([data[:, 1], data[:, 0]])\n', (3932, 3958), True, 'import numpy as np\n')]
import requests import json import pandas as pd import numpy as np import sys import logging from pathlib import Path logging.basicConfig(filename='logging_for_adding_group_permissions.log',level=logging.INFO) """ This python script is used to add group permissions based on the group_permissions_input file. python3 add_group_permissions.py 0000000000000000000000000000000000000000000000000000000000000000 """ def log_information(log_string): logging.info(log_string) print(log_string) def get_group_permissions_template_input(file_name): group_permissions_template_input = pd.read_csv(file_name) return group_permissions_template_input def get_group_permissions(AccountPermissions_file_name): account_permissions = pd.read_csv(AccountPermissions_file_name) group_permissions = [] for i in np.arange(0, np.shape(account_permissions)[0]): group_permissions.append(account_permissions.iloc[i][0]) # print(group_permissions) return group_permissions def get_project_id(account_name, account_name_id_connector): """ Looks through all of the account names in the account_name_id_connector numpy array. Then returns the project id for that account name """ for i in np.arange(0, np.shape(account_name_id_connector)[0]): if str(account_name_id_connector[i][0]) == str(account_name): return account_name_id_connector[i][1] return None def get_account_type(admin_api_key, env, project_id): if check_invalid_env(env): return None api_url = env + "/api/account.json/get_account?access_key=" + str(admin_api_key) + "&account_id=" + str(project_id) r7 = requests.get(api_url) # TODO: expand this to work for Google. (not released yet) if "Provider" in r7.json(): if "Type" in r7.json(): provider = r7.json()["Provider"] account_type = r7.json()["Type"] if provider == "Amazon Web Services": if account_type == "General": return "AwsPermissions" else: if account_type == "MultiView": return "AwsMavPermissions" else: log_information("Could not match account type and provider for project_id: " + str(project_id)) log_information(r7.json()) return None else: if provider == "Microsoft Azure": if account_type == "General": return "AzurePermissions" else: if account_type == "MultiView": return "AzureMavPermissions" else: log_information("Could not match account type and provider for project_id: " + str(project_id)) log_information(r7.json()) return None else: log_information("Could not match account type and provider for project_id: " + str(project_id)) log_information(r7.json()) return None else: log_information("Could not get account type for project_id: " + str(project_id)) log_information(r7.json()) return None else: log_information("Could not get provider for project_id: " + str(project_id)) log_information(r7.json()) return None def add_group_permissions(admin_api_key, group_permissions_input_row, AccountPermissions, group_id, account_type): env = group_permissions_input_row[0] if check_invalid_env(env): return None api_url = env + "/api/account.json/add_access_control_lists_per_account_per_group" # print(AccountPermissions) add_acl_info = json.dumps({"group_id": group_id, "use_account": group_permissions_input_row[2], "acls": AccountPermissions}) r7 = requests.post(api_url, headers = {"Content-Type": "application/json", "access_key": admin_api_key}, data = add_acl_info) if "Code" in r7.json(): log_information("Added the acls for AccountType: " + str(account_type) + " for group: " + group_permissions_input_row[1] + " (group_id: " + str(group_id) + ") for account: " + group_permissions_input_row[2]) log_information(r7.json()) log_information("") else: log_information("Failed to add the acls for group: " + group_permissions_input_row[1] + " (group_id: " + str(group_id) + ") for account: " + group_permissions_input_row[2]) log_information(r7.json()) def get_groups_connector(admin_api_key, env): if check_invalid_env(env): return None api_url = env + "/api/account.json/get_groups_v2" get_group_info = json.dumps({}) r7 = requests.post(api_url, headers = {"Content-Type": "application/json", "access_key": admin_api_key}, data = get_group_info) if "Groups" in r7.json(): Groups = r7.json()["Groups"] if len(Groups) > 0: group_name_id_connector = np.zeros((len(Groups),2), dtype="U200") for i in np.arange(0, len(Groups)): if "Name" in Groups[i] and "Id" in Groups[i]: group_name_id_connector[i][0] = Groups[i]["Name"] group_name_id_connector[i][1] = Groups[i]["Id"] else: log_information("Could not find name or id of group") log_information(str(Groups[i])) return group_name_id_connector else: log_information("Could not find any Groups ") log_information(r7.json()) return None else: log_information("Could not find any Groups") log_information(r7.json()) return None def get_group_id(group_name, group_name_id_connector): """ Looks through the numpy array of a list of group names and their associated id. Then returns the group id for the inputted group name. """ # TODO: vectorize this search to make it quicker for i in np.arange(0, np.shape(group_name_id_connector)[0]): if str(group_name_id_connector[i][0]) == str(group_name): return group_name_id_connector[i][1] return None def get_accounts_connector(admin_api_key, env): """ Gets the list of all accounts. Generates a list of account names to project id """ if check_invalid_env(env): return None api_url = env + "/api/account.json/get_accounts_v4?access_key=" + str(admin_api_key) r7 = requests.get(api_url) if "accounts_and_users" in r7.json(): accounts_and_users = r7.json()["accounts_and_users"] account_name_id_connector = np.zeros((len(accounts_and_users),2), dtype="U400") if len(accounts_and_users) > 0: for i in np.arange(0, np.shape(accounts_and_users)[0]): if "account_name" in accounts_and_users[i] and "cc_account_id" in accounts_and_users[i]: account_name_id_connector[i][0] = accounts_and_users[i]["account_name"] account_name_id_connector[i][1] = accounts_and_users[i]["cc_account_id"] else: log_information("Could not find an account_name or cc_account_id for this account") log_information(str(accounts_and_users[i])) return account_name_id_connector else: log_information("There are no accounts in this partner") log_information(r7.json()) return None else: log_information("Could not find any accounts in this partner") log_information(r7.json()) return None def cycle_add_group_permissions(admin_api_key, group_permissions_template_input, Permissions): """ Finds the group id from the group name. Then adds the permissions to that group and account based on the input file. """ group_name_id_connector = get_groups_connector(admin_api_key, group_permissions_template_input.iloc[0][0]) # print(group_name_id_connector) if group_name_id_connector is None: log_information("Groups were not properly parsed, please contact Support") return None account_name_id_connector = get_accounts_connector(admin_api_key, group_permissions_template_input.iloc[0][0]) if account_name_id_connector is None: return None # TODO: use python objects and types to make this a proper type AccountTypes = ["AwsPermissions", "AwsMavPermissions", "AzurePermissions", "AzureMavPermissions"] for i in np.arange(0, np.shape(group_permissions_template_input)[0]): project_id = get_project_id(group_permissions_template_input.iloc[i][2], account_name_id_connector) if not(project_id is None): account_type = get_account_type(admin_api_key, group_permissions_template_input.iloc[i][0], project_id) if not(account_type is None): if account_type in AccountTypes: account_type_index = AccountTypes.index(account_type) if Permissions[account_type_index] is None: log_information("AccountType: " + str(account_type) + " has no permissions csv file, so skipping for group " + group_permissions_template_input.iloc[i][1] + " and account " + group_permissions_template_input.iloc[i][2]) else: group_id = get_group_id(group_permissions_template_input.iloc[i][1], group_name_id_connector) if not(group_id is None): add_group_permissions(admin_api_key, group_permissions_template_input.iloc[i], Permissions[account_type_index], group_id, account_type) else: log_information("Could not find a group id for the group with name: " + str(group_permissions_template_input.iloc[i][1]) + " skipping row " + str(i + 2)) else: log_information("Could not find a matching account type for " + str(account_type) + " skipping row " + str(i + 2)) else: log_information("Could not get the account type for the account name: " + str(group_permissions_template_input.iloc[i][2]) + " for the project_id: " + str(project_id) + " skipping row " + str(i + 2)) else: log_information("Could not find a project_id for the account " + str(group_permissions_template_input.iloc[i][2]) + " skipping row " + str(i + 2)) log_information("") def get_groups(env, admin_api_key): """ You have to check for and handle duplicate groups because historically CloudCheckr used to allow for duplicate group creation. """ if check_invalid_env(env): return None, None api_url = env + "/api/account.json/get_groups" r7 = requests.get(api_url, headers = {"Content-Type": "application/json", "access_key": admin_api_key}) groups_list = [] groups_duplicate_list = [] if "GroupNames" in r7.json(): GroupNames = r7.json()["GroupNames"] for i in np.arange(0, len(GroupNames)): groups_list.append(GroupNames[i]) for i in np.arange(0, len(GroupNames)): if groups_list.count(GroupNames[i]) > 1: groups_duplicate_list.append(GroupNames[i]) log_information("Found duplicate group: " + GroupNames[i] + ". We recommend renaming it through the UI to remove duplicates.") return groups_list, groups_duplicate_list else: return groups_list, groups_duplicate_list def check_invalid_env(env): """ This will check for an invalid enviroment. Currently it will only check for api, eu, au, or gov. If you are using a standalone environment, then you MUST add that to this function """ Enviroments = ["https://api.cloudcheckr.com", "https://eu.cloudcheckr.com", "https://au.cloudcheckr.com", "https://gov.cloudcheckr.com", "https://qa.cloudcheckr.com"] if not(env in Enviroments): log_information("The environment " + str(env) + " is not valid. If this is a standalone environment, please add the url to the check_invalid_env function.") return True return False def main(): file_name = "group_permissions_input.csv" check_group_permissions_input_file = Path(file_name) if check_group_permissions_input_file.is_file(): group_permissions_template_input = get_group_permissions_template_input(file_name) else: log_information("No group_permissions_input.csv found. Please write file for input") return AwsPermissions_file_name = "AwsPermissions.csv" check_aws_permissions = Path(AwsPermissions_file_name) AwsPermissions = None if check_aws_permissions.is_file(): AwsPermissions = get_group_permissions(AwsPermissions_file_name) else: log_information("No Aws Permissions found") AwsMavPermissions_file_name = "AwsMavPermissions.csv" check_aws_mav_permissions = Path(AwsMavPermissions_file_name) AwsMavPermissions = None if check_aws_mav_permissions.is_file(): AwsMavPermissions = get_group_permissions(AwsMavPermissions_file_name) else: log_information("No Aws Mav Permissions found") AzurePermissions_file_name = "AzurePermissions.csv" check_azure_permissions = Path(AzurePermissions_file_name) AzurePermissions = None if check_azure_permissions.is_file(): AzurePermissions = get_group_permissions(AzurePermissions_file_name) else: log_information("No Azure Account Permissions found") AzureMavPermissions_file_name = "AzureMavPermissions.csv" check_azure_mav_permissions = Path(AzureMavPermissions_file_name) AzureMavPermissions = None if check_azure_mav_permissions.is_file(): AzureMavPermissions = get_group_permissions(AzureMavPermissions_file_name) else: log_information("No Azure Mav Account Permissions found") try: admin_api_key = sys.argv[1] except IndexError: print("Need admin_api_key in input") return groups_list, groups_duplicate_list = get_groups(group_permissions_template_input.iloc[0][0], admin_api_key) if groups_list is None: return if len(groups_duplicate_list) > 0: log_information("Please remove duplicate group names before proceeding.") return else: log_information("No duplicate groups found, please proceed.") cycle_add_group_permissions(admin_api_key, group_permissions_template_input, [AwsPermissions, AwsMavPermissions, AzurePermissions, AzureMavPermissions]) if __name__ == '__main__': main()
[ "logging.basicConfig", "pandas.read_csv", "json.dumps", "numpy.shape", "logging.info", "pathlib.Path", "requests.get", "requests.post" ]
[((118, 214), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': '"""logging_for_adding_group_permissions.log"""', 'level': 'logging.INFO'}), "(filename='logging_for_adding_group_permissions.log',\n level=logging.INFO)\n", (137, 214), False, 'import logging\n'), ((450, 474), 'logging.info', 'logging.info', (['log_string'], {}), '(log_string)\n', (462, 474), False, 'import logging\n'), ((592, 614), 'pandas.read_csv', 'pd.read_csv', (['file_name'], {}), '(file_name)\n', (603, 614), True, 'import pandas as pd\n'), ((746, 787), 'pandas.read_csv', 'pd.read_csv', (['AccountPermissions_file_name'], {}), '(AccountPermissions_file_name)\n', (757, 787), True, 'import pandas as pd\n'), ((1667, 1688), 'requests.get', 'requests.get', (['api_url'], {}), '(api_url)\n', (1679, 1688), False, 'import requests\n'), ((3853, 3966), 'json.dumps', 'json.dumps', (["{'group_id': group_id, 'use_account': group_permissions_input_row[2],\n 'acls': AccountPermissions}"], {}), "({'group_id': group_id, 'use_account':\n group_permissions_input_row[2], 'acls': AccountPermissions})\n", (3863, 3966), False, 'import json\n'), ((3973, 4093), 'requests.post', 'requests.post', (['api_url'], {'headers': "{'Content-Type': 'application/json', 'access_key': admin_api_key}", 'data': 'add_acl_info'}), "(api_url, headers={'Content-Type': 'application/json',\n 'access_key': admin_api_key}, data=add_acl_info)\n", (3986, 4093), False, 'import requests\n'), ((4806, 4820), 'json.dumps', 'json.dumps', (['{}'], {}), '({})\n', (4816, 4820), False, 'import json\n'), ((4831, 4953), 'requests.post', 'requests.post', (['api_url'], {'headers': "{'Content-Type': 'application/json', 'access_key': admin_api_key}", 'data': 'get_group_info'}), "(api_url, headers={'Content-Type': 'application/json',\n 'access_key': admin_api_key}, data=get_group_info)\n", (4844, 4953), False, 'import requests\n'), ((6587, 6608), 'requests.get', 'requests.get', (['api_url'], {}), '(api_url)\n', (6599, 6608), False, 'import requests\n'), ((10870, 10970), 'requests.get', 'requests.get', (['api_url'], {'headers': "{'Content-Type': 'application/json', 'access_key': admin_api_key}"}), "(api_url, headers={'Content-Type': 'application/json',\n 'access_key': admin_api_key})\n", (10882, 10970), False, 'import requests\n'), ((12355, 12370), 'pathlib.Path', 'Path', (['file_name'], {}), '(file_name)\n', (12359, 12370), False, 'from pathlib import Path\n'), ((12715, 12745), 'pathlib.Path', 'Path', (['AwsPermissions_file_name'], {}), '(AwsPermissions_file_name)\n', (12719, 12745), False, 'from pathlib import Path\n'), ((13038, 13071), 'pathlib.Path', 'Path', (['AwsMavPermissions_file_name'], {}), '(AwsMavPermissions_file_name)\n', (13042, 13071), False, 'from pathlib import Path\n'), ((13377, 13409), 'pathlib.Path', 'Path', (['AzurePermissions_file_name'], {}), '(AzurePermissions_file_name)\n', (13381, 13409), False, 'from pathlib import Path\n'), ((13727, 13762), 'pathlib.Path', 'Path', (['AzureMavPermissions_file_name'], {}), '(AzureMavPermissions_file_name)\n', (13731, 13762), False, 'from pathlib import Path\n'), ((843, 872), 'numpy.shape', 'np.shape', (['account_permissions'], {}), '(account_permissions)\n', (851, 872), True, 'import numpy as np\n'), ((1251, 1286), 'numpy.shape', 'np.shape', (['account_name_id_connector'], {}), '(account_name_id_connector)\n', (1259, 1286), True, 'import numpy as np\n'), ((6116, 6149), 'numpy.shape', 'np.shape', (['group_name_id_connector'], {}), '(group_name_id_connector)\n', (6124, 6149), True, 'import numpy as np\n'), ((8620, 8662), 'numpy.shape', 'np.shape', (['group_permissions_template_input'], {}), '(group_permissions_template_input)\n', (8628, 8662), True, 'import numpy as np\n'), ((6875, 6903), 'numpy.shape', 'np.shape', (['accounts_and_users'], {}), '(accounts_and_users)\n', (6883, 6903), True, 'import numpy as np\n')]
import torch import numpy as np import pandas as pd import torch.optim as optim from agents.common.logger import Logger from agents.common.replay_buffer import ReplayBuffer from agents.common.utils import quantile_huber_loss class EGreedyAgent(): def __init__(self,env, network, epsilon=0.05, n_quantiles=20, mean_prior=0, std_prior=0.01, logging=True, train_freq=10, updates_per_train=100, batch_size=32, start_train_step=10, log_folder_details=None, learning_rate=1e-3, verbose=False ): self.env = env self.network = network(env.n_features, n_quantiles, mean_prior, std_prior) self.logging = logging self.replay_buffer = ReplayBuffer() self.batch_size = batch_size self.log_folder_details = log_folder_details self.epsilon = epsilon self.optimizer = optim.Adam(self.network.parameters(), lr=learning_rate, eps=1e-8) self.n_quantiles = n_quantiles self.train_freq = train_freq self.start_train_step = start_train_step self.updates_per_train = updates_per_train self.verbose = verbose self.n_samples = 0 self.train_parameters = {'epsilon':epsilon, 'n_quantiles':n_quantiles, 'mean_prior':mean_prior, 'std_prior':std_prior, 'train_freq':train_freq, 'updates_per_train':updates_per_train, 'batch_size':batch_size, 'start_train_step':start_train_step, 'learning_rate':learning_rate } def learn(self,n_steps): self.train_parameters['n_steps']=n_steps if self.logging: self.logger = Logger(self.log_folder_details,self.train_parameters) cumulative_regret = 0 for timestep in range(n_steps): x = self.env.sample() action = self.act(x.float()) reward = self.env.hit(action) regret = self.env.regret(action) cumulative_regret += regret action = torch.as_tensor([action], dtype=torch.long) reward = torch.as_tensor([reward], dtype=torch.float) if action ==1: self.n_samples += 1 self.replay_buffer.add(x, reward) if self.logging: self.logger.add_scalar('Cumulative_Regret', cumulative_regret, timestep) self.logger.add_scalar('Mushrooms_Eaten', self.n_samples, timestep) if timestep % self.train_freq == 0 and self.n_samples > self.start_train_step: if self.verbose: print('Timestep: {}, cumulative regret {}'.format(str(timestep),str(cumulative_regret))) for update in range(self.updates_per_train): samples = self.replay_buffer.sample(np.min([self.n_samples,self.batch_size])) self.train_step(samples) if self.logging: self.logger.save() def train_step(self,samples): states, rewards = samples target = rewards.repeat(1,self.n_quantiles) q_value = self.network(states.float()).view(np.min([self.n_samples,self.batch_size]),self.n_quantiles) loss = quantile_huber_loss(q_value.squeeze(), target.squeeze()) self.optimizer.zero_grad() loss.backward() self.optimizer.step() def act(self,x): if np.random.uniform() >= self.epsilon: action = self.predict(x) else: action = np.random.randint(0, 2) return action @torch.no_grad() def predict(self,x): estimated_value = torch.mean(self.network(x)) if estimated_value > 0: action = 1 else: action = 0 return action
[ "numpy.random.uniform", "numpy.min", "numpy.random.randint", "torch.as_tensor", "agents.common.replay_buffer.ReplayBuffer", "torch.no_grad", "agents.common.logger.Logger" ]
[((3554, 3569), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3567, 3569), False, 'import torch\n'), ((719, 733), 'agents.common.replay_buffer.ReplayBuffer', 'ReplayBuffer', ([], {}), '()\n', (731, 733), False, 'from agents.common.replay_buffer import ReplayBuffer\n'), ((1680, 1734), 'agents.common.logger.Logger', 'Logger', (['self.log_folder_details', 'self.train_parameters'], {}), '(self.log_folder_details, self.train_parameters)\n', (1686, 1734), False, 'from agents.common.logger import Logger\n'), ((2034, 2077), 'torch.as_tensor', 'torch.as_tensor', (['[action]'], {'dtype': 'torch.long'}), '([action], dtype=torch.long)\n', (2049, 2077), False, 'import torch\n'), ((2099, 2143), 'torch.as_tensor', 'torch.as_tensor', (['[reward]'], {'dtype': 'torch.float'}), '([reward], dtype=torch.float)\n', (2114, 2143), False, 'import torch\n'), ((3135, 3176), 'numpy.min', 'np.min', (['[self.n_samples, self.batch_size]'], {}), '([self.n_samples, self.batch_size])\n', (3141, 3176), True, 'import numpy as np\n'), ((3393, 3412), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (3410, 3412), True, 'import numpy as np\n'), ((3502, 3525), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)'], {}), '(0, 2)\n', (3519, 3525), True, 'import numpy as np\n'), ((2815, 2856), 'numpy.min', 'np.min', (['[self.n_samples, self.batch_size]'], {}), '([self.n_samples, self.batch_size])\n', (2821, 2856), True, 'import numpy as np\n')]
""" NOTE: This file is not using to.testing.assert_allclose because most methods need to work for both torch and numpy. """ import pytest import numpy as np import torch as to import itertools import pickle from typing import NamedTuple from pyrado.algorithms.utils import ReplayMemory from pyrado.sampling.step_sequence import StepSequence from pyrado.sampling.data_format import to_format from pyrado.sampling.step_sequence import discounted_value, gae_returns from pyrado.sampling.rollout import rollout from pyrado.environments.pysim.ball_on_beam import BallOnBeamSim rewards = [ -200, -100, -50, -25, -17.5, ] # Observations has one additional element observations = [ np.array([3, 2, 7]), np.array([3, 1, 7]), np.array([2, 0, 7]), np.array([3, 1, 3]), np.array([0, 2, 4]), np.array([1, 1, 1]), ] # Actions come from PyTorch actions = [ to.tensor([0, 1]), to.tensor([0, 3]), to.tensor([2, 4]), to.tensor([3, 1]), to.tensor([0, 0]), ] # Policy infos as dict collapse test policy_infos = [ {'mean': np.array([0, 1]), 'std': 0.4}, {'mean': np.array([0, 3]), 'std': 0.2}, {'mean': np.array([2, 4]), 'std': 0.1}, {'mean': np.array([3, 1]), 'std': 0.05}, {'mean': np.array([0, 0]), 'std': 0.025}, ] # Hidden is a tuple, like we see with LSTMs hidden = [ (np.array([3, 2, 7]), np.array([2, 1])), (np.array([4, 9, 8]), np.array([5, 6])), (np.array([1, 4, 9]), np.array([7, 3])), (np.array([0, 8, 2]), np.array([4, 9])), (np.array([2, 7, 6]), np.array([8, 0])), ] def test_create_rew_only(): # Don't require additional fields for this test StepSequence.required_fields = {} ro = StepSequence(rewards=rewards, data_format='numpy') assert len(ro) == 5 assert (ro.rewards == np.array(rewards)).all() @pytest.mark.parametrize( 'data_format, tensor_type', [('numpy', np.ndarray), ('torch', to.Tensor)], ids=['numpy', 'torch'] ) def test_create(data_format, tensor_type): # With actions, observations and dicts ro = StepSequence(rewards=rewards, observations=observations, actions=actions, policy_infos=policy_infos, hidden=hidden, data_format=data_format) assert len(ro) == 5 assert isinstance(ro.rewards, tensor_type) assert isinstance(ro.observations, tensor_type) assert isinstance(ro.actions, tensor_type) assert isinstance(ro.policy_infos['mean'], tensor_type) assert isinstance(ro.policy_infos['std'], tensor_type) assert isinstance(ro.hidden[0], tensor_type) # Done should always be a ndarray assert isinstance(ro.done, np.ndarray) assert not ro.done[:-1].any() assert ro.done[-1] @pytest.mark.parametrize( 'other_format, tensor_type', [('torch', np.ndarray), ('numpy', to.Tensor)], ids=['numpy to torch', 'torch to numpy'] ) def test_convert(other_format, tensor_type): ro = StepSequence(rewards=rewards, observations=observations, actions=actions, policy_infos=policy_infos, hidden=hidden, data_format=other_format) # convert if other_format == 'numpy': ro.torch() elif other_format == 'torch': ro.numpy() # Verify assert isinstance(ro.rewards, tensor_type) assert isinstance(ro.observations, tensor_type) assert isinstance(ro.actions, tensor_type) assert isinstance(ro.policy_infos['mean'], tensor_type) assert isinstance(ro.policy_infos['std'], tensor_type) assert isinstance(ro.hidden[0], tensor_type) # Done should always be a ndarray assert isinstance(ro.done, np.ndarray) @pytest.mark.parametrize( 'data_format', ['numpy', 'torch'] ) def test_step_iter(data_format): ro = StepSequence(rewards=rewards, observations=observations, actions=actions, policy_infos=policy_infos, hidden=hidden, data_format=data_format) assert len(ro) == 5 for i, step in enumerate(ro): assert step.reward == rewards[i] # Check current and next assert (step.observation == to_format(observations[i], data_format)).all() assert (step.next_observation == to_format(observations[i + 1], data_format)).all() # Check dict sub element assert (step.policy_info.mean == to_format(policy_infos[i]['mean'], data_format)).all() assert (step.hidden[0] == to_format(hidden[i][0], data_format)).all() @pytest.mark.parametrize( 'sls', [slice(2, 4), slice(2, 5, 2), slice(3), slice(4, None)] ) @pytest.mark.parametrize( 'data_format', ['numpy', 'torch'] ) def test_slice(sls, data_format): ro = StepSequence(rewards=rewards, observations=observations, actions=actions, policy_infos=policy_infos, hidden=hidden, data_format=data_format) # Slice rollout sliced = ro[sls] # Slice reward list for verification sliced_rew = rewards[sls] for i, step in enumerate(sliced): assert step.reward == sliced_rew[i] @pytest.mark.parametrize( 'data_format', ['numpy', 'torch'] ) def test_add_data(data_format): ro = StepSequence( rewards=rewards, observations=observations, actions=actions, policy_infos=policy_infos, hidden=hidden, data_format=data_format ) # Add a data field ro.add_data('return', discounted_value(ro, 0.9)) assert hasattr(ro, 'return') # Query new data field from steps assert abs(ro[2]['return'] - -86.675) < 0.01 @pytest.mark.parametrize( 'data_format', ['numpy', 'torch'] ) def test_concat(data_format): # Create some rollouts with random rewards ros = [ StepSequence( rewards=np.random.randn(5), observations=np.random.randn(6), actions=np.random.randn(5), policy_infos={'mean': np.random.randn(5)}, hidden=(np.random.randn(5), np.random.randn(5)), data_format=data_format ), StepSequence( rewards=np.random.randn(5), observations=np.random.randn(6), actions=np.random.randn(5), policy_infos={'mean': np.random.randn(5)}, hidden=(np.random.randn(5), np.random.randn(5)), data_format=data_format ) ] # Perform concatenation cat = StepSequence.concat(ros) assert cat.continuous assert cat.rollout_count == 2 # Check steps for step_ro, step_cat in zip(itertools.chain.from_iterable(ros), cat): assert step_ro.reward == step_cat.reward assert step_ro.observation == step_cat.observation assert step_ro.done == step_cat.done @pytest.mark.parametrize( 'data_format', ['numpy', 'torch'] ) def test_split_multi(data_format): # Don't require additional fields for this test StepSequence.required_fields = {} ro = StepSequence( rewards=np.arange(20), rollout_bounds=[0, 4, 11, 17, 20], data_format=data_format ) # There should be four parts assert ro.rollout_count == 4 # Of these sizes assert list(ro.rollout_lengths) == [4, 7, 6, 3] # Test selecting one s1 = ro.get_rollout(1) assert s1.rollout_count == 1 assert s1[0].reward == ro[4].reward # Test selecting a slice s2 = ro.get_rollout(slice(1, -1)) assert s2.rollout_count == 2 assert s2[0].reward == ro[4].reward assert s2[7].reward == ro[11].reward # Test selecting by list s2 = ro.get_rollout([1, 3]) assert s2.rollout_count == 2 assert s2[0].reward == ro[4].reward assert s2[7].reward == ro[17].reward @pytest.mark.parametrize( 'data_format', ['numpy', 'torch'] ) def test_pickle(data_format): ro = StepSequence(rewards=rewards, observations=observations, actions=actions, policy_infos=policy_infos, hidden=hidden, data_format=data_format) # Pickle/unpickle ro2 = pickle.loads(pickle.dumps(ro, pickle.HIGHEST_PROTOCOL)) for step, step_pi in zip(ro, ro2): assert step.reward == step_pi.reward assert (step.observation == step_pi.observation).all() assert (step.action == step_pi.action).all() assert step.done == step_pi.done @pytest.mark.parametrize( 'env', [ BallOnBeamSim(dt=0.01, max_steps=200), ], ids=['bob_linpol'] ) def test_advantage_calculation(env, linear_policy): ro = rollout(env, linear_policy) gamma = 0.99 lamb = 0.95 # Add dummy values values = np.ones_like(ro.rewards) if not ro.done[-1]: values = to.cat([values, 0]) ro.add_data('values', values) gae1 = gae_returns(ro, gamma, lamb) # Compute the advantages gae2 = np.empty_like(values) for k in reversed(range(ro.length)): if ro[k].done: gae2[k] = ro[k].reward - values[k] else: gae2[k] = ro[k].reward + gamma*values[k + 1] - values[k] + \ gamma*lamb*gae2[k + 1] assert (gae1 == gae2).all() @pytest.mark.replay @pytest.mark.parametrize( 'capacity', [ 1, 2, 8, ], ids=['1', '2', '8'] ) def test_replay_memory(capacity): rm = ReplayMemory(capacity) # Create fake rollouts (of length 5) ro1 = StepSequence(rewards=rewards, observations=observations, actions=actions, hidden=hidden) ro2 = StepSequence(rewards=rewards, observations=observations, actions=actions, hidden=hidden) # Concatenate them for testing only ros = StepSequence.concat([ro1, ro2], truncate_last=True) # same truncate_last behavior as push function # Check the lengths rm.push(ro1) assert len(rm) == len(ro1) or len(rm) == capacity rm.push(ro2) assert len(rm) == len(ro1) + len(ro1) or len(rm) == capacity # Check the elements shift = len(ros) - capacity if shift < len(ro1): assert all(rm.memory.observations[0] == ros.observations[shift]) assert all(rm.memory.observations[-1] == ro2.observations[-2]) # -2 since one was truncated # A dummy namedtuple for testing class DummyNT(NamedTuple): part1: to.Tensor part2: to.Tensor @pytest.mark.parametrize( 'data_format', ['numpy', 'torch'] ) def test_namedtuple(data_format): hid_nt = [DummyNT(*it) for it in hidden] ro = StepSequence( rewards=rewards, hidden=hid_nt, data_format=data_format ) assert isinstance(ro.hidden, DummyNT) for i, step in enumerate(ro): assert isinstance(step.hidden, DummyNT) assert (step.hidden.part1 == to_format(hid_nt[i].part1, data_format)).all()
[ "pyrado.sampling.step_sequence.StepSequence.concat", "numpy.ones_like", "pyrado.algorithms.utils.ReplayMemory", "numpy.random.randn", "numpy.empty_like", "pyrado.sampling.step_sequence.StepSequence", "torch.cat", "pyrado.environments.pysim.ball_on_beam.BallOnBeamSim", "numpy.array", "pyrado.sampling.step_sequence.gae_returns", "numpy.arange", "pyrado.sampling.data_format.to_format", "pyrado.sampling.rollout.rollout", "pytest.mark.parametrize", "pyrado.sampling.step_sequence.discounted_value", "itertools.chain.from_iterable", "torch.tensor", "pickle.dumps" ]
[((1826, 1952), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""data_format, tensor_type"""', "[('numpy', np.ndarray), ('torch', to.Tensor)]"], {'ids': "['numpy', 'torch']"}), "('data_format, tensor_type', [('numpy', np.ndarray),\n ('torch', to.Tensor)], ids=['numpy', 'torch'])\n", (1849, 1952), False, 'import pytest\n'), ((2694, 2839), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""other_format, tensor_type"""', "[('torch', np.ndarray), ('numpy', to.Tensor)]"], {'ids': "['numpy to torch', 'torch to numpy']"}), "('other_format, tensor_type', [('torch', np.ndarray),\n ('numpy', to.Tensor)], ids=['numpy to torch', 'torch to numpy'])\n", (2717, 2839), False, 'import pytest\n'), ((3594, 3652), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""data_format"""', "['numpy', 'torch']"], {}), "('data_format', ['numpy', 'torch'])\n", (3617, 3652), False, 'import pytest\n'), ((4478, 4536), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""data_format"""', "['numpy', 'torch']"], {}), "('data_format', ['numpy', 'torch'])\n", (4501, 4536), False, 'import pytest\n'), ((4948, 5006), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""data_format"""', "['numpy', 'torch']"], {}), "('data_format', ['numpy', 'torch'])\n", (4971, 5006), False, 'import pytest\n'), ((5449, 5507), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""data_format"""', "['numpy', 'torch']"], {}), "('data_format', ['numpy', 'torch'])\n", (5472, 5507), False, 'import pytest\n'), ((6603, 6661), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""data_format"""', "['numpy', 'torch']"], {}), "('data_format', ['numpy', 'torch'])\n", (6626, 6661), False, 'import pytest\n'), ((7556, 7614), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""data_format"""', "['numpy', 'torch']"], {}), "('data_format', ['numpy', 'torch'])\n", (7579, 7614), False, 'import pytest\n'), ((8952, 9019), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""capacity"""', '[1, 2, 8]'], {'ids': "['1', '2', '8']"}), "('capacity', [1, 2, 8], ids=['1', '2', '8'])\n", (8975, 9019), False, 'import pytest\n'), ((10035, 10093), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""data_format"""', "['numpy', 'torch']"], {}), "('data_format', ['numpy', 'torch'])\n", (10058, 10093), False, 'import pytest\n'), ((701, 720), 'numpy.array', 'np.array', (['[3, 2, 7]'], {}), '([3, 2, 7])\n', (709, 720), True, 'import numpy as np\n'), ((726, 745), 'numpy.array', 'np.array', (['[3, 1, 7]'], {}), '([3, 1, 7])\n', (734, 745), True, 'import numpy as np\n'), ((751, 770), 'numpy.array', 'np.array', (['[2, 0, 7]'], {}), '([2, 0, 7])\n', (759, 770), True, 'import numpy as np\n'), ((776, 795), 'numpy.array', 'np.array', (['[3, 1, 3]'], {}), '([3, 1, 3])\n', (784, 795), True, 'import numpy as np\n'), ((801, 820), 'numpy.array', 'np.array', (['[0, 2, 4]'], {}), '([0, 2, 4])\n', (809, 820), True, 'import numpy as np\n'), ((826, 845), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (834, 845), True, 'import numpy as np\n'), ((893, 910), 'torch.tensor', 'to.tensor', (['[0, 1]'], {}), '([0, 1])\n', (902, 910), True, 'import torch as to\n'), ((916, 933), 'torch.tensor', 'to.tensor', (['[0, 3]'], {}), '([0, 3])\n', (925, 933), True, 'import torch as to\n'), ((939, 956), 'torch.tensor', 'to.tensor', (['[2, 4]'], {}), '([2, 4])\n', (948, 956), True, 'import torch as to\n'), ((962, 979), 'torch.tensor', 'to.tensor', (['[3, 1]'], {}), '([3, 1])\n', (971, 979), True, 'import torch as to\n'), ((985, 1002), 'torch.tensor', 'to.tensor', (['[0, 0]'], {}), '([0, 0])\n', (994, 1002), True, 'import torch as to\n'), ((1697, 1747), 'pyrado.sampling.step_sequence.StepSequence', 'StepSequence', ([], {'rewards': 'rewards', 'data_format': '"""numpy"""'}), "(rewards=rewards, data_format='numpy')\n", (1709, 1747), False, 'from pyrado.sampling.step_sequence import StepSequence\n'), ((2050, 2194), 'pyrado.sampling.step_sequence.StepSequence', 'StepSequence', ([], {'rewards': 'rewards', 'observations': 'observations', 'actions': 'actions', 'policy_infos': 'policy_infos', 'hidden': 'hidden', 'data_format': 'data_format'}), '(rewards=rewards, observations=observations, actions=actions,\n policy_infos=policy_infos, hidden=hidden, data_format=data_format)\n', (2062, 2194), False, 'from pyrado.sampling.step_sequence import StepSequence\n'), ((2900, 3045), 'pyrado.sampling.step_sequence.StepSequence', 'StepSequence', ([], {'rewards': 'rewards', 'observations': 'observations', 'actions': 'actions', 'policy_infos': 'policy_infos', 'hidden': 'hidden', 'data_format': 'other_format'}), '(rewards=rewards, observations=observations, actions=actions,\n policy_infos=policy_infos, hidden=hidden, data_format=other_format)\n', (2912, 3045), False, 'from pyrado.sampling.step_sequence import StepSequence\n'), ((3701, 3845), 'pyrado.sampling.step_sequence.StepSequence', 'StepSequence', ([], {'rewards': 'rewards', 'observations': 'observations', 'actions': 'actions', 'policy_infos': 'policy_infos', 'hidden': 'hidden', 'data_format': 'data_format'}), '(rewards=rewards, observations=observations, actions=actions,\n policy_infos=policy_infos, hidden=hidden, data_format=data_format)\n', (3713, 3845), False, 'from pyrado.sampling.step_sequence import StepSequence\n'), ((4586, 4730), 'pyrado.sampling.step_sequence.StepSequence', 'StepSequence', ([], {'rewards': 'rewards', 'observations': 'observations', 'actions': 'actions', 'policy_infos': 'policy_infos', 'hidden': 'hidden', 'data_format': 'data_format'}), '(rewards=rewards, observations=observations, actions=actions,\n policy_infos=policy_infos, hidden=hidden, data_format=data_format)\n', (4598, 4730), False, 'from pyrado.sampling.step_sequence import StepSequence\n'), ((5054, 5198), 'pyrado.sampling.step_sequence.StepSequence', 'StepSequence', ([], {'rewards': 'rewards', 'observations': 'observations', 'actions': 'actions', 'policy_infos': 'policy_infos', 'hidden': 'hidden', 'data_format': 'data_format'}), '(rewards=rewards, observations=observations, actions=actions,\n policy_infos=policy_infos, hidden=hidden, data_format=data_format)\n', (5066, 5198), False, 'from pyrado.sampling.step_sequence import StepSequence\n'), ((6267, 6291), 'pyrado.sampling.step_sequence.StepSequence.concat', 'StepSequence.concat', (['ros'], {}), '(ros)\n', (6286, 6291), False, 'from pyrado.sampling.step_sequence import StepSequence\n'), ((7660, 7804), 'pyrado.sampling.step_sequence.StepSequence', 'StepSequence', ([], {'rewards': 'rewards', 'observations': 'observations', 'actions': 'actions', 'policy_infos': 'policy_infos', 'hidden': 'hidden', 'data_format': 'data_format'}), '(rewards=rewards, observations=observations, actions=actions,\n policy_infos=policy_infos, hidden=hidden, data_format=data_format)\n', (7672, 7804), False, 'from pyrado.sampling.step_sequence import StepSequence\n'), ((8331, 8358), 'pyrado.sampling.rollout.rollout', 'rollout', (['env', 'linear_policy'], {}), '(env, linear_policy)\n', (8338, 8358), False, 'from pyrado.sampling.rollout import rollout\n'), ((8429, 8453), 'numpy.ones_like', 'np.ones_like', (['ro.rewards'], {}), '(ro.rewards)\n', (8441, 8453), True, 'import numpy as np\n'), ((8561, 8589), 'pyrado.sampling.step_sequence.gae_returns', 'gae_returns', (['ro', 'gamma', 'lamb'], {}), '(ro, gamma, lamb)\n', (8572, 8589), False, 'from pyrado.sampling.step_sequence import discounted_value, gae_returns\n'), ((8631, 8652), 'numpy.empty_like', 'np.empty_like', (['values'], {}), '(values)\n', (8644, 8652), True, 'import numpy as np\n'), ((9084, 9106), 'pyrado.algorithms.utils.ReplayMemory', 'ReplayMemory', (['capacity'], {}), '(capacity)\n', (9096, 9106), False, 'from pyrado.algorithms.utils import ReplayMemory\n'), ((9159, 9251), 'pyrado.sampling.step_sequence.StepSequence', 'StepSequence', ([], {'rewards': 'rewards', 'observations': 'observations', 'actions': 'actions', 'hidden': 'hidden'}), '(rewards=rewards, observations=observations, actions=actions,\n hidden=hidden)\n', (9171, 9251), False, 'from pyrado.sampling.step_sequence import StepSequence\n'), ((9258, 9350), 'pyrado.sampling.step_sequence.StepSequence', 'StepSequence', ([], {'rewards': 'rewards', 'observations': 'observations', 'actions': 'actions', 'hidden': 'hidden'}), '(rewards=rewards, observations=observations, actions=actions,\n hidden=hidden)\n', (9270, 9350), False, 'from pyrado.sampling.step_sequence import StepSequence\n'), ((9397, 9448), 'pyrado.sampling.step_sequence.StepSequence.concat', 'StepSequence.concat', (['[ro1, ro2]'], {'truncate_last': '(True)'}), '([ro1, ro2], truncate_last=True)\n', (9416, 9448), False, 'from pyrado.sampling.step_sequence import StepSequence\n'), ((10189, 10258), 'pyrado.sampling.step_sequence.StepSequence', 'StepSequence', ([], {'rewards': 'rewards', 'hidden': 'hid_nt', 'data_format': 'data_format'}), '(rewards=rewards, hidden=hid_nt, data_format=data_format)\n', (10201, 10258), False, 'from pyrado.sampling.step_sequence import StepSequence\n'), ((1073, 1089), 'numpy.array', 'np.array', (['[0, 1]'], {}), '([0, 1])\n', (1081, 1089), True, 'import numpy as np\n'), ((1117, 1133), 'numpy.array', 'np.array', (['[0, 3]'], {}), '([0, 3])\n', (1125, 1133), True, 'import numpy as np\n'), ((1161, 1177), 'numpy.array', 'np.array', (['[2, 4]'], {}), '([2, 4])\n', (1169, 1177), True, 'import numpy as np\n'), ((1205, 1221), 'numpy.array', 'np.array', (['[3, 1]'], {}), '([3, 1])\n', (1213, 1221), True, 'import numpy as np\n'), ((1250, 1266), 'numpy.array', 'np.array', (['[0, 0]'], {}), '([0, 0])\n', (1258, 1266), True, 'import numpy as np\n'), ((1345, 1364), 'numpy.array', 'np.array', (['[3, 2, 7]'], {}), '([3, 2, 7])\n', (1353, 1364), True, 'import numpy as np\n'), ((1366, 1382), 'numpy.array', 'np.array', (['[2, 1]'], {}), '([2, 1])\n', (1374, 1382), True, 'import numpy as np\n'), ((1390, 1409), 'numpy.array', 'np.array', (['[4, 9, 8]'], {}), '([4, 9, 8])\n', (1398, 1409), True, 'import numpy as np\n'), ((1411, 1427), 'numpy.array', 'np.array', (['[5, 6]'], {}), '([5, 6])\n', (1419, 1427), True, 'import numpy as np\n'), ((1435, 1454), 'numpy.array', 'np.array', (['[1, 4, 9]'], {}), '([1, 4, 9])\n', (1443, 1454), True, 'import numpy as np\n'), ((1456, 1472), 'numpy.array', 'np.array', (['[7, 3]'], {}), '([7, 3])\n', (1464, 1472), True, 'import numpy as np\n'), ((1480, 1499), 'numpy.array', 'np.array', (['[0, 8, 2]'], {}), '([0, 8, 2])\n', (1488, 1499), True, 'import numpy as np\n'), ((1501, 1517), 'numpy.array', 'np.array', (['[4, 9]'], {}), '([4, 9])\n', (1509, 1517), True, 'import numpy as np\n'), ((1525, 1544), 'numpy.array', 'np.array', (['[2, 7, 6]'], {}), '([2, 7, 6])\n', (1533, 1544), True, 'import numpy as np\n'), ((1546, 1562), 'numpy.array', 'np.array', (['[8, 0]'], {}), '([8, 0])\n', (1554, 1562), True, 'import numpy as np\n'), ((5298, 5323), 'pyrado.sampling.step_sequence.discounted_value', 'discounted_value', (['ro', '(0.9)'], {}), '(ro, 0.9)\n', (5314, 5323), False, 'from pyrado.sampling.step_sequence import discounted_value, gae_returns\n'), ((6405, 6439), 'itertools.chain.from_iterable', 'itertools.chain.from_iterable', (['ros'], {}), '(ros)\n', (6434, 6439), False, 'import itertools\n'), ((7869, 7910), 'pickle.dumps', 'pickle.dumps', (['ro', 'pickle.HIGHEST_PROTOCOL'], {}), '(ro, pickle.HIGHEST_PROTOCOL)\n', (7881, 7910), False, 'import pickle\n'), ((8495, 8514), 'torch.cat', 'to.cat', (['[values, 0]'], {}), '([values, 0])\n', (8501, 8514), True, 'import torch as to\n'), ((8203, 8240), 'pyrado.environments.pysim.ball_on_beam.BallOnBeamSim', 'BallOnBeamSim', ([], {'dt': '(0.01)', 'max_steps': '(200)'}), '(dt=0.01, max_steps=200)\n', (8216, 8240), False, 'from pyrado.environments.pysim.ball_on_beam import BallOnBeamSim\n'), ((6833, 6846), 'numpy.arange', 'np.arange', (['(20)'], {}), '(20)\n', (6842, 6846), True, 'import numpy as np\n'), ((1798, 1815), 'numpy.array', 'np.array', (['rewards'], {}), '(rewards)\n', (1806, 1815), True, 'import numpy as np\n'), ((5645, 5663), 'numpy.random.randn', 'np.random.randn', (['(5)'], {}), '(5)\n', (5660, 5663), True, 'import numpy as np\n'), ((5690, 5708), 'numpy.random.randn', 'np.random.randn', (['(6)'], {}), '(6)\n', (5705, 5708), True, 'import numpy as np\n'), ((5730, 5748), 'numpy.random.randn', 'np.random.randn', (['(5)'], {}), '(5)\n', (5745, 5748), True, 'import numpy as np\n'), ((5955, 5973), 'numpy.random.randn', 'np.random.randn', (['(5)'], {}), '(5)\n', (5970, 5973), True, 'import numpy as np\n'), ((6000, 6018), 'numpy.random.randn', 'np.random.randn', (['(6)'], {}), '(6)\n', (6015, 6018), True, 'import numpy as np\n'), ((6040, 6058), 'numpy.random.randn', 'np.random.randn', (['(5)'], {}), '(5)\n', (6055, 6058), True, 'import numpy as np\n'), ((4034, 4073), 'pyrado.sampling.data_format.to_format', 'to_format', (['observations[i]', 'data_format'], {}), '(observations[i], data_format)\n', (4043, 4073), False, 'from pyrado.sampling.data_format import to_format\n'), ((4122, 4165), 'pyrado.sampling.data_format.to_format', 'to_format', (['observations[i + 1]', 'data_format'], {}), '(observations[i + 1], data_format)\n', (4131, 4165), False, 'from pyrado.sampling.data_format import to_format\n'), ((4247, 4294), 'pyrado.sampling.data_format.to_format', 'to_format', (["policy_infos[i]['mean']", 'data_format'], {}), "(policy_infos[i]['mean'], data_format)\n", (4256, 4294), False, 'from pyrado.sampling.data_format import to_format\n'), ((4336, 4372), 'pyrado.sampling.data_format.to_format', 'to_format', (['hidden[i][0]', 'data_format'], {}), '(hidden[i][0], data_format)\n', (4345, 4372), False, 'from pyrado.sampling.data_format import to_format\n'), ((5784, 5802), 'numpy.random.randn', 'np.random.randn', (['(5)'], {}), '(5)\n', (5799, 5802), True, 'import numpy as np\n'), ((5825, 5843), 'numpy.random.randn', 'np.random.randn', (['(5)'], {}), '(5)\n', (5840, 5843), True, 'import numpy as np\n'), ((5845, 5863), 'numpy.random.randn', 'np.random.randn', (['(5)'], {}), '(5)\n', (5860, 5863), True, 'import numpy as np\n'), ((6094, 6112), 'numpy.random.randn', 'np.random.randn', (['(5)'], {}), '(5)\n', (6109, 6112), True, 'import numpy as np\n'), ((6135, 6153), 'numpy.random.randn', 'np.random.randn', (['(5)'], {}), '(5)\n', (6150, 6153), True, 'import numpy as np\n'), ((6155, 6173), 'numpy.random.randn', 'np.random.randn', (['(5)'], {}), '(5)\n', (6170, 6173), True, 'import numpy as np\n'), ((10452, 10491), 'pyrado.sampling.data_format.to_format', 'to_format', (['hid_nt[i].part1', 'data_format'], {}), '(hid_nt[i].part1, data_format)\n', (10461, 10491), False, 'from pyrado.sampling.data_format import to_format\n')]
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test Gaussian """ import unittest from test import QiskitMachineLearningTestCase from test.datasets import get_deprecated_msg_ref import warnings import numpy as np from qiskit_machine_learning.datasets import gaussian class TestGaussian(QiskitMachineLearningTestCase): """Gaussian tests.""" def test_gaussian(self): """Gaussian test.""" with warnings.catch_warnings(record=True) as c_m: warnings.simplefilter("always") training_features, training_labels, test_features, test_labels = gaussian( training_size=20, test_size=10, n=2, plot_data=False ) with self.subTest("Test training_features"): np.testing.assert_array_equal(training_features.shape, (40, 2)) with self.subTest("Test training_labels1"): np.testing.assert_array_equal(training_labels.shape, (40, 2)) with self.subTest("Test training_labels2"): np.testing.assert_array_equal(np.sum(training_labels, axis=0), np.array([20, 20])) with self.subTest("Test training_labels3"): np.testing.assert_array_equal(np.sum(training_labels, axis=1), np.ones(40)) with self.subTest("Test features.shape1"): np.testing.assert_array_equal(test_features.shape, (20, 2)) with self.subTest("Test features.shape2"): np.testing.assert_array_equal(test_features.shape, (20, 2)) with self.subTest("Test test_labels1"): np.testing.assert_array_equal(np.sum(test_labels, axis=0), np.array([10, 10])) with self.subTest("Test test_labels2"): np.testing.assert_array_equal(np.sum(test_labels, axis=1), np.ones(20)) with self.subTest("Test deprecation msg"): msg = str(c_m[0].message) self.assertEqual(msg, get_deprecated_msg_ref("gaussian")) if __name__ == "__main__": unittest.main()
[ "unittest.main", "numpy.sum", "warnings.simplefilter", "test.datasets.get_deprecated_msg_ref", "numpy.testing.assert_array_equal", "numpy.ones", "warnings.catch_warnings", "numpy.array", "qiskit_machine_learning.datasets.gaussian" ]
[((2435, 2450), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2448, 2450), False, 'import unittest\n'), ((860, 896), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (883, 896), False, 'import warnings\n'), ((917, 948), 'warnings.simplefilter', 'warnings.simplefilter', (['"""always"""'], {}), "('always')\n", (938, 948), False, 'import warnings\n'), ((1026, 1088), 'qiskit_machine_learning.datasets.gaussian', 'gaussian', ([], {'training_size': '(20)', 'test_size': '(10)', 'n': '(2)', 'plot_data': '(False)'}), '(training_size=20, test_size=10, n=2, plot_data=False)\n', (1034, 1088), False, 'from qiskit_machine_learning.datasets import gaussian\n'), ((1192, 1255), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['training_features.shape', '(40, 2)'], {}), '(training_features.shape, (40, 2))\n', (1221, 1255), True, 'import numpy as np\n'), ((1328, 1389), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['training_labels.shape', '(40, 2)'], {}), '(training_labels.shape, (40, 2))\n', (1357, 1389), True, 'import numpy as np\n'), ((1764, 1823), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['test_features.shape', '(20, 2)'], {}), '(test_features.shape, (20, 2))\n', (1793, 1823), True, 'import numpy as np\n'), ((1895, 1954), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['test_features.shape', '(20, 2)'], {}), '(test_features.shape, (20, 2))\n', (1924, 1954), True, 'import numpy as np\n'), ((2366, 2400), 'test.datasets.get_deprecated_msg_ref', 'get_deprecated_msg_ref', (['"""gaussian"""'], {}), "('gaussian')\n", (2388, 2400), False, 'from test.datasets import get_deprecated_msg_ref\n'), ((1492, 1523), 'numpy.sum', 'np.sum', (['training_labels'], {'axis': '(0)'}), '(training_labels, axis=0)\n', (1498, 1523), True, 'import numpy as np\n'), ((1525, 1543), 'numpy.array', 'np.array', (['[20, 20]'], {}), '([20, 20])\n', (1533, 1543), True, 'import numpy as np\n'), ((1647, 1678), 'numpy.sum', 'np.sum', (['training_labels'], {'axis': '(1)'}), '(training_labels, axis=1)\n', (1653, 1678), True, 'import numpy as np\n'), ((1680, 1691), 'numpy.ones', 'np.ones', (['(40)'], {}), '(40)\n', (1687, 1691), True, 'import numpy as np\n'), ((2053, 2080), 'numpy.sum', 'np.sum', (['test_labels'], {'axis': '(0)'}), '(test_labels, axis=0)\n', (2059, 2080), True, 'import numpy as np\n'), ((2082, 2100), 'numpy.array', 'np.array', (['[10, 10]'], {}), '([10, 10])\n', (2090, 2100), True, 'import numpy as np\n'), ((2200, 2227), 'numpy.sum', 'np.sum', (['test_labels'], {'axis': '(1)'}), '(test_labels, axis=1)\n', (2206, 2227), True, 'import numpy as np\n'), ((2229, 2240), 'numpy.ones', 'np.ones', (['(20)'], {}), '(20)\n', (2236, 2240), True, 'import numpy as np\n')]
from keras.datasets import boston_housing from keras import models, layers import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt print("获取数据集") (train_data, train_targets), (test_data, test_targets) = boston_housing.load_data() print("训练数据大小", train_data.shape) print("测试数据大小", test_data.shape) print("训练目标是房屋价格中位数,单位是千美元") print(train_targets) print("标准化数据,特征的平均值为 0,标准差为 1") mean = train_data.mean(axis=0) train_data -= mean std = train_data.std(axis=0) train_data /= std print("在工作流程中,不能使用在测试数据上计算得到的任何结果,标准化也不行") test_data -= mean test_data /= std print("构建网络,较小的网络可以降低过拟合") print("MSE - 均方误差,回归问题常用") print("MAE - 平均绝对误差,比如 MAE 0.5 在这里意味着平均价格相差 500 美元") def build_model(): model = models.Sequential() model.add(layers.Dense(64, activation='relu', input_shape=(train_data.shape[1], ))) model.add(layers.Dense(64, activation='relu')) model.add(layers.Dense(1)) model.compile(optimizer='rmsprop', loss='mse', metrics=['mae']) return model print("在小样本上利用 K Fold 验证") k = 4 num_val_samples = len(train_data) // k num_epochs = 500 all_mae_histories = [] for i in range(k): print("处理 Fold #", i) val_start = i * num_val_samples val_end = val_start + num_val_samples # 验证数据 val_data = train_data[val_start: val_end] val_targets = train_targets[val_start: val_end] # 训练数据 partial_train_data = np.concatenate( [train_data[:val_start], train_data[val_end:]],axis=0) partial_train_targets = np.concatenate( [train_targets[:val_start], train_targets[val_end:]],axis=0) model = build_model() history = model.fit(partial_train_data, partial_train_targets, validation_data=(val_data, val_targets), epochs=num_epochs, batch_size=1, verbose=0) mae_history = history.history['val_mean_absolute_error'] all_mae_histories.append(mae_history) print("计算所有轮次中 K 折验证分数平均值") average_mae_history = [np.mean([x[i] for x in all_mae_histories]) for i in range(num_epochs)] print("绘制验证分数") plt.plot(range(1, len(average_mae_history) + 1), average_mae_history) plt.xlabel('Epochs') plt.ylabel('Validation MAE') plt.show() print("重新绘制以看清规律。删除前十个点;将每个数据点替换为前面数据点的指数移动平均值") def smooth_curve(points, factor=0.9): smoothed_points = [] for point in points: if smoothed_points: previous = smoothed_points[-1] smoothed_points.append(previous * factor + point * (1 - factor)) else: smoothed_points.append(point) return smoothed_points smooth_mae_history = smooth_curve(average_mae_history[10:]) plt.clf() plt.plot(range(1, len(smooth_mae_history) + 1), smooth_mae_history) plt.xlabel('Epochs') plt.ylabel('Validation MAE after Smoothing') plt.show() print("从图中可得 MAE 在 80 轮后不再降低,之后开始过拟合") print("重新训练") model = build_model() model.fit(train_data, train_targets, epochs=80, batch_size=16, verbose=0) test_mse_score, test_mae_score = model.evaluate(test_data, test_targets) print("Test MSE", test_mse_score) print("Test MAE", test_mae_score)
[ "matplotlib.pyplot.show", "matplotlib.pyplot.clf", "keras.models.Sequential", "matplotlib.use", "numpy.mean", "keras.layers.Dense", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "numpy.concatenate", "keras.datasets.boston_housing.load_data" ]
[((113, 136), 'matplotlib.use', 'matplotlib.use', (['"""TkAgg"""'], {}), "('TkAgg')\n", (127, 136), False, 'import matplotlib\n'), ((242, 268), 'keras.datasets.boston_housing.load_data', 'boston_housing.load_data', ([], {}), '()\n', (266, 268), False, 'from keras.datasets import boston_housing\n'), ((2150, 2170), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epochs"""'], {}), "('Epochs')\n", (2160, 2170), True, 'import matplotlib.pyplot as plt\n'), ((2171, 2199), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Validation MAE"""'], {}), "('Validation MAE')\n", (2181, 2199), True, 'import matplotlib.pyplot as plt\n'), ((2200, 2210), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2208, 2210), True, 'import matplotlib.pyplot as plt\n'), ((2641, 2650), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (2648, 2650), True, 'import matplotlib.pyplot as plt\n'), ((2719, 2739), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epochs"""'], {}), "('Epochs')\n", (2729, 2739), True, 'import matplotlib.pyplot as plt\n'), ((2740, 2784), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Validation MAE after Smoothing"""'], {}), "('Validation MAE after Smoothing')\n", (2750, 2784), True, 'import matplotlib.pyplot as plt\n'), ((2785, 2795), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2793, 2795), True, 'import matplotlib.pyplot as plt\n'), ((733, 752), 'keras.models.Sequential', 'models.Sequential', ([], {}), '()\n', (750, 752), False, 'from keras import models, layers\n'), ((1390, 1460), 'numpy.concatenate', 'np.concatenate', (['[train_data[:val_start], train_data[val_end:]]'], {'axis': '(0)'}), '([train_data[:val_start], train_data[val_end:]], axis=0)\n', (1404, 1460), True, 'import numpy as np\n'), ((1505, 1581), 'numpy.concatenate', 'np.concatenate', (['[train_targets[:val_start], train_targets[val_end:]]'], {'axis': '(0)'}), '([train_targets[:val_start], train_targets[val_end:]], axis=0)\n', (1519, 1581), True, 'import numpy as np\n'), ((1993, 2035), 'numpy.mean', 'np.mean', (['[x[i] for x in all_mae_histories]'], {}), '([x[i] for x in all_mae_histories])\n', (2000, 2035), True, 'import numpy as np\n'), ((767, 838), 'keras.layers.Dense', 'layers.Dense', (['(64)'], {'activation': '"""relu"""', 'input_shape': '(train_data.shape[1],)'}), "(64, activation='relu', input_shape=(train_data.shape[1],))\n", (779, 838), False, 'from keras import models, layers\n'), ((855, 890), 'keras.layers.Dense', 'layers.Dense', (['(64)'], {'activation': '"""relu"""'}), "(64, activation='relu')\n", (867, 890), False, 'from keras import models, layers\n'), ((906, 921), 'keras.layers.Dense', 'layers.Dense', (['(1)'], {}), '(1)\n', (918, 921), False, 'from keras import models, layers\n')]
import numpy as np import re def extract(filename1,filename2): input_file = open(filename1) output_file = open(filename2) data = input_file.readlines() out_data = output_file.readlines() """ Number of training data records """ ntrain = int(data[0].split()[0]) traindata = data[1:ntrain+1] """ Number of test data records """ ntest = int(data[int(data[0].split()[0])+1]) testdata = data[ntrain+2:ntrain+ntest+2] features = [] labels = [] test_labels = [] test_features = [] for line in traindata: formatted_line = line.strip("\n") labels.append(formatted_line.split(" ")[1]) features.append(re.sub(r"(\d+):", "", formatted_line).split(" ")[2:]) features = np.array(features).astype(np.float) labels = np.array(labels).astype(np.int) for lines in testdata: formatted_lines = lines.strip("\n") test_features.append(re.sub(r"(\d+):", "", formatted_lines).split(" ")[1:]) for lines in out_data: test_labels.append(lines.split()[1]) test_features = np.array(test_features).astype(np.float) test_labels = np.array(test_labels).astype(np.int) return features,labels,test_features,test_labels
[ "numpy.array", "re.sub" ]
[((770, 788), 'numpy.array', 'np.array', (['features'], {}), '(features)\n', (778, 788), True, 'import numpy as np\n'), ((819, 835), 'numpy.array', 'np.array', (['labels'], {}), '(labels)\n', (827, 835), True, 'import numpy as np\n'), ((1115, 1138), 'numpy.array', 'np.array', (['test_features'], {}), '(test_features)\n', (1123, 1138), True, 'import numpy as np\n'), ((1174, 1195), 'numpy.array', 'np.array', (['test_labels'], {}), '(test_labels)\n', (1182, 1195), True, 'import numpy as np\n'), ((696, 733), 're.sub', 're.sub', (['"""(\\\\d+):"""', '""""""', 'formatted_line'], {}), "('(\\\\d+):', '', formatted_line)\n", (702, 733), False, 'import re\n'), ((956, 994), 're.sub', 're.sub', (['"""(\\\\d+):"""', '""""""', 'formatted_lines'], {}), "('(\\\\d+):', '', formatted_lines)\n", (962, 994), False, 'import re\n')]
import cv2 import numpy as np import copy import imgaug.augmenters as iaa from . import pallete_aug as pa def pallete_augmentation(img, img_data, config): if config.pallete: csv_path = img_data['csvpath'] #Exception none value. if csv_path is None or '': print("CSV path is {}".format(csv_path)) return img data = pa.open_path_array(csv_path) #Preprocessing pa.getHistogram(data, percentile=75) normalizedImg = pa.normalize_thermal(data) pa.getHistogram(normalizedImg, percentile=75) # getHistogram(normalizedImg) img = pa.heatMapConvert(normalizedImg,bboxes=None, specific_cm=None, tool='matplot', is_random=True) # img= pa.heatMapConvert(normalizedImg, bboxes=img_data['bboxes'], # specific_cm=None, # tool='matplot', # is_random=True) return img def augment(img_data, config, augment=True): assert 'filepath' in img_data assert 'bboxes' in img_data assert 'width' in img_data assert 'height' in img_data img_data_aug = copy.deepcopy(img_data) aug_list = [] img = cv2.imread(img_data_aug['filepath']) if augment: rows, cols = img.shape[:2] #[START] Pallete Augmentation pallete_augmentation(img =img, img_data = img_data_aug, config=config) #[END] Pallete Augmentation if config.use_horizontal_flips and np.random.randint(0, 2) == 0: img = cv2.flip(img, 1) for bbox in img_data_aug['bboxes']: x1 = bbox['x1'] x2 = bbox['x2'] bbox['x2'] = cols - x1 bbox['x1'] = cols - x2 if config.use_vertical_flips and np.random.randint(0, 2) == 0: img = cv2.flip(img, 0) for bbox in img_data_aug['bboxes']: y1 = bbox['y1'] y2 = bbox['y2'] bbox['y2'] = rows - y1 bbox['y1'] = rows - y2 if config.rot_90: angle = np.random.choice([0,90,180,270],1)[0] if angle == 270: img = np.transpose(img, (1,0,2)) img = cv2.flip(img, 0) elif angle == 180: img = cv2.flip(img, -1) elif angle == 90: img = np.transpose(img, (1,0,2)) img = cv2.flip(img, 1) elif angle == 0: pass for bbox in img_data_aug['bboxes']: x1 = bbox['x1'] x2 = bbox['x2'] y1 = bbox['y1'] y2 = bbox['y2'] if angle == 270: bbox['x1'] = y1 bbox['x2'] = y2 bbox['y1'] = cols - x2 bbox['y2'] = cols - x1 elif angle == 180: bbox['x2'] = cols - x1 bbox['x1'] = cols - x2 bbox['y2'] = rows - y1 bbox['y1'] = rows - y2 elif angle == 90: bbox['x1'] = rows - y2 bbox['x2'] = rows - y1 bbox['y1'] = x1 bbox['y2'] = x2 elif angle == 0: pass if config.color: aug_list.append(np.random.choice([iaa.MultiplyHueAndSaturation((0.5, 1.5), per_channel=True), iaa.AddToHueAndSaturation((-50, 50), per_channel=True), iaa.KMeansColorQuantization(), iaa.UniformColorQuantization(), iaa.Grayscale(alpha=(0.0, 1.0))])) if config.contrast: aug_list.append(np.random.choice([iaa.GammaContrast((0.5, 2.0), per_channel=True), iaa.SigmoidContrast(gain=(3, 10), cutoff=(0.4, 0.6),per_channel=True), iaa.LogContrast(gain=(0.6, 1.4), per_channel=True), iaa.LinearContrast((0.4, 1.6), per_channel=True), iaa.AllChannelsCLAHE(clip_limit=(1, 10), per_channel=True), iaa.AllChannelsHistogramEqualization(), iaa.HistogramEqualization()])) ## Augmentation aug = iaa.SomeOf((0, None), aug_list, random_order=True) seq = iaa.Sequential(aug) img = seq.augment_image(img) ## img_data_aug['width'] = img.shape[1] img_data_aug['height'] = img.shape[0] return img_data_aug, img
[ "imgaug.augmenters.SomeOf", "imgaug.augmenters.KMeansColorQuantization", "numpy.random.randint", "imgaug.augmenters.LogContrast", "imgaug.augmenters.AllChannelsHistogramEqualization", "imgaug.augmenters.GammaContrast", "numpy.transpose", "numpy.random.choice", "copy.deepcopy", "imgaug.augmenters.LinearContrast", "imgaug.augmenters.AllChannelsCLAHE", "imgaug.augmenters.Sequential", "imgaug.augmenters.MultiplyHueAndSaturation", "cv2.flip", "imgaug.augmenters.AddToHueAndSaturation", "cv2.imread", "imgaug.augmenters.Grayscale", "imgaug.augmenters.UniformColorQuantization", "imgaug.augmenters.SigmoidContrast", "imgaug.augmenters.HistogramEqualization" ]
[((1351, 1374), 'copy.deepcopy', 'copy.deepcopy', (['img_data'], {}), '(img_data)\n', (1364, 1374), False, 'import copy\n'), ((1403, 1439), 'cv2.imread', 'cv2.imread', (["img_data_aug['filepath']"], {}), "(img_data_aug['filepath'])\n", (1413, 1439), False, 'import cv2\n'), ((4948, 4998), 'imgaug.augmenters.SomeOf', 'iaa.SomeOf', (['(0, None)', 'aug_list'], {'random_order': '(True)'}), '((0, None), aug_list, random_order=True)\n', (4958, 4998), True, 'import imgaug.augmenters as iaa\n'), ((5013, 5032), 'imgaug.augmenters.Sequential', 'iaa.Sequential', (['aug'], {}), '(aug)\n', (5027, 5032), True, 'import imgaug.augmenters as iaa\n'), ((1737, 1753), 'cv2.flip', 'cv2.flip', (['img', '(1)'], {}), '(img, 1)\n', (1745, 1753), False, 'import cv2\n'), ((2034, 2050), 'cv2.flip', 'cv2.flip', (['img', '(0)'], {}), '(img, 0)\n', (2042, 2050), False, 'import cv2\n'), ((1689, 1712), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)'], {}), '(0, 2)\n', (1706, 1712), True, 'import numpy as np\n'), ((1986, 2009), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)'], {}), '(0, 2)\n', (2003, 2009), True, 'import numpy as np\n'), ((2288, 2326), 'numpy.random.choice', 'np.random.choice', (['[0, 90, 180, 270]', '(1)'], {}), '([0, 90, 180, 270], 1)\n', (2304, 2326), True, 'import numpy as np\n'), ((2377, 2405), 'numpy.transpose', 'np.transpose', (['img', '(1, 0, 2)'], {}), '(img, (1, 0, 2))\n', (2389, 2405), True, 'import numpy as np\n'), ((2426, 2442), 'cv2.flip', 'cv2.flip', (['img', '(0)'], {}), '(img, 0)\n', (2434, 2442), False, 'import cv2\n'), ((2496, 2513), 'cv2.flip', 'cv2.flip', (['img', '(-1)'], {}), '(img, -1)\n', (2504, 2513), False, 'import cv2\n'), ((2566, 2594), 'numpy.transpose', 'np.transpose', (['img', '(1, 0, 2)'], {}), '(img, (1, 0, 2))\n', (2578, 2594), True, 'import numpy as np\n'), ((2615, 2631), 'cv2.flip', 'cv2.flip', (['img', '(1)'], {}), '(img, 1)\n', (2623, 2631), False, 'import cv2\n'), ((3587, 3645), 'imgaug.augmenters.MultiplyHueAndSaturation', 'iaa.MultiplyHueAndSaturation', (['(0.5, 1.5)'], {'per_channel': '(True)'}), '((0.5, 1.5), per_channel=True)\n', (3615, 3645), True, 'import imgaug.augmenters as iaa\n'), ((3715, 3769), 'imgaug.augmenters.AddToHueAndSaturation', 'iaa.AddToHueAndSaturation', (['(-50, 50)'], {'per_channel': '(True)'}), '((-50, 50), per_channel=True)\n', (3740, 3769), True, 'import imgaug.augmenters as iaa\n'), ((3839, 3868), 'imgaug.augmenters.KMeansColorQuantization', 'iaa.KMeansColorQuantization', ([], {}), '()\n', (3866, 3868), True, 'import imgaug.augmenters as iaa\n'), ((3938, 3968), 'imgaug.augmenters.UniformColorQuantization', 'iaa.UniformColorQuantization', ([], {}), '()\n', (3966, 3968), True, 'import imgaug.augmenters as iaa\n'), ((4038, 4069), 'imgaug.augmenters.Grayscale', 'iaa.Grayscale', ([], {'alpha': '(0.0, 1.0)'}), '(alpha=(0.0, 1.0))\n', (4051, 4069), True, 'import imgaug.augmenters as iaa\n'), ((4148, 4195), 'imgaug.augmenters.GammaContrast', 'iaa.GammaContrast', (['(0.5, 2.0)'], {'per_channel': '(True)'}), '((0.5, 2.0), per_channel=True)\n', (4165, 4195), True, 'import imgaug.augmenters as iaa\n'), ((4265, 4335), 'imgaug.augmenters.SigmoidContrast', 'iaa.SigmoidContrast', ([], {'gain': '(3, 10)', 'cutoff': '(0.4, 0.6)', 'per_channel': '(True)'}), '(gain=(3, 10), cutoff=(0.4, 0.6), per_channel=True)\n', (4284, 4335), True, 'import imgaug.augmenters as iaa\n'), ((4404, 4454), 'imgaug.augmenters.LogContrast', 'iaa.LogContrast', ([], {'gain': '(0.6, 1.4)', 'per_channel': '(True)'}), '(gain=(0.6, 1.4), per_channel=True)\n', (4419, 4454), True, 'import imgaug.augmenters as iaa\n'), ((4524, 4572), 'imgaug.augmenters.LinearContrast', 'iaa.LinearContrast', (['(0.4, 1.6)'], {'per_channel': '(True)'}), '((0.4, 1.6), per_channel=True)\n', (4542, 4572), True, 'import imgaug.augmenters as iaa\n'), ((4642, 4700), 'imgaug.augmenters.AllChannelsCLAHE', 'iaa.AllChannelsCLAHE', ([], {'clip_limit': '(1, 10)', 'per_channel': '(True)'}), '(clip_limit=(1, 10), per_channel=True)\n', (4662, 4700), True, 'import imgaug.augmenters as iaa\n'), ((4770, 4808), 'imgaug.augmenters.AllChannelsHistogramEqualization', 'iaa.AllChannelsHistogramEqualization', ([], {}), '()\n', (4806, 4808), True, 'import imgaug.augmenters as iaa\n'), ((4878, 4905), 'imgaug.augmenters.HistogramEqualization', 'iaa.HistogramEqualization', ([], {}), '()\n', (4903, 4905), True, 'import imgaug.augmenters as iaa\n')]
import numpy as np from colearning.game import Player class BasePlayer(Player): """docstring for BasePlayer""" #----Fields team = None individual_id = None def initialize_player(self, team, individual_id): """ Setup the player's external attributes """ self.team = team self.individual_id = individual_id def get_view(self, players, bullets): """ Returns what the player is able to see Outputs: Fov (in rad) Num enemy Num Ally in view Num Ally ping in view Enemy bullets in view """ output = np.zeros(5) output[0] = self.fov_angle for obj in players: if(self.is_in_fov(obj.position)): if(obj.team != self.team): output[1] += 1 else: output[2] += 1 if(obj.ping): output[3] += 1 for obj in bullets: if(self.is_in_fov(obj.position)): output[4] += 1 return output def pre_update(self, players, bullets): """ Get a move from the model """ in_vals = self.get_view(players, bullets) return self.get_move(in_vals) #----VIRTUAL FUNTIONS #---------------------------------------------------- def reset(self): raise NotImplementedError('Player subclasses must reimplement reset') def learn(self): raise NotImplementedError('Player subclasses must reimplement learn') def get_move(self, in_vals): raise NotImplementedError('Player subclasses must reimplement get_move') def set_params(self, params): raise NotImplementedError('Player subclasses must reimplement set_params') def get_params(self): raise NotImplementedError('Player subclasses must reimplement set_params') def param_dim(self): raise NotImplementedError('Player subclasses must reimplement param_dim') def reward(self, amount): raise NotImplementedError('Player subclasses must reimplement reward')
[ "numpy.zeros" ]
[((649, 660), 'numpy.zeros', 'np.zeros', (['(5)'], {}), '(5)\n', (657, 660), True, 'import numpy as np\n')]
import pickle import logging import numpy as np import torch import models import utils logger = logging.getLogger() class BaseExperiment(): def __init__(self, args): self.save_dir = args.save_dir self.burn_in_steps = args.burn_in_steps self.eval_freq = args.eval_freq self.cpu = args.cpu self.batch_size = args.batch_size self.is_vi = args.is_vi self.samp_num = args.mcmc_samp_num self.exp_type = args.exp_type self.resume_path = args.resume_path if args.save_name is None: self.save_name = args.exp_type else: self.save_name = args.save_name self.log = dict() self.log['user_time'] = 0 ''' load dataset ''' dataset_list = utils.get_dataset(args.dataset) self.trainset = dataset_list[0] if len(dataset_list) == 2: self.testset = dataset_list[1] ''' burn_in_sampler is provided only for `burn_in_stage` ''' self.burn_in_sampler = utils.DataSampler( self.trainset, batch_size=args.batch_size) ''' train_sampler is provided only for `forget_stage` ''' self.train_sampler = utils.DataSampler( self.trainset, batch_size=args.ifs_iter_bs) ''' train_loader is provided for evaluation ''' self.train_loader = utils.DataLoader(self.trainset, self.batch_size) self.ifs_params = { 'scaling': args.ifs_scaling, 'iter_T': args.ifs_iter_T, 'samp_T': args.ifs_samp_T, 'iter_bs': args.ifs_iter_bs, 'rm_bs': args.ifs_rm_bs, 'kill_num': args.ifs_kill_num, } ''' generate the indices of forgetted data ''' self.forgetted_train_idx = self.generate_forget_idx( self.trainset, self.ifs_params['kill_num'],) ''' forgetting follows random order ''' self.forgetted_train_idx = np.random.permutation(self.forgetted_train_idx) utils.add_log(self.log, 'forgetted_train_idx', self.forgetted_train_idx) ''' build a loader on forgetted data (for evaluation) ''' self.forgetted_train_loader = utils.DataLoader(self.trainset, batch_size=self.batch_size, shuffle=False, drop_last=False) self.forgetted_train_loader.set_sampler_indices(self.forgetted_train_idx) self.optim_params = { 'opt': args.optim, 'lr': args.lr / len(self.trainset), 'weight_decay': args.weight_decay, 'momentum': args.momentum, 'sghmc_alpha': args.sghmc_alpha, } self.lr_params = { 'lr': args.lr / len(self.trainset), 'lr_decay_exp': args.lr_decay_exp, 'lr_decay_rate': args.lr_decay_rate, 'lr_decay_freq': args.lr_decay_freq, } def run(self): real_save_name = '{}-ckpt'.format(self.save_name) if self.exp_type == 'burn-in-remain': self.burn_in_sampler.remove( self.forgetted_train_idx ) self.train_loader.remove( self.forgetted_train_idx ) self.burn_in_stage() self.save_checkpoint(real_save_name) elif self.exp_type == 'forget': state_dict = torch.load(self.resume_path) self.model.load_state_dict(state_dict['model_state_dict']) self.optimizer.load_state_dict(state_dict['optimizer_state_dict']) self.forget_stage() self.save_checkpoint(real_save_name) else: raise ValueError('exp {} not found'.format(self.exp_type)) def burn_in_stage(self): raise NotImplementedError def forget_stage(self): ''' step 1, obtain the indices of forgetted data ''' self.forgetted_train_idx_loader = utils.IndexBatchSampler( batch_size=self.ifs_params['rm_bs'], indices=self.forgetted_train_idx) ''' step 2, obtain train loader (for evaluation) ''' self.train_loader.remove(self.forgetted_train_idx) ''' forgetting preprocessing end ''' def eval_one_epoch(self, model, loader): raise NotImplementedError def generate_forget_idx(self, dataset, kill_num): raise NotImplementedError def save_checkpoint(self, name, save_log=True, save_model=True): save_dir = self.save_dir log = self.log model = self.model optimizer = self.optimizer if save_log: with open('{}/{}-log.pkl'.format(save_dir, name), 'wb') as f: pickle.dump(log, f) if save_model: torch.save({ 'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict(), }, '{}/{}-model.pkl'.format(save_dir, name))
[ "pickle.dump", "utils.DataLoader", "utils.DataSampler", "torch.load", "utils.add_log", "numpy.random.permutation", "utils.get_dataset", "utils.IndexBatchSampler", "logging.getLogger" ]
[((100, 119), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (117, 119), False, 'import logging\n'), ((780, 811), 'utils.get_dataset', 'utils.get_dataset', (['args.dataset'], {}), '(args.dataset)\n', (797, 811), False, 'import utils\n'), ((1031, 1091), 'utils.DataSampler', 'utils.DataSampler', (['self.trainset'], {'batch_size': 'args.batch_size'}), '(self.trainset, batch_size=args.batch_size)\n', (1048, 1091), False, 'import utils\n'), ((1201, 1262), 'utils.DataSampler', 'utils.DataSampler', (['self.trainset'], {'batch_size': 'args.ifs_iter_bs'}), '(self.trainset, batch_size=args.ifs_iter_bs)\n', (1218, 1262), False, 'import utils\n'), ((1361, 1409), 'utils.DataLoader', 'utils.DataLoader', (['self.trainset', 'self.batch_size'], {}), '(self.trainset, self.batch_size)\n', (1377, 1409), False, 'import utils\n'), ((1946, 1993), 'numpy.random.permutation', 'np.random.permutation', (['self.forgetted_train_idx'], {}), '(self.forgetted_train_idx)\n', (1967, 1993), True, 'import numpy as np\n'), ((2003, 2075), 'utils.add_log', 'utils.add_log', (['self.log', '"""forgetted_train_idx"""', 'self.forgetted_train_idx'], {}), "(self.log, 'forgetted_train_idx', self.forgetted_train_idx)\n", (2016, 2075), False, 'import utils\n'), ((2181, 2276), 'utils.DataLoader', 'utils.DataLoader', (['self.trainset'], {'batch_size': 'self.batch_size', 'shuffle': '(False)', 'drop_last': '(False)'}), '(self.trainset, batch_size=self.batch_size, shuffle=False,\n drop_last=False)\n', (2197, 2276), False, 'import utils\n'), ((3798, 3897), 'utils.IndexBatchSampler', 'utils.IndexBatchSampler', ([], {'batch_size': "self.ifs_params['rm_bs']", 'indices': 'self.forgetted_train_idx'}), "(batch_size=self.ifs_params['rm_bs'], indices=self.\n forgetted_train_idx)\n", (3821, 3897), False, 'import utils\n'), ((3255, 3283), 'torch.load', 'torch.load', (['self.resume_path'], {}), '(self.resume_path)\n', (3265, 3283), False, 'import torch\n'), ((4554, 4573), 'pickle.dump', 'pickle.dump', (['log', 'f'], {}), '(log, f)\n', (4565, 4573), False, 'import pickle\n')]
import numpy as np import cv2 import logging from .utils.localization import LocResult class CppLocalization: def __init__(self, db_ids, local_db, global_descriptors, images, points): import _hloc_cpp self.hloc = _hloc_cpp.HLoc() id_to_idx = {} old_to_new_kpt = {} for idx, i in enumerate(db_ids): keypoints = local_db[i].keypoints.T.astype(np.float32).copy() local_desc = local_db[i].descriptors.T.astype(np.float32).copy() global_desc = global_descriptors[idx].astype(np.float32).copy() # keypoints are NOT undistorted or nomalized idx = self.hloc.addImage(global_desc, keypoints, local_desc) id_to_idx[i] = idx old_to_new_kpt[i] = { k: j for j, k in enumerate(np.where(images[i].point3D_ids >= 0)[0])} for i, pt in points.items(): observations = np.array( [[id_to_idx[im_id], old_to_new_kpt[im_id][kpt_id]] for im_id, kpt_id in zip(pt.image_ids, pt.point2D_idxs)], dtype=np.int32) self.hloc.add3dPoint( pt.xyz.astype(np.float32).copy(), observations.copy()) self.hloc.buildIndex() def localize(self, query_info, query_item, global_transf, local_transf): global_desc = global_transf(query_item.global_desc[np.newaxis])[0] local_desc = local_transf(query_item.local_desc) keypoints = cv2.undistortPoints( query_item.keypoints[np.newaxis], query_info.K, np.array([query_info.dist, 0, 0, 0]))[0] logging.info('Localizing image %s', query_info.name) ret = self.cpp_backend.localize( global_desc.astype(np.float32), keypoints.astype(np.float32).T.copy(), local_desc.astype(np.float32).T.copy()) (success, num_components_total, num_components_tested, last_component_size, num_db_landmarks, num_matches, num_inliers, num_iters, global_ms, covis_ms, local_ms, pnp_ms) = ret result = LocResult(success, num_inliers, 0, np.eye(4)) stats = { 'success': success, 'num_components_total': num_components_total, 'num_components_tested': num_components_tested, 'last_component_size': last_component_size, 'num_db_landmarks': num_db_landmarks, 'num_matches': num_matches, 'num_inliers': num_inliers, 'num_ransac_iters': num_iters, 'timings': { 'global': global_ms, 'covis': covis_ms, 'local': local_ms, 'pnp': pnp_ms, } } return (result, stats)
[ "_hloc_cpp.HLoc", "logging.info", "numpy.where", "numpy.array", "numpy.eye" ]
[((236, 252), '_hloc_cpp.HLoc', '_hloc_cpp.HLoc', ([], {}), '()\n', (250, 252), False, 'import _hloc_cpp\n'), ((1628, 1680), 'logging.info', 'logging.info', (['"""Localizing image %s"""', 'query_info.name'], {}), "('Localizing image %s', query_info.name)\n", (1640, 1680), False, 'import logging\n'), ((2124, 2133), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (2130, 2133), True, 'import numpy as np\n'), ((1578, 1614), 'numpy.array', 'np.array', (['[query_info.dist, 0, 0, 0]'], {}), '([query_info.dist, 0, 0, 0])\n', (1586, 1614), True, 'import numpy as np\n'), ((828, 864), 'numpy.where', 'np.where', (['(images[i].point3D_ids >= 0)'], {}), '(images[i].point3D_ids >= 0)\n', (836, 864), True, 'import numpy as np\n')]
import scipy.optimize as so import numpy as np import scipy as sp import scipy.io as sio import os import sys import matplotlib.pyplot as plt localSize = 200 diagAdd = 0 maxIte = localSize if len(sys.argv) > 1: localSize = sys.argv[1] if len(sys.argv) > 2: diagAdd = sys.argv[2] if len(sys.argv) > 3: maxIte = sys.argv[3] print('mpirun -n 2 --map-by numa ./BCQPSolver_test ' + str(localSize)+' '+str(diagAdd)+' > ./testLog') os.system('mpirun -n 2 --map-by numa ./BCQPSolver_test ' + str(localSize)+' '+str(diagAdd)+' > ./testLog') Amat = sio.mmread('Amat_TCMAT.mtx') bvec = sio.mmread('bvec_TV.mtx').flatten() lb = sio.mmread('lbvec_TV.mtx').flatten() ub = sio.mmread('ubvec_TV.mtx').flatten() xsolBBPGD = sio.mmread('xsolBBPGD_TV.mtx').flatten() xsolAPGD = sio.mmread('xsolAPGD_TV.mtx').flatten() xguess = np.zeros(len(xsolBBPGD)) def func(x): return 0.5*x.dot((Amat.dot(x)))+bvec.dot(x) def grad(x): return Amat.dot(x)+bvec # minimize f = x^T A x + b^T x, subject to lb <= x <= ub bound = so.Bounds(lb, ub) res = so.minimize(func, xguess, jac=grad, bounds=bound, tol=1e-8, method='L-BFGS-B') print('scipy optimization func eval:', res.nfev) if res.success: print('reference min:', res.fun) print('BBPGD min:', func(xsolBBPGD)) print('APGD min:', func(xsolAPGD)) errorBBPGD = xsolBBPGD-res.x errorAPGD = xsolAPGD-res.x print('BBPGD error norm: ', np.linalg.norm(errorBBPGD)) print(' APGD error norm: ', np.linalg.norm(errorAPGD)) else: print('scipy optimization failed') # plot BBPGD and APGD history os.system('grep BBPGD_HISTORY ./testLog > ./BBPGD.log') os.system('grep APGD_HISTORY ./testLog > ./APGD.log') bbhistory = np.genfromtxt('BBPGD.log', usecols=(5, 6), delimiter=',') ahistory = np.genfromtxt('APGD.log', usecols=(5, 6), delimiter=',') plt.semilogy(bbhistory[:, 1], bbhistory[:, 0], label='BBPGD') plt.semilogy(ahistory[:, 1], ahistory[:, 0], label='APGD') plt.ylabel('residual') plt.xlabel('MV Count') plt.legend() plt.show() plt.savefig('testBCQP.png', dpi=150) plt.loglog(bbhistory[:, 1], bbhistory[:, 0], label='BBPGD') plt.loglog(ahistory[:, 1], ahistory[:, 0], label='APGD') plt.ylabel('residual') plt.xlabel('MV Count') plt.legend() plt.show() plt.savefig('testBCQP-log.png', dpi=150)
[ "matplotlib.pyplot.loglog", "scipy.optimize.minimize", "matplotlib.pyplot.show", "matplotlib.pyplot.legend", "numpy.genfromtxt", "os.system", "scipy.io.mmread", "scipy.optimize.Bounds", "numpy.linalg.norm", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.semilogy", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.savefig" ]
[((572, 600), 'scipy.io.mmread', 'sio.mmread', (['"""Amat_TCMAT.mtx"""'], {}), "('Amat_TCMAT.mtx')\n", (582, 600), True, 'import scipy.io as sio\n'), ((1039, 1056), 'scipy.optimize.Bounds', 'so.Bounds', (['lb', 'ub'], {}), '(lb, ub)\n', (1048, 1056), True, 'import scipy.optimize as so\n'), ((1063, 1142), 'scipy.optimize.minimize', 'so.minimize', (['func', 'xguess'], {'jac': 'grad', 'bounds': 'bound', 'tol': '(1e-08)', 'method': '"""L-BFGS-B"""'}), "(func, xguess, jac=grad, bounds=bound, tol=1e-08, method='L-BFGS-B')\n", (1074, 1142), True, 'import scipy.optimize as so\n'), ((1603, 1658), 'os.system', 'os.system', (['"""grep BBPGD_HISTORY ./testLog > ./BBPGD.log"""'], {}), "('grep BBPGD_HISTORY ./testLog > ./BBPGD.log')\n", (1612, 1658), False, 'import os\n'), ((1659, 1712), 'os.system', 'os.system', (['"""grep APGD_HISTORY ./testLog > ./APGD.log"""'], {}), "('grep APGD_HISTORY ./testLog > ./APGD.log')\n", (1668, 1712), False, 'import os\n'), ((1726, 1783), 'numpy.genfromtxt', 'np.genfromtxt', (['"""BBPGD.log"""'], {'usecols': '(5, 6)', 'delimiter': '""","""'}), "('BBPGD.log', usecols=(5, 6), delimiter=',')\n", (1739, 1783), True, 'import numpy as np\n'), ((1795, 1851), 'numpy.genfromtxt', 'np.genfromtxt', (['"""APGD.log"""'], {'usecols': '(5, 6)', 'delimiter': '""","""'}), "('APGD.log', usecols=(5, 6), delimiter=',')\n", (1808, 1851), True, 'import numpy as np\n'), ((1853, 1914), 'matplotlib.pyplot.semilogy', 'plt.semilogy', (['bbhistory[:, 1]', 'bbhistory[:, 0]'], {'label': '"""BBPGD"""'}), "(bbhistory[:, 1], bbhistory[:, 0], label='BBPGD')\n", (1865, 1914), True, 'import matplotlib.pyplot as plt\n'), ((1915, 1973), 'matplotlib.pyplot.semilogy', 'plt.semilogy', (['ahistory[:, 1]', 'ahistory[:, 0]'], {'label': '"""APGD"""'}), "(ahistory[:, 1], ahistory[:, 0], label='APGD')\n", (1927, 1973), True, 'import matplotlib.pyplot as plt\n'), ((1974, 1996), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""residual"""'], {}), "('residual')\n", (1984, 1996), True, 'import matplotlib.pyplot as plt\n'), ((1997, 2019), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""MV Count"""'], {}), "('MV Count')\n", (2007, 2019), True, 'import matplotlib.pyplot as plt\n'), ((2020, 2032), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2030, 2032), True, 'import matplotlib.pyplot as plt\n'), ((2033, 2043), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2041, 2043), True, 'import matplotlib.pyplot as plt\n'), ((2044, 2080), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""testBCQP.png"""'], {'dpi': '(150)'}), "('testBCQP.png', dpi=150)\n", (2055, 2080), True, 'import matplotlib.pyplot as plt\n'), ((2082, 2141), 'matplotlib.pyplot.loglog', 'plt.loglog', (['bbhistory[:, 1]', 'bbhistory[:, 0]'], {'label': '"""BBPGD"""'}), "(bbhistory[:, 1], bbhistory[:, 0], label='BBPGD')\n", (2092, 2141), True, 'import matplotlib.pyplot as plt\n'), ((2142, 2198), 'matplotlib.pyplot.loglog', 'plt.loglog', (['ahistory[:, 1]', 'ahistory[:, 0]'], {'label': '"""APGD"""'}), "(ahistory[:, 1], ahistory[:, 0], label='APGD')\n", (2152, 2198), True, 'import matplotlib.pyplot as plt\n'), ((2199, 2221), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""residual"""'], {}), "('residual')\n", (2209, 2221), True, 'import matplotlib.pyplot as plt\n'), ((2222, 2244), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""MV Count"""'], {}), "('MV Count')\n", (2232, 2244), True, 'import matplotlib.pyplot as plt\n'), ((2245, 2257), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2255, 2257), True, 'import matplotlib.pyplot as plt\n'), ((2258, 2268), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2266, 2268), True, 'import matplotlib.pyplot as plt\n'), ((2269, 2309), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""testBCQP-log.png"""'], {'dpi': '(150)'}), "('testBCQP-log.png', dpi=150)\n", (2280, 2309), True, 'import matplotlib.pyplot as plt\n'), ((608, 633), 'scipy.io.mmread', 'sio.mmread', (['"""bvec_TV.mtx"""'], {}), "('bvec_TV.mtx')\n", (618, 633), True, 'import scipy.io as sio\n'), ((649, 675), 'scipy.io.mmread', 'sio.mmread', (['"""lbvec_TV.mtx"""'], {}), "('lbvec_TV.mtx')\n", (659, 675), True, 'import scipy.io as sio\n'), ((691, 717), 'scipy.io.mmread', 'sio.mmread', (['"""ubvec_TV.mtx"""'], {}), "('ubvec_TV.mtx')\n", (701, 717), True, 'import scipy.io as sio\n'), ((740, 770), 'scipy.io.mmread', 'sio.mmread', (['"""xsolBBPGD_TV.mtx"""'], {}), "('xsolBBPGD_TV.mtx')\n", (750, 770), True, 'import scipy.io as sio\n'), ((792, 821), 'scipy.io.mmread', 'sio.mmread', (['"""xsolAPGD_TV.mtx"""'], {}), "('xsolAPGD_TV.mtx')\n", (802, 821), True, 'import scipy.io as sio\n'), ((1440, 1466), 'numpy.linalg.norm', 'np.linalg.norm', (['errorBBPGD'], {}), '(errorBBPGD)\n', (1454, 1466), True, 'import numpy as np\n'), ((1500, 1525), 'numpy.linalg.norm', 'np.linalg.norm', (['errorAPGD'], {}), '(errorAPGD)\n', (1514, 1525), True, 'import numpy as np\n')]
import pytest import numpy as np from scipy.ndimage import gaussian_filter1d import astropy.units as u from astropy.utils.data import download_file from astropy.tests.helper import assert_quantity_allclose from ..io import EchelleSpectrum, Template, Spectrum from ..ccf import cross_corr lkca4_id = "1x3nIg1P5tYFQqJrwEpQU11XQOs3ImH3v" proxima_id = "1I7E1x1XRjcxXNQXiuaajb_Jz7Wn2N_Eo" # T=3000 K, Molecule=TiO: template_id = "1eGUBfk7Q9zaXgJQJtVFB6pit7cmoGCpn" base_url = "https://drive.google.com/uc?export=download&id={0}" lkca4_url = base_url.format(lkca4_id) proxima_url = base_url.format(proxima_id) template_url = base_url.format(template_id) @pytest.mark.remote_data @pytest.mark.parametrize("url,", [ lkca4_url, proxima_url, ]) def test_ingest_e2ds(url): spectrum_path = download_file(url) spectrum = EchelleSpectrum.from_e2ds(spectrum_path) assert hasattr(spectrum.orders[0], 'wavelength') assert hasattr(spectrum.orders[0], 'flux') assert len(spectrum.orders) == 72 assert spectrum.header['DATE-OBS'].startswith('2004') assert (spectrum.orders[1].wavelength.mean() > spectrum.orders[0].wavelength.mean()) @pytest.mark.remote_data @pytest.mark.parametrize("url,", [ lkca4_url, proxima_url, ]) def test_continuum_normalize(url): spectrum_path = download_file(url) spectrum = EchelleSpectrum.from_e2ds(spectrum_path) spectrum.continuum_normalize() # Confirm that each echelle order is roughly continuum normalized (roughly # distributed about unity): for order in spectrum.orders: assert abs(np.median(order.flux) - 1) < 1 @pytest.mark.remote_data @pytest.mark.parametrize("url,", [ proxima_url, ]) def test_end_to_end(url): spectrum_path = download_file(url) spectrum = EchelleSpectrum.from_e2ds(spectrum_path) spectrum.continuum_normalize() template_3000_tio_path = download_file(template_url) template_3000_tio = Template.from_npy(template_3000_tio_path) ccf = cross_corr(spectrum.nearest_order(6800), template_3000_tio) # Check that the TiO signal shows up at the radial velocity of the star assert_quantity_allclose(ccf.rv, -22 * u.km / u.s, atol=4 * u.km / u.s) # Check that the SNR of the detection is significant assert ccf.signal_to_noise > 5 @pytest.mark.parametrize("seed, snr,", [ (42, 13), (1984, 10), ]) def test_ccf(seed, snr): # Make test reproducible: np.random.seed(seed) # Generate a wavelength grid: wl = np.arange(6800, 6900, 0.1) # Generate a pseudo-random absorption pattern absorption_pattern = gaussian_filter1d(0.1 * np.random.randn(len(wl)), 5) absorption_pattern = absorption_pattern - absorption_pattern.min() # Roll the absorption pattern offset by 3 indices index_offset = 3 fl = np.ones_like(wl) - np.roll(absorption_pattern, index_offset) spectrum = Spectrum(wl, fl) emission = absorption_pattern / np.trapz(absorption_pattern, wl) template = Template(wl, emission) ccf = cross_corr(spectrum, template, start_lam=-10, end_lam=10, n_steps=100) # Check that S/N is approximately correct: assert abs(ccf.signal_to_noise - snr) < 1 # Check that the estimated radial velocity is equivalent to index offset ref_wl = 6800 * u.Angstrom measured_velocity_offset = (ccf.rv.to(u.Angstrom, u.doppler_optical(ref_wl)) - ref_wl) / ((wl[1] - wl[0])*u.Angstrom) assert_quantity_allclose(measured_velocity_offset, index_offset, atol=1e-2)
[ "numpy.trapz", "numpy.random.seed", "numpy.ones_like", "numpy.roll", "numpy.median", "astropy.tests.helper.assert_quantity_allclose", "numpy.arange", "astropy.units.doppler_optical", "astropy.utils.data.download_file", "pytest.mark.parametrize" ]
[((681, 738), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""url,"""', '[lkca4_url, proxima_url]'], {}), "('url,', [lkca4_url, proxima_url])\n", (704, 738), False, 'import pytest\n'), ((1198, 1255), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""url,"""', '[lkca4_url, proxima_url]'], {}), "('url,', [lkca4_url, proxima_url])\n", (1221, 1255), False, 'import pytest\n'), ((1656, 1702), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""url,"""', '[proxima_url]'], {}), "('url,', [proxima_url])\n", (1679, 1702), False, 'import pytest\n'), ((2311, 2372), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""seed, snr,"""', '[(42, 13), (1984, 10)]'], {}), "('seed, snr,', [(42, 13), (1984, 10)])\n", (2334, 2372), False, 'import pytest\n'), ((797, 815), 'astropy.utils.data.download_file', 'download_file', (['url'], {}), '(url)\n', (810, 815), False, 'from astropy.utils.data import download_file\n'), ((1322, 1340), 'astropy.utils.data.download_file', 'download_file', (['url'], {}), '(url)\n', (1335, 1340), False, 'from astropy.utils.data import download_file\n'), ((1756, 1774), 'astropy.utils.data.download_file', 'download_file', (['url'], {}), '(url)\n', (1769, 1774), False, 'from astropy.utils.data import download_file\n'), ((1897, 1924), 'astropy.utils.data.download_file', 'download_file', (['template_url'], {}), '(template_url)\n', (1910, 1924), False, 'from astropy.utils.data import download_file\n'), ((2143, 2214), 'astropy.tests.helper.assert_quantity_allclose', 'assert_quantity_allclose', (['ccf.rv', '(-22 * u.km / u.s)'], {'atol': '(4 * u.km / u.s)'}), '(ccf.rv, -22 * u.km / u.s, atol=4 * u.km / u.s)\n', (2167, 2214), False, 'from astropy.tests.helper import assert_quantity_allclose\n'), ((2443, 2463), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (2457, 2463), True, 'import numpy as np\n'), ((2508, 2534), 'numpy.arange', 'np.arange', (['(6800)', '(6900)', '(0.1)'], {}), '(6800, 6900, 0.1)\n', (2517, 2534), True, 'import numpy as np\n'), ((3529, 3604), 'astropy.tests.helper.assert_quantity_allclose', 'assert_quantity_allclose', (['measured_velocity_offset', 'index_offset'], {'atol': '(0.01)'}), '(measured_velocity_offset, index_offset, atol=0.01)\n', (3553, 3604), False, 'from astropy.tests.helper import assert_quantity_allclose\n'), ((2820, 2836), 'numpy.ones_like', 'np.ones_like', (['wl'], {}), '(wl)\n', (2832, 2836), True, 'import numpy as np\n'), ((2839, 2880), 'numpy.roll', 'np.roll', (['absorption_pattern', 'index_offset'], {}), '(absorption_pattern, index_offset)\n', (2846, 2880), True, 'import numpy as np\n'), ((2951, 2983), 'numpy.trapz', 'np.trapz', (['absorption_pattern', 'wl'], {}), '(absorption_pattern, wl)\n', (2959, 2983), True, 'import numpy as np\n'), ((3424, 3449), 'astropy.units.doppler_optical', 'u.doppler_optical', (['ref_wl'], {}), '(ref_wl)\n', (3441, 3449), True, 'import astropy.units as u\n'), ((1597, 1618), 'numpy.median', 'np.median', (['order.flux'], {}), '(order.flux)\n', (1606, 1618), True, 'import numpy as np\n')]
import numpy as np import scipy.linalg as la import seaborn as sns import matplotlib.patches as mpatches import matplotlib.pyplot as plt from scipy.stats import multivariate_normal from plot_utils import * nburnin = 500 nsample = 1000 niter = nburnin + nsample ################## ### 1-D Normal ### ################## np.random.seed(2019) sample_mean = 1 sample_sig2 = 1 X = np.random.normal(sample_mean, sample_sig2, size = 100) U = lambda mu: mu**2/2 + np.sum((X-mu)**2/2) gradU = lambda mu: mu + np.sum(mu-X) # theoretical distribution sig2_pos = 1/(1/1 + len(X) / np.cov(X)) mean_pos = (0 + X.mean()*len(X)/np.cov(X))/(1/1 + len(X) / np.cov(X)) dist = multivariate_normal(mean_pos, (sig2_pos)) sim = np.random.normal(mean_pos, np.sqrt(sig2_pos), nsample) def leapfrog(gradU, p, r, eps = 0.01, L = 100, M_i = np.array([[1,0],[0,1]])): """ Using leapfrog to discretize Args: gradU: gradient of potential energy (posterior) p: position (parameters) r: momentum (auxiliary) eps: stepsize L: # of steps M_i: inversion of preconditioned mass matrix (omitted since assumed to be identity) """ r = r - eps/2 * gradU(p) for i in range(L-1): p = p + eps * r r = r - eps * gradU(p) p = p + eps * r r = r - eps/2 * gradU(p) return p, r def log_r(U, p0, r0, p, r, M_i = np.array([[1,0],[0,1]])): """log of acceptance ratio""" return (U(p0) + 1/2*r0.dot(r0)) - (U(p0) + 1/2*r.dot(r)) eps = 0.01 L = 100 # M_i = np.array([[1]]) # for we assume Mass matrix M either to be identity or 1, it can be omitted. samples = np.zeros(niter+1) p = np.array([0.0]) samples[0] = p for k in range(niter): r0 = np.random.normal(0,1,1) p, r = leapfrog(gradU, p, r0, eps, L) # M-H p0 = samples[k] a = np.exp(log_r(U, p0, r0, p, r)) u = np.random.rand() if u < a: samples[k+1] = p else: samples[k+1] = p0 print("%.2f %%" % np.round((k+1)/niter*100,2), end = "\r") plt.figure(figsize=(10,6)) sns.kdeplot(samples[nburnin+1:], label = 'Samples with HMC') sns.kdeplot(sim, label = 'Samples from true posterior') plt.title("HMC (univariate normal)") # plt.savefig('HMC_1d.png'); ################## ### 2-D Normal ### ################## mean_or = np.array([1,-1]) sig_or = np.array([[1,0.75],[0.75,1]]) sig_or_i = la.inv(sig_or) np.random.seed(2019) data = multivariate_normal(mean_or, sig_or).rvs(100) Sig_pos = la.inv(len(data)*la.inv(np.cov(data.T)) + np.eye(2)) mean_pos = (la.inv(len(data)*la.inv(np.cov(data.T)) + np.eye(2)) @ (len(data)*la.inv(np.cov(data.T))@np.mean(data,0) + np.eye(2)@np.zeros(2))) sim = multivariate_normal(mean_pos, Sig_pos).rvs(nsample) U = lambda mu: np.sum(np.diag((data - mu)@sig_or_i@(data - mu).T/2)) + 1/2 * mu.T @ mu gradU = lambda mu: -sig_or_i.dot((data-mu).T).sum(1) + mu eps = 0.01 L = 100 np.random.seed(2019) orbit = np.zeros((niter+1, 2)) p = np.array([0,0.0]) orbit[0] = p for k in range(niter): r0 = np.random.normal(0,1,2) p, r = leapfrog(gradU, p, r0, 0.01, L) # accept-reject p0 = orbit[k] a = np.exp(log_r(U, p0, r0, p, r)) u = np.random.rand() if u < a: orbit[k+1] = p else: orbit[k+1] = p0 print("%.2f %%" % np.round((k+1)/niter*100,2), end = "\r") kde_stack(orbit[nburnin+1:,0], orbit[nburnin+1:,1], sim[:,0], sim[:,1])
[ "matplotlib.pyplot.title", "numpy.random.seed", "seaborn.kdeplot", "numpy.sum", "numpy.zeros", "scipy.stats.multivariate_normal", "scipy.linalg.inv", "matplotlib.pyplot.figure", "numpy.mean", "numpy.array", "numpy.random.normal", "numpy.random.rand", "numpy.eye", "numpy.cov", "numpy.round", "numpy.diag", "numpy.sqrt" ]
[((322, 342), 'numpy.random.seed', 'np.random.seed', (['(2019)'], {}), '(2019)\n', (336, 342), True, 'import numpy as np\n'), ((379, 431), 'numpy.random.normal', 'np.random.normal', (['sample_mean', 'sample_sig2'], {'size': '(100)'}), '(sample_mean, sample_sig2, size=100)\n', (395, 431), True, 'import numpy as np\n'), ((662, 701), 'scipy.stats.multivariate_normal', 'multivariate_normal', (['mean_pos', 'sig2_pos'], {}), '(mean_pos, sig2_pos)\n', (681, 701), False, 'from scipy.stats import multivariate_normal\n'), ((1644, 1663), 'numpy.zeros', 'np.zeros', (['(niter + 1)'], {}), '(niter + 1)\n', (1652, 1663), True, 'import numpy as np\n'), ((1666, 1681), 'numpy.array', 'np.array', (['[0.0]'], {}), '([0.0])\n', (1674, 1681), True, 'import numpy as np\n'), ((2034, 2061), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 6)'}), '(figsize=(10, 6))\n', (2044, 2061), True, 'import matplotlib.pyplot as plt\n'), ((2061, 2121), 'seaborn.kdeplot', 'sns.kdeplot', (['samples[nburnin + 1:]'], {'label': '"""Samples with HMC"""'}), "(samples[nburnin + 1:], label='Samples with HMC')\n", (2072, 2121), True, 'import seaborn as sns\n'), ((2122, 2175), 'seaborn.kdeplot', 'sns.kdeplot', (['sim'], {'label': '"""Samples from true posterior"""'}), "(sim, label='Samples from true posterior')\n", (2133, 2175), True, 'import seaborn as sns\n'), ((2178, 2214), 'matplotlib.pyplot.title', 'plt.title', (['"""HMC (univariate normal)"""'], {}), "('HMC (univariate normal)')\n", (2187, 2214), True, 'import matplotlib.pyplot as plt\n'), ((2316, 2333), 'numpy.array', 'np.array', (['[1, -1]'], {}), '([1, -1])\n', (2324, 2333), True, 'import numpy as np\n'), ((2342, 2374), 'numpy.array', 'np.array', (['[[1, 0.75], [0.75, 1]]'], {}), '([[1, 0.75], [0.75, 1]])\n', (2350, 2374), True, 'import numpy as np\n'), ((2383, 2397), 'scipy.linalg.inv', 'la.inv', (['sig_or'], {}), '(sig_or)\n', (2389, 2397), True, 'import scipy.linalg as la\n'), ((2398, 2418), 'numpy.random.seed', 'np.random.seed', (['(2019)'], {}), '(2019)\n', (2412, 2418), True, 'import numpy as np\n'), ((2917, 2937), 'numpy.random.seed', 'np.random.seed', (['(2019)'], {}), '(2019)\n', (2931, 2937), True, 'import numpy as np\n'), ((2947, 2971), 'numpy.zeros', 'np.zeros', (['(niter + 1, 2)'], {}), '((niter + 1, 2))\n', (2955, 2971), True, 'import numpy as np\n'), ((2974, 2992), 'numpy.array', 'np.array', (['[0, 0.0]'], {}), '([0, 0.0])\n', (2982, 2992), True, 'import numpy as np\n'), ((737, 754), 'numpy.sqrt', 'np.sqrt', (['sig2_pos'], {}), '(sig2_pos)\n', (744, 754), True, 'import numpy as np\n'), ((820, 846), 'numpy.array', 'np.array', (['[[1, 0], [0, 1]]'], {}), '([[1, 0], [0, 1]])\n', (828, 846), True, 'import numpy as np\n'), ((1390, 1416), 'numpy.array', 'np.array', (['[[1, 0], [0, 1]]'], {}), '([[1, 0], [0, 1]])\n', (1398, 1416), True, 'import numpy as np\n'), ((1729, 1754), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', '(1)'], {}), '(0, 1, 1)\n', (1745, 1754), True, 'import numpy as np\n'), ((1873, 1889), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (1887, 1889), True, 'import numpy as np\n'), ((3037, 3062), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', '(2)'], {}), '(0, 1, 2)\n', (3053, 3062), True, 'import numpy as np\n'), ((3190, 3206), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (3204, 3206), True, 'import numpy as np\n'), ((460, 485), 'numpy.sum', 'np.sum', (['((X - mu) ** 2 / 2)'], {}), '((X - mu) ** 2 / 2)\n', (466, 485), True, 'import numpy as np\n'), ((504, 518), 'numpy.sum', 'np.sum', (['(mu - X)'], {}), '(mu - X)\n', (510, 518), True, 'import numpy as np\n'), ((2426, 2462), 'scipy.stats.multivariate_normal', 'multivariate_normal', (['mean_or', 'sig_or'], {}), '(mean_or, sig_or)\n', (2445, 2462), False, 'from scipy.stats import multivariate_normal\n'), ((2526, 2535), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (2532, 2535), True, 'import numpy as np\n'), ((2699, 2737), 'scipy.stats.multivariate_normal', 'multivariate_normal', (['mean_pos', 'Sig_pos'], {}), '(mean_pos, Sig_pos)\n', (2718, 2737), False, 'from scipy.stats import multivariate_normal\n'), ((574, 583), 'numpy.cov', 'np.cov', (['X'], {}), '(X)\n', (580, 583), True, 'import numpy as np\n'), ((617, 626), 'numpy.cov', 'np.cov', (['X'], {}), '(X)\n', (623, 626), True, 'import numpy as np\n'), ((644, 653), 'numpy.cov', 'np.cov', (['X'], {}), '(X)\n', (650, 653), True, 'import numpy as np\n'), ((1988, 2022), 'numpy.round', 'np.round', (['((k + 1) / niter * 100)', '(2)'], {}), '((k + 1) / niter * 100, 2)\n', (1996, 2022), True, 'import numpy as np\n'), ((2591, 2600), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (2597, 2600), True, 'import numpy as np\n'), ((2650, 2666), 'numpy.mean', 'np.mean', (['data', '(0)'], {}), '(data, 0)\n', (2657, 2666), True, 'import numpy as np\n'), ((2668, 2677), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (2674, 2677), True, 'import numpy as np\n'), ((2678, 2689), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (2686, 2689), True, 'import numpy as np\n'), ((2774, 2825), 'numpy.diag', 'np.diag', (['((data - mu) @ sig_or_i @ (data - mu).T / 2)'], {}), '((data - mu) @ sig_or_i @ (data - mu).T / 2)\n', (2781, 2825), True, 'import numpy as np\n'), ((3301, 3335), 'numpy.round', 'np.round', (['((k + 1) / niter * 100)', '(2)'], {}), '((k + 1) / niter * 100, 2)\n', (3309, 3335), True, 'import numpy as np\n'), ((2508, 2522), 'numpy.cov', 'np.cov', (['data.T'], {}), '(data.T)\n', (2514, 2522), True, 'import numpy as np\n'), ((2573, 2587), 'numpy.cov', 'np.cov', (['data.T'], {}), '(data.T)\n', (2579, 2587), True, 'import numpy as np\n'), ((2634, 2648), 'numpy.cov', 'np.cov', (['data.T'], {}), '(data.T)\n', (2640, 2648), True, 'import numpy as np\n')]
# coding: utf-8 # ## Pothole Detection # #### Load important libraries # In[1]: import cv2 import numpy as np import pygame import time import smtplib import sys from matplotlib import pyplot as plt # In[2]: file_name = 'pothole.jpg' #file name can be passed as an commandline argument. if sys.argv[1] != None: file_name = sys.argv[1] # Show the image # Open a new thread to manage the external cv2 interaction cv2.startWindowThread() def plt_show(image, title=""): if len(image.shape) == 3: image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) plt.axis("off") plt.title(title) # plt.imshow(image, cmap="Greys_r") # plt.imshow(image, cmap=plt.cm.Spectral) plt.imshow(image, cmap=plt.cm.Greys_r) plt.show() # #### Resize the image # In[3]: def image_resize(image, width = None, height = None, inter = cv2.INTER_AREA): # initialize the dimensions of the image to be resized and # grab the image size dim = None (h, w) = image.shape[:2] # if both the width and height are None, then return the # original image if width is None and height is None: return image # check to see if the width is None if width is None: # calculate the ratio of the height and construct the # dimensions r = height / float(h) dim = (int(w * r), height) # otherwise, the height is None else: # calculate the ratio of the width and construct the # dimensions r = width / float(w) dim = (width, int(h * r)) # resize the image resized = cv2.resize(image, dim, interpolation = inter) # return the resized image return resized # In[4]: r_image1 = cv2.imread(file_name) r_image2 = image_resize(r_image1, width = 275, height = 180) # In[5]: plt_show(r_image2) # In[6]: plt.title("Pothole Image") plt.imshow(r_image2) plt.show() #resize_image = cv2.resize(r_image1, (275,180)) #plt_show(resize_image) # In[7]: #im = cv2.imread('index4.jpg') im = r_image2 plt_show(im) # In[8]: # Convert the GrayScale gray1 = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) plt_show(gray1) # In[9]: # save the image cv2.imwrite('grayImg.jpg', gray1) # #### Contour Detection Code # In[10]: imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) plt_show(imgray) # In[11]: ret,thresh = cv2.threshold(imgray,127,255,0) # In[12]: #contours1, _, a = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE) image1, contours1, hierarchy1 = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE) # In[13]: plt_show(image1) # In[14]: #print(contours1) #contours1.shape # plt.title("Pothole Image") # plt.imshow(image1) # plt.show() # In[15]: image2, contours2, hierarchy2 = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) # In[16]: plt_show(image2) # In[17]: # copy the real image img2 = im.copy() # In[18]: plt_show(img2) # In[19]: out = cv2.drawContours(img2, contours2, -1, (0,250,0),1) # In[20]: plt.title("drawContours Pothole Image") plt.imshow(out) plt.show() # #### Detec the pothole # In[21]: cv2.imshow('img1',img2) cv2.waitKey(0) plt.subplot(331),plt.imshow(im),plt.title('GRAY') plt.xticks([]), plt.yticks([]) # In[22]: img = cv2.imread('index2.jpg',0) # In[23]: plt_show(img) # In[24]: ret,thresh = cv2.threshold(img,127,255,0) # In[25]: image, contours, hierarchy = cv2.findContours(thresh, 1, 2) # In[26]: cnt = contours[0] M = cv2.moments(cnt) print(M) # In[27]: perimeter = cv2.arcLength(cnt,True) print (perimeter) # In[28]: area = cv2.contourArea(cnt) print (area) # In[29]: epsilon = 0.1*cv2.arcLength(cnt,True) approx = cv2.approxPolyDP(cnt,epsilon,True) print (epsilon) print (approx) # In[30]: for c in contours: rect = cv2.boundingRect(c) if rect[2] < 100 or rect[3] < 100: continue #print cv2.contourArea(c) x,y,w,h = rect cv2.rectangle(img2,(x,y),(x+w,y+h),(0,255,0),8) cv2.putText(img2,'Moth Detected',(x+w+40,y+h),0,2.0,(0,255,0)) plt.title("Moth Detected Pothole Image") plt.imshow(img2) plt.show() cv2.imshow("Show",img2) #cv2.imshow('img' , resize_img) x = cv2.waitKey(0) if x == 27: cv2.destroyWindow('img') cv2.waitKey() cv2.destroyAllWindows() # In[31]: k = cv2.isContourConvex(cnt) print(k) # In[32]: #blur blur = cv2.blur(im,(5,5)) # In[33]: plt_show(blur) # In[34]: #guassian blur gblur = cv2.GaussianBlur(im,(5,5),0) plt_show(gblur) # In[35]: #median median = cv2.medianBlur(im,5) plt_show(median) # In[36]: #erosion kernel = np.ones((5,5),np.uint8) erosion = cv2.erode(median,kernel,iterations = 1) # In[37]: dilation = cv2.dilate(erosion,kernel,iterations = 5) # In[38]: #erosion followed dilation closing = cv2.morphologyEx(dilation, cv2.MORPH_CLOSE, kernel) # In[39]: #canny edge detection edges = cv2.Canny(dilation,9,220) # In[40]: #plotting using matplotlib plt.subplot(332),plt.imshow(blur),plt.title('BLURRED') plt.xticks([]), plt.yticks([]) plt.show() # In[41]: plt.subplot(333),plt.imshow(gblur),plt.title('guassianblur') plt.xticks([]), plt.yticks([]) plt.show() # In[42]: plt.subplot(334),plt.imshow(median),plt.title('Medianblur') plt.xticks([]), plt.yticks([]) plt.show() # In[43]: plt.subplot(337),plt.imshow(img,cmap = 'gray') plt.title('dilated Image'), plt.xticks([]), plt.yticks([]) plt.show() # In[44]: plt.subplot(338),plt.imshow(edges,cmap = 'gray') plt.title('Edge Image'), plt.xticks([]), plt.yticks([]) plt.show() # In[45]: plt.subplot(335),plt.imshow(erosion),plt.title('EROSION') plt.xticks([]), plt.yticks([]) plt.show() # In[46]: plt.subplot(336),plt.imshow(closing),plt.title('closing') plt.xticks([]), plt.yticks([]) plt.show() # # #### Plot all images # In[47]: #plotting using matplotlib plt.subplot(332),plt.imshow(blur),plt.title('BLURRED') plt.xticks([]), plt.yticks([]) plt.subplot(333),plt.imshow(gblur),plt.title('guassianblur') plt.xticks([]), plt.yticks([]) plt.subplot(334),plt.imshow(median),plt.title('Medianblur') plt.xticks([]), plt.yticks([]) plt.subplot(337),plt.imshow(img,cmap = 'gray') plt.title('dilated Image'), plt.xticks([]), plt.yticks([]) plt.subplot(338),plt.imshow(edges,cmap = 'gray') plt.title('Edge Image'), plt.xticks([]), plt.yticks([]) plt.subplot(335),plt.imshow(erosion),plt.title('EROSION') plt.xticks([]), plt.yticks([]) plt.subplot(336),plt.imshow(closing),plt.title('closing') plt.xticks([]), plt.yticks([]) plt.show() # #### alerting the driver # In[48]: pygame.init() pygame.mixer.music.load("buzz.mp3") pygame.mixer.music.play() time.sleep(5) # # End of Pothhole Detection Project # In[ ]:
[ "matplotlib.pyplot.title", "cv2.GaussianBlur", "cv2.approxPolyDP", "cv2.arcLength", "cv2.medianBlur", "numpy.ones", "cv2.isContourConvex", "cv2.startWindowThread", "cv2.rectangle", "cv2.erode", "cv2.imshow", "cv2.contourArea", "cv2.dilate", "cv2.cvtColor", "matplotlib.pyplot.imshow", "cv2.imwrite", "matplotlib.pyplot.yticks", "pygame.mixer.music.play", "cv2.drawContours", "cv2.destroyAllWindows", "matplotlib.pyplot.xticks", "cv2.boundingRect", "cv2.resize", "cv2.Canny", "matplotlib.pyplot.show", "cv2.waitKey", "cv2.morphologyEx", "pygame.init", "time.sleep", "matplotlib.pyplot.subplot", "cv2.putText", "cv2.threshold", "cv2.moments", "matplotlib.pyplot.axis", "cv2.blur", "cv2.imread", "cv2.destroyWindow", "pygame.mixer.music.load", "cv2.findContours" ]
[((426, 449), 'cv2.startWindowThread', 'cv2.startWindowThread', ([], {}), '()\n', (447, 449), False, 'import cv2\n'), ((1707, 1728), 'cv2.imread', 'cv2.imread', (['file_name'], {}), '(file_name)\n', (1717, 1728), False, 'import cv2\n'), ((1835, 1861), 'matplotlib.pyplot.title', 'plt.title', (['"""Pothole Image"""'], {}), "('Pothole Image')\n", (1844, 1861), True, 'from matplotlib import pyplot as plt\n'), ((1862, 1882), 'matplotlib.pyplot.imshow', 'plt.imshow', (['r_image2'], {}), '(r_image2)\n', (1872, 1882), True, 'from matplotlib import pyplot as plt\n'), ((1883, 1893), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1891, 1893), True, 'from matplotlib import pyplot as plt\n'), ((2082, 2118), 'cv2.cvtColor', 'cv2.cvtColor', (['im', 'cv2.COLOR_BGR2GRAY'], {}), '(im, cv2.COLOR_BGR2GRAY)\n', (2094, 2118), False, 'import cv2\n'), ((2165, 2198), 'cv2.imwrite', 'cv2.imwrite', (['"""grayImg.jpg"""', 'gray1'], {}), "('grayImg.jpg', gray1)\n", (2176, 2198), False, 'import cv2\n'), ((2253, 2289), 'cv2.cvtColor', 'cv2.cvtColor', (['im', 'cv2.COLOR_BGR2GRAY'], {}), '(im, cv2.COLOR_BGR2GRAY)\n', (2265, 2289), False, 'import cv2\n'), ((2333, 2367), 'cv2.threshold', 'cv2.threshold', (['imgray', '(127)', '(255)', '(0)'], {}), '(imgray, 127, 255, 0)\n', (2346, 2367), False, 'import cv2\n'), ((2491, 2553), 'cv2.findContours', 'cv2.findContours', (['thresh', 'cv2.RETR_TREE', 'cv2.CHAIN_APPROX_NONE'], {}), '(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n', (2507, 2553), False, 'import cv2\n'), ((2741, 2805), 'cv2.findContours', 'cv2.findContours', (['thresh', 'cv2.RETR_TREE', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n', (2757, 2805), False, 'import cv2\n'), ((2937, 2990), 'cv2.drawContours', 'cv2.drawContours', (['img2', 'contours2', '(-1)', '(0, 250, 0)', '(1)'], {}), '(img2, contours2, -1, (0, 250, 0), 1)\n', (2953, 2990), False, 'import cv2\n'), ((3002, 3041), 'matplotlib.pyplot.title', 'plt.title', (['"""drawContours Pothole Image"""'], {}), "('drawContours Pothole Image')\n", (3011, 3041), True, 'from matplotlib import pyplot as plt\n'), ((3042, 3057), 'matplotlib.pyplot.imshow', 'plt.imshow', (['out'], {}), '(out)\n', (3052, 3057), True, 'from matplotlib import pyplot as plt\n'), ((3058, 3068), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3066, 3068), True, 'from matplotlib import pyplot as plt\n'), ((3109, 3133), 'cv2.imshow', 'cv2.imshow', (['"""img1"""', 'img2'], {}), "('img1', img2)\n", (3119, 3133), False, 'import cv2\n'), ((3133, 3147), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (3144, 3147), False, 'import cv2\n'), ((3249, 3276), 'cv2.imread', 'cv2.imread', (['"""index2.jpg"""', '(0)'], {}), "('index2.jpg', 0)\n", (3259, 3276), False, 'import cv2\n'), ((3331, 3362), 'cv2.threshold', 'cv2.threshold', (['img', '(127)', '(255)', '(0)'], {}), '(img, 127, 255, 0)\n', (3344, 3362), False, 'import cv2\n'), ((3403, 3433), 'cv2.findContours', 'cv2.findContours', (['thresh', '(1)', '(2)'], {}), '(thresh, 1, 2)\n', (3419, 3433), False, 'import cv2\n'), ((3470, 3486), 'cv2.moments', 'cv2.moments', (['cnt'], {}), '(cnt)\n', (3481, 3486), False, 'import cv2\n'), ((3522, 3546), 'cv2.arcLength', 'cv2.arcLength', (['cnt', '(True)'], {}), '(cnt, True)\n', (3535, 3546), False, 'import cv2\n'), ((3585, 3605), 'cv2.contourArea', 'cv2.contourArea', (['cnt'], {}), '(cnt)\n', (3600, 3605), False, 'import cv2\n'), ((3680, 3716), 'cv2.approxPolyDP', 'cv2.approxPolyDP', (['cnt', 'epsilon', '(True)'], {}), '(cnt, epsilon, True)\n', (3696, 3716), False, 'import cv2\n'), ((4109, 4133), 'cv2.imshow', 'cv2.imshow', (['"""Show"""', 'img2'], {}), "('Show', img2)\n", (4119, 4133), False, 'import cv2\n'), ((4169, 4183), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (4180, 4183), False, 'import cv2\n'), ((4225, 4238), 'cv2.waitKey', 'cv2.waitKey', ([], {}), '()\n', (4236, 4238), False, 'import cv2\n'), ((4239, 4262), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (4260, 4262), False, 'import cv2\n'), ((4281, 4305), 'cv2.isContourConvex', 'cv2.isContourConvex', (['cnt'], {}), '(cnt)\n', (4300, 4305), False, 'import cv2\n'), ((4342, 4362), 'cv2.blur', 'cv2.blur', (['im', '(5, 5)'], {}), '(im, (5, 5))\n', (4350, 4362), False, 'import cv2\n'), ((4427, 4458), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['im', '(5, 5)', '(0)'], {}), '(im, (5, 5), 0)\n', (4443, 4458), False, 'import cv2\n'), ((4503, 4524), 'cv2.medianBlur', 'cv2.medianBlur', (['im', '(5)'], {}), '(im, 5)\n', (4517, 4524), False, 'import cv2\n'), ((4573, 4598), 'numpy.ones', 'np.ones', (['(5, 5)', 'np.uint8'], {}), '((5, 5), np.uint8)\n', (4580, 4598), True, 'import numpy as np\n'), ((4607, 4646), 'cv2.erode', 'cv2.erode', (['median', 'kernel'], {'iterations': '(1)'}), '(median, kernel, iterations=1)\n', (4616, 4646), False, 'import cv2\n'), ((4672, 4713), 'cv2.dilate', 'cv2.dilate', (['erosion', 'kernel'], {'iterations': '(5)'}), '(erosion, kernel, iterations=5)\n', (4682, 4713), False, 'import cv2\n'), ((4765, 4816), 'cv2.morphologyEx', 'cv2.morphologyEx', (['dilation', 'cv2.MORPH_CLOSE', 'kernel'], {}), '(dilation, cv2.MORPH_CLOSE, kernel)\n', (4781, 4816), False, 'import cv2\n'), ((4861, 4888), 'cv2.Canny', 'cv2.Canny', (['dilation', '(9)', '(220)'], {}), '(dilation, 9, 220)\n', (4870, 4888), False, 'import cv2\n'), ((5014, 5024), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5022, 5024), True, 'from matplotlib import pyplot as plt\n'), ((5131, 5141), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5139, 5141), True, 'from matplotlib import pyplot as plt\n'), ((5247, 5257), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5255, 5257), True, 'from matplotlib import pyplot as plt\n'), ((5378, 5388), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5386, 5388), True, 'from matplotlib import pyplot as plt\n'), ((5508, 5518), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5516, 5518), True, 'from matplotlib import pyplot as plt\n'), ((5622, 5632), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5630, 5632), True, 'from matplotlib import pyplot as plt\n'), ((5736, 5746), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5744, 5746), True, 'from matplotlib import pyplot as plt\n'), ((6472, 6482), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6480, 6482), True, 'from matplotlib import pyplot as plt\n'), ((6525, 6538), 'pygame.init', 'pygame.init', ([], {}), '()\n', (6536, 6538), False, 'import pygame\n'), ((6539, 6574), 'pygame.mixer.music.load', 'pygame.mixer.music.load', (['"""buzz.mp3"""'], {}), "('buzz.mp3')\n", (6562, 6574), False, 'import pygame\n'), ((6575, 6600), 'pygame.mixer.music.play', 'pygame.mixer.music.play', ([], {}), '()\n', (6598, 6600), False, 'import pygame\n'), ((6601, 6614), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (6611, 6614), False, 'import time\n'), ((570, 585), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (578, 585), True, 'from matplotlib import pyplot as plt\n'), ((590, 606), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (599, 606), True, 'from matplotlib import pyplot as plt\n'), ((697, 735), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image'], {'cmap': 'plt.cm.Greys_r'}), '(image, cmap=plt.cm.Greys_r)\n', (707, 735), True, 'from matplotlib import pyplot as plt\n'), ((740, 750), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (748, 750), True, 'from matplotlib import pyplot as plt\n'), ((1586, 1629), 'cv2.resize', 'cv2.resize', (['image', 'dim'], {'interpolation': 'inter'}), '(image, dim, interpolation=inter)\n', (1596, 1629), False, 'import cv2\n'), ((3148, 3164), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(331)'], {}), '(331)\n', (3159, 3164), True, 'from matplotlib import pyplot as plt\n'), ((3165, 3179), 'matplotlib.pyplot.imshow', 'plt.imshow', (['im'], {}), '(im)\n', (3175, 3179), True, 'from matplotlib import pyplot as plt\n'), ((3180, 3197), 'matplotlib.pyplot.title', 'plt.title', (['"""GRAY"""'], {}), "('GRAY')\n", (3189, 3197), True, 'from matplotlib import pyplot as plt\n'), ((3198, 3212), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (3208, 3212), True, 'from matplotlib import pyplot as plt\n'), ((3214, 3228), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (3224, 3228), True, 'from matplotlib import pyplot as plt\n'), ((3647, 3671), 'cv2.arcLength', 'cv2.arcLength', (['cnt', '(True)'], {}), '(cnt, True)\n', (3660, 3671), False, 'import cv2\n'), ((3790, 3809), 'cv2.boundingRect', 'cv2.boundingRect', (['c'], {}), '(c)\n', (3806, 3809), False, 'import cv2\n'), ((3911, 3970), 'cv2.rectangle', 'cv2.rectangle', (['img2', '(x, y)', '(x + w, y + h)', '(0, 255, 0)', '(8)'], {}), '(img2, (x, y), (x + w, y + h), (0, 255, 0), 8)\n', (3924, 3970), False, 'import cv2\n'), ((3963, 4039), 'cv2.putText', 'cv2.putText', (['img2', '"""Moth Detected"""', '(x + w + 40, y + h)', '(0)', '(2.0)', '(0, 255, 0)'], {}), "(img2, 'Moth Detected', (x + w + 40, y + h), 0, 2.0, (0, 255, 0))\n", (3974, 4039), False, 'import cv2\n'), ((4031, 4071), 'matplotlib.pyplot.title', 'plt.title', (['"""Moth Detected Pothole Image"""'], {}), "('Moth Detected Pothole Image')\n", (4040, 4071), True, 'from matplotlib import pyplot as plt\n'), ((4076, 4092), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img2'], {}), '(img2)\n', (4086, 4092), True, 'from matplotlib import pyplot as plt\n'), ((4097, 4107), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4105, 4107), True, 'from matplotlib import pyplot as plt\n'), ((4200, 4224), 'cv2.destroyWindow', 'cv2.destroyWindow', (['"""img"""'], {}), "('img')\n", (4217, 4224), False, 'import cv2\n'), ((4928, 4944), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(332)'], {}), '(332)\n', (4939, 4944), True, 'from matplotlib import pyplot as plt\n'), ((4945, 4961), 'matplotlib.pyplot.imshow', 'plt.imshow', (['blur'], {}), '(blur)\n', (4955, 4961), True, 'from matplotlib import pyplot as plt\n'), ((4962, 4982), 'matplotlib.pyplot.title', 'plt.title', (['"""BLURRED"""'], {}), "('BLURRED')\n", (4971, 4982), True, 'from matplotlib import pyplot as plt\n'), ((4983, 4997), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (4993, 4997), True, 'from matplotlib import pyplot as plt\n'), ((4999, 5013), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (5009, 5013), True, 'from matplotlib import pyplot as plt\n'), ((5039, 5055), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(333)'], {}), '(333)\n', (5050, 5055), True, 'from matplotlib import pyplot as plt\n'), ((5056, 5073), 'matplotlib.pyplot.imshow', 'plt.imshow', (['gblur'], {}), '(gblur)\n', (5066, 5073), True, 'from matplotlib import pyplot as plt\n'), ((5074, 5099), 'matplotlib.pyplot.title', 'plt.title', (['"""guassianblur"""'], {}), "('guassianblur')\n", (5083, 5099), True, 'from matplotlib import pyplot as plt\n'), ((5100, 5114), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (5110, 5114), True, 'from matplotlib import pyplot as plt\n'), ((5116, 5130), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (5126, 5130), True, 'from matplotlib import pyplot as plt\n'), ((5156, 5172), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(334)'], {}), '(334)\n', (5167, 5172), True, 'from matplotlib import pyplot as plt\n'), ((5173, 5191), 'matplotlib.pyplot.imshow', 'plt.imshow', (['median'], {}), '(median)\n', (5183, 5191), True, 'from matplotlib import pyplot as plt\n'), ((5192, 5215), 'matplotlib.pyplot.title', 'plt.title', (['"""Medianblur"""'], {}), "('Medianblur')\n", (5201, 5215), True, 'from matplotlib import pyplot as plt\n'), ((5216, 5230), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (5226, 5230), True, 'from matplotlib import pyplot as plt\n'), ((5232, 5246), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (5242, 5246), True, 'from matplotlib import pyplot as plt\n'), ((5272, 5288), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(337)'], {}), '(337)\n', (5283, 5288), True, 'from matplotlib import pyplot as plt\n'), ((5289, 5317), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {'cmap': '"""gray"""'}), "(img, cmap='gray')\n", (5299, 5317), True, 'from matplotlib import pyplot as plt\n'), ((5319, 5345), 'matplotlib.pyplot.title', 'plt.title', (['"""dilated Image"""'], {}), "('dilated Image')\n", (5328, 5345), True, 'from matplotlib import pyplot as plt\n'), ((5347, 5361), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (5357, 5361), True, 'from matplotlib import pyplot as plt\n'), ((5363, 5377), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (5373, 5377), True, 'from matplotlib import pyplot as plt\n'), ((5403, 5419), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(338)'], {}), '(338)\n', (5414, 5419), True, 'from matplotlib import pyplot as plt\n'), ((5420, 5450), 'matplotlib.pyplot.imshow', 'plt.imshow', (['edges'], {'cmap': '"""gray"""'}), "(edges, cmap='gray')\n", (5430, 5450), True, 'from matplotlib import pyplot as plt\n'), ((5452, 5475), 'matplotlib.pyplot.title', 'plt.title', (['"""Edge Image"""'], {}), "('Edge Image')\n", (5461, 5475), True, 'from matplotlib import pyplot as plt\n'), ((5477, 5491), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (5487, 5491), True, 'from matplotlib import pyplot as plt\n'), ((5493, 5507), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (5503, 5507), True, 'from matplotlib import pyplot as plt\n'), ((5533, 5549), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(335)'], {}), '(335)\n', (5544, 5549), True, 'from matplotlib import pyplot as plt\n'), ((5550, 5569), 'matplotlib.pyplot.imshow', 'plt.imshow', (['erosion'], {}), '(erosion)\n', (5560, 5569), True, 'from matplotlib import pyplot as plt\n'), ((5570, 5590), 'matplotlib.pyplot.title', 'plt.title', (['"""EROSION"""'], {}), "('EROSION')\n", (5579, 5590), True, 'from matplotlib import pyplot as plt\n'), ((5591, 5605), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (5601, 5605), True, 'from matplotlib import pyplot as plt\n'), ((5607, 5621), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (5617, 5621), True, 'from matplotlib import pyplot as plt\n'), ((5647, 5663), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(336)'], {}), '(336)\n', (5658, 5663), True, 'from matplotlib import pyplot as plt\n'), ((5664, 5683), 'matplotlib.pyplot.imshow', 'plt.imshow', (['closing'], {}), '(closing)\n', (5674, 5683), True, 'from matplotlib import pyplot as plt\n'), ((5684, 5704), 'matplotlib.pyplot.title', 'plt.title', (['"""closing"""'], {}), "('closing')\n", (5693, 5704), True, 'from matplotlib import pyplot as plt\n'), ((5705, 5719), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (5715, 5719), True, 'from matplotlib import pyplot as plt\n'), ((5721, 5735), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (5731, 5735), True, 'from matplotlib import pyplot as plt\n'), ((5814, 5830), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(332)'], {}), '(332)\n', (5825, 5830), True, 'from matplotlib import pyplot as plt\n'), ((5831, 5847), 'matplotlib.pyplot.imshow', 'plt.imshow', (['blur'], {}), '(blur)\n', (5841, 5847), True, 'from matplotlib import pyplot as plt\n'), ((5848, 5868), 'matplotlib.pyplot.title', 'plt.title', (['"""BLURRED"""'], {}), "('BLURRED')\n", (5857, 5868), True, 'from matplotlib import pyplot as plt\n'), ((5869, 5883), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (5879, 5883), True, 'from matplotlib import pyplot as plt\n'), ((5885, 5899), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (5895, 5899), True, 'from matplotlib import pyplot as plt\n'), ((5900, 5916), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(333)'], {}), '(333)\n', (5911, 5916), True, 'from matplotlib import pyplot as plt\n'), ((5917, 5934), 'matplotlib.pyplot.imshow', 'plt.imshow', (['gblur'], {}), '(gblur)\n', (5927, 5934), True, 'from matplotlib import pyplot as plt\n'), ((5935, 5960), 'matplotlib.pyplot.title', 'plt.title', (['"""guassianblur"""'], {}), "('guassianblur')\n", (5944, 5960), True, 'from matplotlib import pyplot as plt\n'), ((5961, 5975), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (5971, 5975), True, 'from matplotlib import pyplot as plt\n'), ((5977, 5991), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (5987, 5991), True, 'from matplotlib import pyplot as plt\n'), ((5992, 6008), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(334)'], {}), '(334)\n', (6003, 6008), True, 'from matplotlib import pyplot as plt\n'), ((6009, 6027), 'matplotlib.pyplot.imshow', 'plt.imshow', (['median'], {}), '(median)\n', (6019, 6027), True, 'from matplotlib import pyplot as plt\n'), ((6028, 6051), 'matplotlib.pyplot.title', 'plt.title', (['"""Medianblur"""'], {}), "('Medianblur')\n", (6037, 6051), True, 'from matplotlib import pyplot as plt\n'), ((6052, 6066), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (6062, 6066), True, 'from matplotlib import pyplot as plt\n'), ((6068, 6082), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (6078, 6082), True, 'from matplotlib import pyplot as plt\n'), ((6083, 6099), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(337)'], {}), '(337)\n', (6094, 6099), True, 'from matplotlib import pyplot as plt\n'), ((6100, 6128), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {'cmap': '"""gray"""'}), "(img, cmap='gray')\n", (6110, 6128), True, 'from matplotlib import pyplot as plt\n'), ((6130, 6156), 'matplotlib.pyplot.title', 'plt.title', (['"""dilated Image"""'], {}), "('dilated Image')\n", (6139, 6156), True, 'from matplotlib import pyplot as plt\n'), ((6158, 6172), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (6168, 6172), True, 'from matplotlib import pyplot as plt\n'), ((6174, 6188), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (6184, 6188), True, 'from matplotlib import pyplot as plt\n'), ((6189, 6205), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(338)'], {}), '(338)\n', (6200, 6205), True, 'from matplotlib import pyplot as plt\n'), ((6206, 6236), 'matplotlib.pyplot.imshow', 'plt.imshow', (['edges'], {'cmap': '"""gray"""'}), "(edges, cmap='gray')\n", (6216, 6236), True, 'from matplotlib import pyplot as plt\n'), ((6238, 6261), 'matplotlib.pyplot.title', 'plt.title', (['"""Edge Image"""'], {}), "('Edge Image')\n", (6247, 6261), True, 'from matplotlib import pyplot as plt\n'), ((6263, 6277), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (6273, 6277), True, 'from matplotlib import pyplot as plt\n'), ((6279, 6293), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (6289, 6293), True, 'from matplotlib import pyplot as plt\n'), ((6294, 6310), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(335)'], {}), '(335)\n', (6305, 6310), True, 'from matplotlib import pyplot as plt\n'), ((6311, 6330), 'matplotlib.pyplot.imshow', 'plt.imshow', (['erosion'], {}), '(erosion)\n', (6321, 6330), True, 'from matplotlib import pyplot as plt\n'), ((6331, 6351), 'matplotlib.pyplot.title', 'plt.title', (['"""EROSION"""'], {}), "('EROSION')\n", (6340, 6351), True, 'from matplotlib import pyplot as plt\n'), ((6352, 6366), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (6362, 6366), True, 'from matplotlib import pyplot as plt\n'), ((6368, 6382), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (6378, 6382), True, 'from matplotlib import pyplot as plt\n'), ((6383, 6399), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(336)'], {}), '(336)\n', (6394, 6399), True, 'from matplotlib import pyplot as plt\n'), ((6400, 6419), 'matplotlib.pyplot.imshow', 'plt.imshow', (['closing'], {}), '(closing)\n', (6410, 6419), True, 'from matplotlib import pyplot as plt\n'), ((6420, 6440), 'matplotlib.pyplot.title', 'plt.title', (['"""closing"""'], {}), "('closing')\n", (6429, 6440), True, 'from matplotlib import pyplot as plt\n'), ((6441, 6455), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (6451, 6455), True, 'from matplotlib import pyplot as plt\n'), ((6457, 6471), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (6467, 6471), True, 'from matplotlib import pyplot as plt\n'), ((527, 565), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2RGB'], {}), '(image, cv2.COLOR_BGR2RGB)\n', (539, 565), False, 'import cv2\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 5 22:36:16 2017 @author: root """ import nltk import numpy as np import tflearn import tensorflow as tf import random # restore all of our data structures import pickle from nltk.stem.lancaster import LancasterStemmer stemmer = LancasterStemmer() data = pickle.load( open( "F:/Projects II/speech/responseEngine/training_data.p", "rb" ) ) words = data['words'] classes = data['classes'] train_x = data['train_x'] train_y = data['train_y'] # import our chat-bot intents file import json with open('F:/Projects II/speech/responseEngine/intents.json') as json_data: intents = json.load(json_data) # load our saved model tf.reset_default_graph() # Build neural network net = tflearn.input_data(shape=[None, len(train_x[0])]) net = tflearn.fully_connected(net, 8) net = tflearn.fully_connected(net, 8) net = tflearn.fully_connected(net, len(train_y[0]), activation='softmax') net = tflearn.regression(net) # Define model and setup tensorboard new_model = tflearn.DNN(net, tensorboard_verbose=3) new_model.load('F:/Projects II/speech/responseEngine/model.tflearn') def clean_up_sentence(sentence): # tokenize the pattern sentence_words = nltk.word_tokenize(sentence) # stem each word sentence_words = [stemmer.stem(word.lower()) for word in sentence_words] return sentence_words # return bag of words array: 0 or 1 for each word in the bag that exists in the sentence def bow(sentence, words, show_details=False): # tokenize the pattern sentence_words = clean_up_sentence(sentence) # bag of words bag = [0]*len(words) for s in sentence_words: for i,w in enumerate(words): if w == s: bag[i] = 1 if show_details: print ("found in bag: %s" % w) return(np.array(bag)) # create a data structure to hold user context context = {} ERROR_THRESHOLD = 0.25 def classify(sentence): # generate probabilities from the model results = new_model.predict([bow(sentence, words)])[0] # filter out predictions below a threshold results = [[i,r] for i,r in enumerate(results) if r>ERROR_THRESHOLD] # sort by strength of probability results.sort(key=lambda x: x[1], reverse=True) return_list = [] for r in results: return_list.append((classes[r[0]], r[1])) # return tuple of intent and probability return return_list def response(sentence, userID='123', show_details=False): results = classify(sentence) # if we have a classification then find the matching intent tag if results: # loop as long as there are matches to process while results: for i in intents['intents']: # find a tag matching the first result if i['tag'] == results[0][0]: # set context for this intent if necessary if 'context_set' in i: if show_details: print ('context:', i['context_set']) context[userID] = i['context_set'] # check if this intent is contextual and applies to this user's conversation if not 'context_filter' in i or \ (userID in context and 'context_filter' in i and i['context_filter'] == context[userID]): if show_details: print ('tag:', i['tag']) # a random response from the intent return(random.choice(i['responses'])) results.pop(0) if i['tag'] == results[0][0]: # set context for this intent if necessary if 'context_set' in i: if show_details: print ('context:', i['context_set']) context[userID] = i['context_set'] # check if this intent is contextual and applies to this user's conversation if not 'context_filter' in i or \ (userID in context and 'context_filter' in i and i['context_filter'] == context[userID]): if show_details: print ('tag:', i['tag']) # a random response from the intent return(random.choice(i['responses'])) def botActs(statement): #engine=pyttsx3.init() #message =all_ears() # while(1): # message=input("You:") # category= [x[0] for x in classify(message)] # print(category[0]) # reply=response(message) # print("Classifier:-", reply) # if (category[0] =='goodbye'): # break category= [x[0] for x in classify(statement)] print(category[0]) reply=response(statement) print("Classifier:-", reply)
[ "json.load", "tflearn.fully_connected", "tensorflow.reset_default_graph", "random.choice", "tflearn.regression", "nltk.stem.lancaster.LancasterStemmer", "tflearn.DNN", "numpy.array", "nltk.word_tokenize" ]
[((302, 320), 'nltk.stem.lancaster.LancasterStemmer', 'LancasterStemmer', ([], {}), '()\n', (318, 320), False, 'from nltk.stem.lancaster import LancasterStemmer\n'), ((697, 721), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (719, 721), True, 'import tensorflow as tf\n'), ((807, 838), 'tflearn.fully_connected', 'tflearn.fully_connected', (['net', '(8)'], {}), '(net, 8)\n', (830, 838), False, 'import tflearn\n'), ((845, 876), 'tflearn.fully_connected', 'tflearn.fully_connected', (['net', '(8)'], {}), '(net, 8)\n', (868, 876), False, 'import tflearn\n'), ((957, 980), 'tflearn.regression', 'tflearn.regression', (['net'], {}), '(net)\n', (975, 980), False, 'import tflearn\n'), ((1031, 1070), 'tflearn.DNN', 'tflearn.DNN', (['net'], {'tensorboard_verbose': '(3)'}), '(net, tensorboard_verbose=3)\n', (1042, 1070), False, 'import tflearn\n'), ((652, 672), 'json.load', 'json.load', (['json_data'], {}), '(json_data)\n', (661, 672), False, 'import json\n'), ((1224, 1252), 'nltk.word_tokenize', 'nltk.word_tokenize', (['sentence'], {}), '(sentence)\n', (1242, 1252), False, 'import nltk\n'), ((1848, 1861), 'numpy.array', 'np.array', (['bag'], {}), '(bag)\n', (1856, 1861), True, 'import numpy as np\n'), ((4275, 4304), 'random.choice', 'random.choice', (["i['responses']"], {}), "(i['responses'])\n", (4288, 4304), False, 'import random\n'), ((3507, 3536), 'random.choice', 'random.choice', (["i['responses']"], {}), "(i['responses'])\n", (3520, 3536), False, 'import random\n')]
""" N-dimensional grids. """ __author__ = "<NAME>" __copyright__ = "Copyright 2014, Stanford University" __license__ = "3-clause BSD" import numpy as np class Grid(object): """ N-dimensional grid. Parameters ---------- shape : tuple Number of grid points in each dimension. center : tuple, optional (defaults to the origin) Grid center. spacing : float, optional (defaults to 1.) Space between grid points. dtype : numpy dtype, optional (defaults to float) Grid data type. """ def __init__(self, shape, center=None, spacing=1., dtype=float): self.grid = np.zeros(shape, dtype=dtype) self.shape = self.grid.shape self.size = self.grid.size self.ndim = self.grid.ndim if center is None: self.center = np.zeros_like(self.shape, dtype=float) else: self.center = np.asarray(center, dtype=float) self.spacing = float(spacing) def __getitem__(self, item): rval = self.grid[item] return rval def __setitem__(self, key, value): self.grid[key] = value def get_real_shape(self): """ Get the shape of the grid in real-space. """ return tuple(np.asarray(self.shape) * self.spacing) def grid_point_in_grid(self, grid_point): """ Check whether a grid point is in the grid. Parameters ---------- grid_point : tuple Grid point. """ # get the maximum indices and see if they exist test_point = np.amax(np.atleast_2d(grid_point), axis=0) try: _ = self.grid[test_point] return True except IndexError: return False def coords_in_grid(self, coords): """ Check whether a real-space point is in the grid. Parameters ---------- coords : tuple Real-space coordinates. """ try: self.get_grid_point(coords) except IndexError: return False else: return True def get_coords(self, grid_points): """ Get real-space coordinates for one or more grid points. Procedure --------- 1. Get the real-space coordinates of the grid point relative to the grid origin (grid[0, ..., 0]). 2. Get the real-space translation of the grid center relative to the grid origin. 3. Subtract (2) from (1) to get the real-space coordinates of the grid point relative to the grid center rather than the grid origin. 4. Translate the coordinates from (3) so they are relative to the real-space grid center. Parameters ---------- grid_points : array_like Grid point(s). """ assert np.atleast_2d(grid_points).ndim == 2 if not self.grid_point_in_grid(grid_points): raise IndexError("Invalid grid point '{}'".format(grid_points)) coords = np.array(grid_points, dtype=float) * self.spacing grid_center = (np.asarray(self.shape) - 1) / 2. * self.spacing coords -= grid_center # move from grid_origin to grid_center coords += self.center # move to real-space center return coords def get_all_coords(self): """ Get real-space coordinates for all grid points. """ # construct an array whose entries correspond to each index of the grid # e.g. grid_points[1, 2, 3] -> [1, 2, 3] grid_points = np.zeros((self.grid.shape + (self.grid.ndim,)), dtype=int) for i, indices in enumerate(np.indices(grid_points.shape[:-1])): grid_points[..., i] = indices # reshape so grid_points is 2D and each row is a grid point grid_points = grid_points.reshape((self.size, self.ndim)) # get real-space coordinates for all grid points # reshape to match shape of the grid # e.g. coords[1, 2, 3] -> self.get_coords([1, 2, 3]) coords = self.get_coords(grid_points).reshape( (self.grid.shape + (self.grid.ndim,))) return coords def get_grid_point(self, coords): """ Get the grid point(s) closest to a set of real-space coordinates. Parameters ---------- coords : array_like Real-space coordinates. """ coords = np.array(coords, dtype=float) coords -= self.center center = (np.asarray(self.shape) - 1) / 2. * self.spacing coords += center coords /= self.spacing grid_points = np.asarray(np.rint(coords), dtype=int) if not self.grid_point_in_grid(grid_points): raise IndexError("Invalid grid point '{}'".format(grid_points)) return grid_points
[ "numpy.zeros_like", "numpy.asarray", "numpy.zeros", "numpy.indices", "numpy.rint", "numpy.array", "numpy.atleast_2d" ]
[((639, 667), 'numpy.zeros', 'np.zeros', (['shape'], {'dtype': 'dtype'}), '(shape, dtype=dtype)\n', (647, 667), True, 'import numpy as np\n'), ((3600, 3656), 'numpy.zeros', 'np.zeros', (['(self.grid.shape + (self.grid.ndim,))'], {'dtype': 'int'}), '(self.grid.shape + (self.grid.ndim,), dtype=int)\n', (3608, 3656), True, 'import numpy as np\n'), ((4489, 4518), 'numpy.array', 'np.array', (['coords'], {'dtype': 'float'}), '(coords, dtype=float)\n', (4497, 4518), True, 'import numpy as np\n'), ((828, 866), 'numpy.zeros_like', 'np.zeros_like', (['self.shape'], {'dtype': 'float'}), '(self.shape, dtype=float)\n', (841, 866), True, 'import numpy as np\n'), ((907, 938), 'numpy.asarray', 'np.asarray', (['center'], {'dtype': 'float'}), '(center, dtype=float)\n', (917, 938), True, 'import numpy as np\n'), ((1595, 1620), 'numpy.atleast_2d', 'np.atleast_2d', (['grid_point'], {}), '(grid_point)\n', (1608, 1620), True, 'import numpy as np\n'), ((3065, 3099), 'numpy.array', 'np.array', (['grid_points'], {'dtype': 'float'}), '(grid_points, dtype=float)\n', (3073, 3099), True, 'import numpy as np\n'), ((3726, 3760), 'numpy.indices', 'np.indices', (['grid_points.shape[:-1]'], {}), '(grid_points.shape[:-1])\n', (3736, 3760), True, 'import numpy as np\n'), ((4704, 4719), 'numpy.rint', 'np.rint', (['coords'], {}), '(coords)\n', (4711, 4719), True, 'import numpy as np\n'), ((1258, 1280), 'numpy.asarray', 'np.asarray', (['self.shape'], {}), '(self.shape)\n', (1268, 1280), True, 'import numpy as np\n'), ((2882, 2908), 'numpy.atleast_2d', 'np.atleast_2d', (['grid_points'], {}), '(grid_points)\n', (2895, 2908), True, 'import numpy as np\n'), ((3138, 3160), 'numpy.asarray', 'np.asarray', (['self.shape'], {}), '(self.shape)\n', (3148, 3160), True, 'import numpy as np\n'), ((4567, 4589), 'numpy.asarray', 'np.asarray', (['self.shape'], {}), '(self.shape)\n', (4577, 4589), True, 'import numpy as np\n')]
import cv2 import os import numpy as np ROOT_PATH = 'G:\\MachineLearning\\unbalance\\core_500' image_path = os.path.join(ROOT_PATH, 'Image') # 原图像保存位置 annotation_path = os.path.join(ROOT_PATH, 'Annotation') # 原目标框保存位置 image_save_path = os.path.join(ROOT_PATH, 'Image_new') # 原目标框保存位置 annotation_save_path = os.path.join(ROOT_PATH, 'Annotation_new') # 原目标框保存位置 def img_flip(img_path, annot_path, new_name): img = cv2.imread(img_path) img_h, img_w = img.shape[:2] new_img = cv2.flip(img, 1) #水平翻转图片 img_name = 'core_battery' + new_name + '.jpg' new_img_path = os.path.join(image_save_path, img_name) cv2.imwrite(new_img_path, new_img) with open(annot_path, encoding='utf-8') as fp: lines = fp.readlines() annot_str = '' for line in lines: temp = line.split() name = temp[1] # 只读两类 if name != '带电芯充电宝' and name != '不带电芯充电宝': continue xmin = int(temp[2]) if xmin > img_w: continue if xmin < 0: xmin = 0 ymin = int(temp[3]) if ymin < 0: ymin = 0 xmax = int(temp[4]) if xmax > img_w: # 是这么个意思吧? xmax = img_w ymax = int(temp[5]) if ymax > img_h: ymax = img_h annot_w = xmax - xmin new_xmin = img_w - xmin - annot_w new_ymin = ymin new_xmax = img_w - xmax + annot_w new_ymax = ymax annot_str += temp[0] + ' ' + temp[1] + ' ' + str(new_xmin) + ' ' + str(new_ymin) + ' ' + str(new_xmax) + ' ' + str(new_ymax) + '\n' annot_name = 'core_battery' + new_name + '.txt' new_annot_path = os.path.join(annotation_save_path, annot_name) with open(new_annot_path, 'w', encoding='utf-8') as fp: fp.write(annot_str) return new_img_path, new_annot_path def img_rot(img_path, annot_path, new_name): img = cv2.imread(img_path) img_h, img_w = img.shape[:2] # 旋转图像 if img_w > img_h: padding = (img_w - img_h) // 2 center = (img_w // 2, img_w // 2) img_padded = np.zeros(shape=(img_w, img_w, 3), dtype=np.uint8) img_padded[padding:padding + img_h, :, :] = img M = cv2.getRotationMatrix2D(center, -90, 1) rotated_padded = cv2.warpAffine(img_padded, M, (img_w, img_w)) new_img = rotated_padded[:, padding:padding + img_h, :] else: padding = (img_h - img_w) // 2 center = (img_h // 2, img_h // 2) img_padded = np.zeros(shape=(img_h, img_h, 3), dtype=np.uint8) img_padded[:, padding:padding + img_w, :] = img M = cv2.getRotationMatrix2D(center, -90, 1) rotated_padded = cv2.warpAffine(img_padded, M, (img_h, img_h)) new_img = rotated_padded[padding:padding + img_w, :, :] img_name = 'core_battery' + new_name + '.jpg' new_img_path = os.path.join(image_save_path, img_name) cv2.imwrite(new_img_path, new_img) with open(annot_path, encoding='utf-8') as fp: lines = fp.readlines() annot_str = '' for line in lines: temp = line.split() name = temp[1] # 只读两类 if name != '带电芯充电宝' and name != '不带电芯充电宝': continue xmin = int(temp[2]) if xmin > img_w: continue if xmin < 0: xmin = 0 ymin = int(temp[3]) if ymin < 0: ymin = 0 xmax = int(temp[4]) if xmax > img_w: # 是这么个意思吧? xmax = img_w ymax = int(temp[5]) if ymax > img_h: ymax = img_h annot_h = ymax - ymin new_xmin = img_h - ymin - annot_h new_ymin = xmin new_xmax = img_h - ymax + annot_h new_ymax = xmax annot_str += temp[0] + ' ' + temp[1] + ' ' + str(new_xmin) + ' ' + str(new_ymin) + ' ' + str(new_xmax) + ' ' + str(new_ymax) + '\n' annot_name = 'core_battery' + new_name + '.txt' new_annot_path = os.path.join(annotation_save_path, annot_name) with open(new_annot_path, 'w', encoding='utf-8') as fp: fp.write(annot_str) return new_img_path, new_annot_path def show_image(img_path, annot_path): with open(annot_path, encoding='utf-8') as fp: lines = fp.readlines() for line in lines: temp = line.split() name = temp[1] # 只读两类 if name != '带电芯充电宝' and name != '不带电芯充电宝': continue xmin = int(temp[2]) ymin = int(temp[3]) xmax = int(temp[4]) ymax = int(temp[5]) img = cv2.imread(img_path) img = cv2.rectangle(img, (xmin, ymin), (xmax, ymax), (0, 0, 255), 2) img = cv2.resize(img, (500, 500)) cv2.imshow('img', img) cv2.waitKey() def img_strength(): if not os.path.isdir(image_save_path): os.mkdir(image_save_path) if not os.path.isdir(annotation_save_path): os.mkdir(annotation_save_path) num_i = 10000000 step = 0 for txt_name in os.listdir(annotation_path): step += 1 print('step:', str(step)) annot_path = os.path.join(annotation_path, txt_name) img_name = txt_name.replace('.txt', '.jpg') img_path = os.path.join(image_path, img_name) img_path, annot_path = img_flip(img_path, annot_path, str(num_i)) num_i += 1 for i in range(3): img_path, annot_path = img_rot(img_path, annot_path, str(num_i)) num_i += 1 img_path, annot_path = img_flip(img_path, annot_path, str(num_i)) num_i += 1 if __name__ == '__main__': img_strength() # index = 0 # for txt_name in os.listdir(annotation_save_path)[20:30]: # annot_path = os.path.join(annotation_save_path, txt_name) # img_name = txt_name.replace('.txt', '.jpg') # img_path = os.path.join(image_save_path, img_name) # show_image(img_path, annot_path)
[ "os.mkdir", "cv2.getRotationMatrix2D", "cv2.waitKey", "cv2.imwrite", "os.path.isdir", "numpy.zeros", "cv2.imread", "cv2.warpAffine", "cv2.rectangle", "cv2.flip", "cv2.imshow", "os.path.join", "os.listdir", "cv2.resize" ]
[((109, 141), 'os.path.join', 'os.path.join', (['ROOT_PATH', '"""Image"""'], {}), "(ROOT_PATH, 'Image')\n", (121, 141), False, 'import os\n'), ((171, 208), 'os.path.join', 'os.path.join', (['ROOT_PATH', '"""Annotation"""'], {}), "(ROOT_PATH, 'Annotation')\n", (183, 208), False, 'import os\n'), ((239, 275), 'os.path.join', 'os.path.join', (['ROOT_PATH', '"""Image_new"""'], {}), "(ROOT_PATH, 'Image_new')\n", (251, 275), False, 'import os\n'), ((311, 352), 'os.path.join', 'os.path.join', (['ROOT_PATH', '"""Annotation_new"""'], {}), "(ROOT_PATH, 'Annotation_new')\n", (323, 352), False, 'import os\n'), ((422, 442), 'cv2.imread', 'cv2.imread', (['img_path'], {}), '(img_path)\n', (432, 442), False, 'import cv2\n'), ((490, 506), 'cv2.flip', 'cv2.flip', (['img', '(1)'], {}), '(img, 1)\n', (498, 506), False, 'import cv2\n'), ((584, 623), 'os.path.join', 'os.path.join', (['image_save_path', 'img_name'], {}), '(image_save_path, img_name)\n', (596, 623), False, 'import os\n'), ((628, 662), 'cv2.imwrite', 'cv2.imwrite', (['new_img_path', 'new_img'], {}), '(new_img_path, new_img)\n', (639, 662), False, 'import cv2\n'), ((1655, 1701), 'os.path.join', 'os.path.join', (['annotation_save_path', 'annot_name'], {}), '(annotation_save_path, annot_name)\n', (1667, 1701), False, 'import os\n'), ((1886, 1906), 'cv2.imread', 'cv2.imread', (['img_path'], {}), '(img_path)\n', (1896, 1906), False, 'import cv2\n'), ((2844, 2883), 'os.path.join', 'os.path.join', (['image_save_path', 'img_name'], {}), '(image_save_path, img_name)\n', (2856, 2883), False, 'import os\n'), ((2888, 2922), 'cv2.imwrite', 'cv2.imwrite', (['new_img_path', 'new_img'], {}), '(new_img_path, new_img)\n', (2899, 2922), False, 'import cv2\n'), ((3914, 3960), 'os.path.join', 'os.path.join', (['annotation_save_path', 'annot_name'], {}), '(annotation_save_path, annot_name)\n', (3926, 3960), False, 'import os\n'), ((4493, 4513), 'cv2.imread', 'cv2.imread', (['img_path'], {}), '(img_path)\n', (4503, 4513), False, 'import cv2\n'), ((4524, 4586), 'cv2.rectangle', 'cv2.rectangle', (['img', '(xmin, ymin)', '(xmax, ymax)', '(0, 0, 255)', '(2)'], {}), '(img, (xmin, ymin), (xmax, ymax), (0, 0, 255), 2)\n', (4537, 4586), False, 'import cv2\n'), ((4597, 4624), 'cv2.resize', 'cv2.resize', (['img', '(500, 500)'], {}), '(img, (500, 500))\n', (4607, 4624), False, 'import cv2\n'), ((4629, 4651), 'cv2.imshow', 'cv2.imshow', (['"""img"""', 'img'], {}), "('img', img)\n", (4639, 4651), False, 'import cv2\n'), ((4656, 4669), 'cv2.waitKey', 'cv2.waitKey', ([], {}), '()\n', (4667, 4669), False, 'import cv2\n'), ((4909, 4936), 'os.listdir', 'os.listdir', (['annotation_path'], {}), '(annotation_path)\n', (4919, 4936), False, 'import os\n'), ((2075, 2124), 'numpy.zeros', 'np.zeros', ([], {'shape': '(img_w, img_w, 3)', 'dtype': 'np.uint8'}), '(shape=(img_w, img_w, 3), dtype=np.uint8)\n', (2083, 2124), True, 'import numpy as np\n'), ((2194, 2233), 'cv2.getRotationMatrix2D', 'cv2.getRotationMatrix2D', (['center', '(-90)', '(1)'], {}), '(center, -90, 1)\n', (2217, 2233), False, 'import cv2\n'), ((2259, 2304), 'cv2.warpAffine', 'cv2.warpAffine', (['img_padded', 'M', '(img_w, img_w)'], {}), '(img_padded, M, (img_w, img_w))\n', (2273, 2304), False, 'import cv2\n'), ((2481, 2530), 'numpy.zeros', 'np.zeros', ([], {'shape': '(img_h, img_h, 3)', 'dtype': 'np.uint8'}), '(shape=(img_h, img_h, 3), dtype=np.uint8)\n', (2489, 2530), True, 'import numpy as np\n'), ((2599, 2638), 'cv2.getRotationMatrix2D', 'cv2.getRotationMatrix2D', (['center', '(-90)', '(1)'], {}), '(center, -90, 1)\n', (2622, 2638), False, 'import cv2\n'), ((2664, 2709), 'cv2.warpAffine', 'cv2.warpAffine', (['img_padded', 'M', '(img_h, img_h)'], {}), '(img_padded, M, (img_h, img_h))\n', (2678, 2709), False, 'import cv2\n'), ((4702, 4732), 'os.path.isdir', 'os.path.isdir', (['image_save_path'], {}), '(image_save_path)\n', (4715, 4732), False, 'import os\n'), ((4742, 4767), 'os.mkdir', 'os.mkdir', (['image_save_path'], {}), '(image_save_path)\n', (4750, 4767), False, 'import os\n'), ((4779, 4814), 'os.path.isdir', 'os.path.isdir', (['annotation_save_path'], {}), '(annotation_save_path)\n', (4792, 4814), False, 'import os\n'), ((4824, 4854), 'os.mkdir', 'os.mkdir', (['annotation_save_path'], {}), '(annotation_save_path)\n', (4832, 4854), False, 'import os\n'), ((5011, 5050), 'os.path.join', 'os.path.join', (['annotation_path', 'txt_name'], {}), '(annotation_path, txt_name)\n', (5023, 5050), False, 'import os\n'), ((5122, 5156), 'os.path.join', 'os.path.join', (['image_path', 'img_name'], {}), '(image_path, img_name)\n', (5134, 5156), False, 'import os\n')]
import tensorflow as tf import numpy as np import logging from global_utils import * import time import json from tensorflow.python.layers import core as layers_core from parametrs import * global data1, data2, vocab, dict_rev, data1_validation, data2_validation, test1, test2 def load_data(parameterClass, length=None): # print('Loading Data...') print('Loading Data...') global data1, data2, vocab, dict_rev, data1_validation, data2_validation, test1, test2 # dataset_path = '../datasets/DailyDialog' t = time.time() vocab, dict_rev = load_vocab_from_csv(parameterClass.vocab_path) print('Vocab loaded') # if length is not None: data1 = load_data_from_csv(parameterClass.train_questions_csv, length) data2 = load_data_from_csv(parameterClass.train_answers_csv, length) # else: # data1 = load_data_from_csv(parameterClass.train_questions_csv) # data2 = load_data_from_csv(parameterClass.train_answers_csv) # data1_validation = load_data_from_csv(validation_questions_csv) # data2_validation = load_data_from_csv(validation_answers_csv) # data1_test = load_data_from_csv(test_questions_csv) # data2_test = load_data_from_csv(test_answers_csv) print('Data is Loaded in', time.time() - t) print('Vocab Length is', len(dict_rev)) print('Number of Training Examples', len(data1)) print('Number of Training Examples', len(data2)) global json_loaded_data global path global train_op global loss global encoder_inputs_placeholder global decoder_inputs_placeholder global decoder_lengths global translations global decoder_targets_placeholder global load global merged_summary def define_graph(parameterClass, address='saved_model', QA=True): global train_op global loss_op global encoder_inputs_placeholder global decoder_inputs_placeholder global decoder_lengths global translations global decoder_targets_placeholder global load global merged_summary global path global json_loaded_data path = address if not os.path.exists(path): os.makedirs(path) print('Model is being created at :', path + parameterClass.config_file) conf = {} with open(path + parameterClass.config_file, 'w', encoding='utf-8') as f: # global json_loaded_data conf['iteration'] = 0 conf['embedding_size'] = parameterClass.embed_size conf['hidden_num'] = parameterClass.hidden_size print(conf) json_string = json.dumps(conf) print(json_string) f.write(json_string) f.flush() json_loaded_data = json.loads(json_string) load = False else: with open(path + parameterClass.config_file, 'r') as f: # global json_loaded_data stri = f.read() print('content loaded :', stri) json_loaded_data = json.loads(stri) # load = False load = True src_vocab_size = len(dict_rev) tgt_vocab_size = len(dict_rev) print(json_loaded_data) embedding_size = json_loaded_data['embedding_size'] hidden_num = json_loaded_data['hidden_num'] encoder_inputs_placeholder = tf.placeholder(shape=(None, None), dtype=tf.int32, name='encoder_inputs') decoder_inputs_placeholder = tf.placeholder(shape=(None, None), dtype=tf.int32, name='decoder_inputs') embeddings1 = tf.Variable(tf.random_uniform([src_vocab_size, embedding_size], -1.0, 1.0)) embeddings2 = None if not QA: embeddings2 = tf.Variable(tf.random_uniform([tgt_vocab_size, embedding_size], -1.0, 1.0)) decoder_inputs_embedded = tf.nn.embedding_lookup(embeddings2, decoder_inputs_placeholder) else: # QA decoder_inputs_embedded = tf.nn.embedding_lookup(embeddings1, decoder_inputs_placeholder) embeddings2 = embeddings1 encoder_inputs_embedded = tf.nn.embedding_lookup(embeddings1, encoder_inputs_placeholder) encoder_cell = tf.contrib.rnn.MultiRNNCell([tf.contrib.rnn.LSTMCell(hidden_num) for i in range(parameterClass.layer_num)]) encoder_outputs, encoder_final_state = tf.nn.dynamic_rnn( encoder_cell, encoder_inputs_embedded, dtype=tf.float32, time_major=True, ) # del encoder_outputs attention_states = tf.transpose(encoder_outputs, [1, 0, 2]) # Create an attention mechanism attention_mechanism = tf.contrib.seq2seq.LuongAttention( hidden_num, attention_states, memory_sequence_length=None) decoder_cell = tf.contrib.rnn.MultiRNNCell([tf.contrib.rnn.LSTMCell(hidden_num) for i in range(parameterClass.layer_num)]) decoder_cell = tf.contrib.seq2seq.AttentionWrapper( decoder_cell, attention_mechanism, attention_layer_size=hidden_num) decoder_lengths = tf.placeholder(tf.int32, shape=parameterClass.batch_size, name="decoder_length") print('decoder length ', decoder_lengths) # batch_size = tf.shape( decoder_lengths)[0] helper = tf.contrib.seq2seq.TrainingHelper(decoder_inputs_embedded, decoder_lengths, time_major=True) projection_layer = layers_core.Dense( tgt_vocab_size, use_bias=False) initial_state = decoder_cell.zero_state(parameterClass.batch_size, tf.float32).clone(cell_state=encoder_final_state) decoder = tf.contrib.seq2seq.BasicDecoder( decoder_cell, helper, initial_state, output_layer=projection_layer) final_outputs, _final_state, _final_sequence_lengths = tf.contrib.seq2seq.dynamic_decode(decoder) logits = final_outputs.rnn_output decoder_targets_placeholder = tf.placeholder(dtype="int32", shape=(parameterClass.batch_size, parameterClass.decoder_length)) # Loss loss_op = tf.nn.sparse_softmax_cross_entropy_with_logits( labels=decoder_targets_placeholder, logits=logits) # Train global_step = tf.Variable(0, name='global_step', trainable=False) # Calculate and clip gradients params = tf.trainable_variables() gradients = tf.gradients(loss_op, params) clipped_gradients, _ = tf.clip_by_global_norm( gradients, max_gradient_norm) # Optimization ## TODO: use specified learning rate optimizer = tf.train.AdamOptimizer(lr) train_op = optimizer.apply_gradients( zip(clipped_gradients, params), global_step=global_step) # Inference inference_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(embeddings2, tf.fill([parameterClass.batch_size], int(dict_rev[start_token])), dict_rev[end_token]) # Inference Decoder inference_decoder = tf.contrib.seq2seq.BasicDecoder( decoder_cell, inference_helper, initial_state, output_layer=projection_layer) # We should specify maximum_iterations, it can't stop otherwise. # source_sequence_length = encoder_length maximum_iterations = tf.round(tf.reduce_max(parameterClass.source_sequence_length) * 2) # Dynamic decoding outputs, _, _ = tf.contrib.seq2seq.dynamic_decode( inference_decoder, maximum_iterations=maximum_iterations) translations = outputs.sample_id def translate(src_sen, parameterClass): src_sen_ = pad_sentence(src_sen.lower(), parameterClass.source_sequence_length) by_index = sentence_by_id(src_sen_, dict_rev) sequence = np.asarray(by_index) print('seq ', sequence) inference_encoder_inputs = np.empty((parameterClass.source_sequence_length, parameterClass.batch_size)) for i in range(0, parameterClass.batch_size): inference_encoder_inputs[:, i] = sequence feed_dict = { encoder_inputs_placeholder: inference_encoder_inputs, decoder_lengths: np.ones(parameterClass.batch_size, dtype=int) * parameterClass.decoder_length } with tf.Session() as sess: sess.run(tf.global_variables_initializer()) saver = tf.train.Saver(tf.global_variables()) if load: print('loading') check_restore_parameters(sess, saver, path + parameterClass.model_file_name) answer = sess.run([translations], feed_dict) print(src_sen) answer = np.reshape(answer, [-1, parameterClass.batch_size]) print(get_sentence_back(answer[0], vocab)) def compute_blue(questions, score_func, parameterClass, session=None): with open(parameterClass.validation_answers, encoding='utf-8') as f: A_lines = f.readlines() answers_given = [] number_of_batches = int(len(A_lines) / parameterClass.batch_size) if session is None: session = tf.Session() session.run(tf.global_variables_initializer()) saver = tf.train.Saver(tf.global_variables()) if load: print('loading Model') check_restore_parameters(session, saver, path + parameterClass.model_file_name) with session as sess: for j in range(0, number_of_batches): enc_inp = np.zeros((parameterClass.source_sequence_length, parameterClass.batch_size), dtype='int') for idx in range(parameterClass.batch_size): enc_inp[:, idx] = questions[j * parameterClass.batch_size + idx][1:-1] feed_dict = { encoder_inputs_placeholder: enc_inp, decoder_lengths: np.ones((batch_size), dtype=int) * (parameterClass.decoder_length) } trans = sess.run([translations], feed_dict=feed_dict) # print('trans_shape :', np.shape(trans)) trans = np.reshape(trans, [-1, parameterClass.batch_size]) for sen in trans: # print('sen', sen) answers_given.append(get_sentence_back(sen, vocab)) score = score_func(A_lines[:number_of_batches * parameterClass.batch_size], answers_given) return score def train(logs_dir, parameterClass, use_tensorBoard=False): global loss_op global train_op global iter_loss_placeholder display_each = 200 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) saver = tf.train.Saver(tf.global_variables()) global path if load: check_restore_parameters(sess, saver, path + parameterClass.model_file_name) num = get_trainable_variables_num() print('Number of trainable variables ', num) number_of_batches = int(len(data1) / parameterClass.batch_size) print('There are ', number_of_batches, ' batches') global json_loaded_data start = json_loaded_data['iteration'] if use_tensorBoard: writer = tf.summary.FileWriter(logs_dir) writer.add_graph(sess.graph) ## TODO: do Early Stopping for i in range(start, epoch_num): iter_loss = 0 iter_time = time.time() for j in range(number_of_batches): enc_inp = np.zeros((parameterClass.source_sequence_length, parameterClass.batch_size), dtype='int') dec_inp = np.zeros((parameterClass.decoder_length, parameterClass.batch_size), dtype='int') dec_tgt = np.zeros((parameterClass.decoder_length, parameterClass.batch_size), dtype='int') # dec_tgt = np.zeros((decoder_length - 1, batch_size, tgt_vocab_size), dtype='int') for idx in range(parameterClass.batch_size): # print('input :', data2[j * batch_size + idx]) dec_inp[:, idx] = data2[j * parameterClass.batch_size + idx][:-1] dec_tgt[:, idx] = data2[j * parameterClass.batch_size + idx][1:] enc_inp[:, idx] = data1[j * parameterClass.batch_size + idx][1:-1] feed_dict = { encoder_inputs_placeholder: enc_inp, decoder_inputs_placeholder: dec_inp, decoder_targets_placeholder: np.transpose(dec_tgt), decoder_lengths: np.ones((parameterClass.batch_size), dtype=int) * (parameterClass.decoder_length) } _, loss = sess.run([train_op, loss_op], feed_dict=feed_dict) # print(np.max(labe)) iter_loss += np.mean(loss) if j % display_each == 0: print('Mini batch loss is ', np.mean(loss)) average_loss = iter_loss / number_of_batches print('Average loss in iteration ', i, ' is ', average_loss) print("It took ", time.time() - iter_time) print('Saving model...') if use_tensorBoard: tf.summary.scalar('loss', iter_loss) iter_loss_placeholder = tf.placeholder(tf.float32, name='iter_loss') tf.summary.scalar("loss", iter_loss_placeholder) merged_summary = tf.summary.merge_all() s = sess.run(merged_summary, feed_dict={iter_loss_placeholder: iter_loss / number_of_batches}) print(merged_summary) writer.add_summary(s, i) else: # print(logs_dir + log_file_name) with open(logs_dir + ".txt", 'a', encoding='utf-8') as f: f.write(str(average_loss) + ',' + str(i) + '\n') f.flush() json_loaded_data['iteration'] = i + 1 with open(path + parameterClass.config_file, 'w', encoding='utf-8') as f: f.write(json.dumps(json_loaded_data)) f.flush() saver.save(sess, path + parameterClass.model_file_name) print('Model saved')
[ "tensorflow.contrib.seq2seq.LuongAttention", "tensorflow.trainable_variables", "numpy.empty", "numpy.ones", "json.dumps", "tensorflow.global_variables", "tensorflow.Variable", "numpy.mean", "tensorflow.contrib.seq2seq.BasicDecoder", "tensorflow.reduce_max", "tensorflow.clip_by_global_norm", "json.loads", "tensorflow.python.layers.core.Dense", "numpy.transpose", "tensorflow.placeholder", "tensorflow.summary.FileWriter", "numpy.reshape", "tensorflow.gradients", "tensorflow.summary.merge_all", "tensorflow.summary.scalar", "tensorflow.nn.embedding_lookup", "tensorflow.global_variables_initializer", "numpy.asarray", "tensorflow.Session", "tensorflow.transpose", "tensorflow.contrib.seq2seq.TrainingHelper", "tensorflow.random_uniform", "tensorflow.nn.dynamic_rnn", "numpy.zeros", "time.time", "tensorflow.contrib.seq2seq.AttentionWrapper", "tensorflow.contrib.seq2seq.dynamic_decode", "tensorflow.contrib.rnn.LSTMCell", "tensorflow.train.AdamOptimizer", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits" ]
[((531, 542), 'time.time', 'time.time', ([], {}), '()\n', (540, 542), False, 'import time\n'), ((3225, 3298), 'tensorflow.placeholder', 'tf.placeholder', ([], {'shape': '(None, None)', 'dtype': 'tf.int32', 'name': '"""encoder_inputs"""'}), "(shape=(None, None), dtype=tf.int32, name='encoder_inputs')\n", (3239, 3298), True, 'import tensorflow as tf\n'), ((3332, 3405), 'tensorflow.placeholder', 'tf.placeholder', ([], {'shape': '(None, None)', 'dtype': 'tf.int32', 'name': '"""decoder_inputs"""'}), "(shape=(None, None), dtype=tf.int32, name='decoder_inputs')\n", (3346, 3405), True, 'import tensorflow as tf\n'), ((3914, 3977), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['embeddings1', 'encoder_inputs_placeholder'], {}), '(embeddings1, encoder_inputs_placeholder)\n', (3936, 3977), True, 'import tensorflow as tf\n'), ((4198, 4293), 'tensorflow.nn.dynamic_rnn', 'tf.nn.dynamic_rnn', (['encoder_cell', 'encoder_inputs_embedded'], {'dtype': 'tf.float32', 'time_major': '(True)'}), '(encoder_cell, encoder_inputs_embedded, dtype=tf.float32,\n time_major=True)\n', (4215, 4293), True, 'import tensorflow as tf\n'), ((4362, 4402), 'tensorflow.transpose', 'tf.transpose', (['encoder_outputs', '[1, 0, 2]'], {}), '(encoder_outputs, [1, 0, 2])\n', (4374, 4402), True, 'import tensorflow as tf\n'), ((4466, 4562), 'tensorflow.contrib.seq2seq.LuongAttention', 'tf.contrib.seq2seq.LuongAttention', (['hidden_num', 'attention_states'], {'memory_sequence_length': 'None'}), '(hidden_num, attention_states,\n memory_sequence_length=None)\n', (4499, 4562), True, 'import tensorflow as tf\n'), ((4771, 4878), 'tensorflow.contrib.seq2seq.AttentionWrapper', 'tf.contrib.seq2seq.AttentionWrapper', (['decoder_cell', 'attention_mechanism'], {'attention_layer_size': 'hidden_num'}), '(decoder_cell, attention_mechanism,\n attention_layer_size=hidden_num)\n', (4806, 4878), True, 'import tensorflow as tf\n'), ((4915, 5000), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': 'parameterClass.batch_size', 'name': '"""decoder_length"""'}), "(tf.int32, shape=parameterClass.batch_size, name='decoder_length'\n )\n", (4929, 5000), True, 'import tensorflow as tf\n'), ((5105, 5201), 'tensorflow.contrib.seq2seq.TrainingHelper', 'tf.contrib.seq2seq.TrainingHelper', (['decoder_inputs_embedded', 'decoder_lengths'], {'time_major': '(True)'}), '(decoder_inputs_embedded, decoder_lengths,\n time_major=True)\n', (5138, 5201), True, 'import tensorflow as tf\n'), ((5222, 5271), 'tensorflow.python.layers.core.Dense', 'layers_core.Dense', (['tgt_vocab_size'], {'use_bias': '(False)'}), '(tgt_vocab_size, use_bias=False)\n', (5239, 5271), True, 'from tensorflow.python.layers import core as layers_core\n'), ((5418, 5521), 'tensorflow.contrib.seq2seq.BasicDecoder', 'tf.contrib.seq2seq.BasicDecoder', (['decoder_cell', 'helper', 'initial_state'], {'output_layer': 'projection_layer'}), '(decoder_cell, helper, initial_state,\n output_layer=projection_layer)\n', (5449, 5521), True, 'import tensorflow as tf\n'), ((5595, 5637), 'tensorflow.contrib.seq2seq.dynamic_decode', 'tf.contrib.seq2seq.dynamic_decode', (['decoder'], {}), '(decoder)\n', (5628, 5637), True, 'import tensorflow as tf\n'), ((5710, 5809), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': '"""int32"""', 'shape': '(parameterClass.batch_size, parameterClass.decoder_length)'}), "(dtype='int32', shape=(parameterClass.batch_size,\n parameterClass.decoder_length))\n", (5724, 5809), True, 'import tensorflow as tf\n'), ((5881, 5983), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'labels': 'decoder_targets_placeholder', 'logits': 'logits'}), '(labels=\n decoder_targets_placeholder, logits=logits)\n', (5927, 5983), True, 'import tensorflow as tf\n'), ((6019, 6070), 'tensorflow.Variable', 'tf.Variable', (['(0)'], {'name': '"""global_step"""', 'trainable': '(False)'}), "(0, name='global_step', trainable=False)\n", (6030, 6070), True, 'import tensorflow as tf\n'), ((6120, 6144), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (6142, 6144), True, 'import tensorflow as tf\n'), ((6161, 6190), 'tensorflow.gradients', 'tf.gradients', (['loss_op', 'params'], {}), '(loss_op, params)\n', (6173, 6190), True, 'import tensorflow as tf\n'), ((6218, 6270), 'tensorflow.clip_by_global_norm', 'tf.clip_by_global_norm', (['gradients', 'max_gradient_norm'], {}), '(gradients, max_gradient_norm)\n', (6240, 6270), True, 'import tensorflow as tf\n'), ((6357, 6383), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['lr'], {}), '(lr)\n', (6379, 6383), True, 'import tensorflow as tf\n'), ((6921, 7034), 'tensorflow.contrib.seq2seq.BasicDecoder', 'tf.contrib.seq2seq.BasicDecoder', (['decoder_cell', 'inference_helper', 'initial_state'], {'output_layer': 'projection_layer'}), '(decoder_cell, inference_helper,\n initial_state, output_layer=projection_layer)\n', (6952, 7034), True, 'import tensorflow as tf\n'), ((7300, 7396), 'tensorflow.contrib.seq2seq.dynamic_decode', 'tf.contrib.seq2seq.dynamic_decode', (['inference_decoder'], {'maximum_iterations': 'maximum_iterations'}), '(inference_decoder, maximum_iterations=\n maximum_iterations)\n', (7333, 7396), True, 'import tensorflow as tf\n'), ((7631, 7651), 'numpy.asarray', 'np.asarray', (['by_index'], {}), '(by_index)\n', (7641, 7651), True, 'import numpy as np\n'), ((7712, 7788), 'numpy.empty', 'np.empty', (['(parameterClass.source_sequence_length, parameterClass.batch_size)'], {}), '((parameterClass.source_sequence_length, parameterClass.batch_size))\n', (7720, 7788), True, 'import numpy as np\n'), ((3437, 3499), 'tensorflow.random_uniform', 'tf.random_uniform', (['[src_vocab_size, embedding_size]', '(-1.0)', '(1.0)'], {}), '([src_vocab_size, embedding_size], -1.0, 1.0)\n', (3454, 3499), True, 'import tensorflow as tf\n'), ((3671, 3734), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['embeddings2', 'decoder_inputs_placeholder'], {}), '(embeddings2, decoder_inputs_placeholder)\n', (3693, 3734), True, 'import tensorflow as tf\n'), ((3785, 3848), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['embeddings1', 'decoder_inputs_placeholder'], {}), '(embeddings1, decoder_inputs_placeholder)\n', (3807, 3848), True, 'import tensorflow as tf\n'), ((8089, 8101), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (8099, 8101), True, 'import tensorflow as tf\n'), ((8447, 8498), 'numpy.reshape', 'np.reshape', (['answer', '[-1, parameterClass.batch_size]'], {}), '(answer, [-1, parameterClass.batch_size])\n', (8457, 8498), True, 'import numpy as np\n'), ((8864, 8876), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (8874, 8876), True, 'import tensorflow as tf\n'), ((10260, 10272), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (10270, 10272), True, 'import tensorflow as tf\n'), ((1256, 1267), 'time.time', 'time.time', ([], {}), '()\n', (1265, 1267), False, 'import time\n'), ((2532, 2548), 'json.dumps', 'json.dumps', (['conf'], {}), '(conf)\n', (2542, 2548), False, 'import json\n'), ((2666, 2689), 'json.loads', 'json.loads', (['json_string'], {}), '(json_string)\n', (2676, 2689), False, 'import json\n'), ((2927, 2943), 'json.loads', 'json.loads', (['stri'], {}), '(stri)\n', (2937, 2943), False, 'import json\n'), ((3573, 3635), 'tensorflow.random_uniform', 'tf.random_uniform', (['[tgt_vocab_size, embedding_size]', '(-1.0)', '(1.0)'], {}), '([tgt_vocab_size, embedding_size], -1.0, 1.0)\n', (3590, 3635), True, 'import tensorflow as tf\n'), ((4027, 4062), 'tensorflow.contrib.rnn.LSTMCell', 'tf.contrib.rnn.LSTMCell', (['hidden_num'], {}), '(hidden_num)\n', (4050, 4062), True, 'import tensorflow as tf\n'), ((4625, 4660), 'tensorflow.contrib.rnn.LSTMCell', 'tf.contrib.rnn.LSTMCell', (['hidden_num'], {}), '(hidden_num)\n', (4648, 4660), True, 'import tensorflow as tf\n'), ((7198, 7250), 'tensorflow.reduce_max', 'tf.reduce_max', (['parameterClass.source_sequence_length'], {}), '(parameterClass.source_sequence_length)\n', (7211, 7250), True, 'import tensorflow as tf\n'), ((7995, 8040), 'numpy.ones', 'np.ones', (['parameterClass.batch_size'], {'dtype': 'int'}), '(parameterClass.batch_size, dtype=int)\n', (8002, 8040), True, 'import numpy as np\n'), ((8128, 8161), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (8159, 8161), True, 'import tensorflow as tf\n'), ((8194, 8215), 'tensorflow.global_variables', 'tf.global_variables', ([], {}), '()\n', (8213, 8215), True, 'import tensorflow as tf\n'), ((8897, 8930), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (8928, 8930), True, 'import tensorflow as tf\n'), ((8963, 8984), 'tensorflow.global_variables', 'tf.global_variables', ([], {}), '()\n', (8982, 8984), True, 'import tensorflow as tf\n'), ((9226, 9319), 'numpy.zeros', 'np.zeros', (['(parameterClass.source_sequence_length, parameterClass.batch_size)'], {'dtype': '"""int"""'}), "((parameterClass.source_sequence_length, parameterClass.batch_size),\n dtype='int')\n", (9234, 9319), True, 'import numpy as np\n'), ((9795, 9845), 'numpy.reshape', 'np.reshape', (['trans', '[-1, parameterClass.batch_size]'], {}), '(trans, [-1, parameterClass.batch_size])\n', (9805, 9845), True, 'import numpy as np\n'), ((10299, 10332), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (10330, 10332), True, 'import tensorflow as tf\n'), ((10365, 10386), 'tensorflow.global_variables', 'tf.global_variables', ([], {}), '()\n', (10384, 10386), True, 'import tensorflow as tf\n'), ((10870, 10901), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['logs_dir'], {}), '(logs_dir)\n', (10891, 10901), True, 'import tensorflow as tf\n'), ((11071, 11082), 'time.time', 'time.time', ([], {}), '()\n', (11080, 11082), False, 'import time\n'), ((11156, 11249), 'numpy.zeros', 'np.zeros', (['(parameterClass.source_sequence_length, parameterClass.batch_size)'], {'dtype': '"""int"""'}), "((parameterClass.source_sequence_length, parameterClass.batch_size),\n dtype='int')\n", (11164, 11249), True, 'import numpy as np\n'), ((11272, 11358), 'numpy.zeros', 'np.zeros', (['(parameterClass.decoder_length, parameterClass.batch_size)'], {'dtype': '"""int"""'}), "((parameterClass.decoder_length, parameterClass.batch_size), dtype=\n 'int')\n", (11280, 11358), True, 'import numpy as np\n'), ((11380, 11466), 'numpy.zeros', 'np.zeros', (['(parameterClass.decoder_length, parameterClass.batch_size)'], {'dtype': '"""int"""'}), "((parameterClass.decoder_length, parameterClass.batch_size), dtype=\n 'int')\n", (11388, 11466), True, 'import numpy as np\n'), ((12451, 12464), 'numpy.mean', 'np.mean', (['loss'], {}), '(loss)\n', (12458, 12464), True, 'import numpy as np\n'), ((12841, 12877), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""loss"""', 'iter_loss'], {}), "('loss', iter_loss)\n", (12858, 12877), True, 'import tensorflow as tf\n'), ((12918, 12962), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""iter_loss"""'}), "(tf.float32, name='iter_loss')\n", (12932, 12962), True, 'import tensorflow as tf\n'), ((12979, 13027), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""loss"""', 'iter_loss_placeholder'], {}), "('loss', iter_loss_placeholder)\n", (12996, 13027), True, 'import tensorflow as tf\n'), ((13061, 13083), 'tensorflow.summary.merge_all', 'tf.summary.merge_all', ([], {}), '()\n', (13081, 13083), True, 'import tensorflow as tf\n'), ((9574, 9604), 'numpy.ones', 'np.ones', (['batch_size'], {'dtype': 'int'}), '(batch_size, dtype=int)\n', (9581, 9604), True, 'import numpy as np\n'), ((12146, 12167), 'numpy.transpose', 'np.transpose', (['dec_tgt'], {}), '(dec_tgt)\n', (12158, 12167), True, 'import numpy as np\n'), ((12731, 12742), 'time.time', 'time.time', ([], {}), '()\n', (12740, 12742), False, 'import time\n'), ((13677, 13705), 'json.dumps', 'json.dumps', (['json_loaded_data'], {}), '(json_loaded_data)\n', (13687, 13705), False, 'import json\n'), ((12206, 12251), 'numpy.ones', 'np.ones', (['parameterClass.batch_size'], {'dtype': 'int'}), '(parameterClass.batch_size, dtype=int)\n', (12213, 12251), True, 'import numpy as np\n'), ((12556, 12569), 'numpy.mean', 'np.mean', (['loss'], {}), '(loss)\n', (12563, 12569), True, 'import numpy as np\n')]
# Some part borrowed from official tutorial https://github.com/pytorch/examples/blob/master/imagenet/main.py from __future__ import print_function from __future__ import absolute_import import os import numpy as np import argparse import importlib import time import logging import warnings from collections import OrderedDict import torch import torch.nn as nn from torch.utils.data.dataset import Dataset from torchvision import datasets, transforms from torch.utils.tensorboard import SummaryWriter from models import SupResNet, SSLResNet import data import trainers from losses import SupConLoss from utils import * def main(): parser = argparse.ArgumentParser(description="SSD evaluation") parser.add_argument( "--results-dir", type=str, default="/data/data_vvikash/fall20/SSD/trained_models/", ) # change this parser.add_argument("--exp-name", type=str, default="temp") parser.add_argument( "--training-mode", type=str, choices=("SimCLR", "SupCon", "SupCE") ) # model parser.add_argument("--arch", type=str, default="resnet50") parser.add_argument("--num-classes", type=int, default=10) # training parser.add_argument("--dataset", type=str, default="cifar10") parser.add_argument("--data-dir", type=str, default="/data/data_vvikash/datasets/") parser.add_argument("--normalize", action="store_true", default=False) parser.add_argument("--batch-size", type=int, default=512) parser.add_argument("--size", type=int, default=32) parser.add_argument("--epochs", type=int, default=500) parser.add_argument("--lr", type=float, default=0.5) parser.add_argument("--momentum", type=float, default=0.9) parser.add_argument("--weight-decay", type=float, default=1e-4) parser.add_argument("--warmup", action="store_true") # ssl parser.add_argument( "--method", type=str, default="SupCon", choices=["SupCon", "SimCLR", "SupCE"] ) parser.add_argument("--temperature", type=float, default=0.5) # misc parser.add_argument("--print-freq", type=int, default=100) parser.add_argument("--save-freq", type=int, default=50) parser.add_argument("--ckpt", type=str, help="checkpoint path") parser.add_argument("--seed", type=int, default=12345) args = parser.parse_args() device = "cuda:0" if args.batch_size > 256 and not args.warmup: warnings.warn("Use warmup training for larger batch-sizes > 256") if not os.path.isdir(args.results_dir): os.mkdir(args.results_dir) # create resutls dir (for logs, checkpoints, etc.) result_main_dir = os.path.join(args.results_dir, args.exp_name) if os.path.exists(result_main_dir): n = len(next(os.walk(result_main_dir))[-2]) # prev experiments with same name result_sub_dir = result_sub_dir = os.path.join( result_main_dir, "{}--dataset-{}-arch-{}-lr-{}_epochs-{}".format( n + 1, args.dataset, args.arch, args.lr, args.epochs ), ) else: os.mkdir(result_main_dir) result_sub_dir = result_sub_dir = os.path.join( result_main_dir, "1--dataset-{}-arch-{}-lr-{}_epochs-{}".format( args.dataset, args.arch, args.lr, args.epochs ), ) create_subdirs(result_sub_dir) # add logger logging.basicConfig(level=logging.INFO, format="%(message)s") logger = logging.getLogger() logger.addHandler( logging.FileHandler(os.path.join(result_sub_dir, "setup.log"), "a") ) logger.info(args) # seed cuda torch.manual_seed(args.seed) torch.cuda.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) np.random.seed(args.seed) # Create model if args.training_mode in ["SimCLR", "SupCon"]: model = SSLResNet(arch=args.arch).to(device) elif args.training_mode == "SupCE": model = SupResNet(arch=args.arch, num_classes=args.num_classes).to(device) else: raise ValueError("training mode not supported") # load feature extractor on gpu model.encoder = torch.nn.DataParallel(model.encoder).to(device) # Dataloader train_loader, test_loader, _ = data.__dict__[args.dataset]( args.data_dir, mode="ssl" if args.training_mode in ["SimCLR", "SupCon"] else "org", normalize=args.normalize, size=args.size, batch_size=args.batch_size, ) criterion = ( SupConLoss(temperature=args.temperature).cuda() if args.training_mode in ["SimCLR", "SupCon"] else nn.CrossEntropyLoss().cuda() ) optimizer = torch.optim.SGD( model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay, ) # select training and validation methods trainer = ( trainers.ssl if args.training_mode in ["SimCLR", "SupCon"] else trainers.supervised ) val = knn if args.training_mode in ["SimCLR", "SupCon"] else baseeval # warmup if args.warmup: wamrup_epochs = 10 print(f"Warmup training for {wamrup_epochs} epochs") warmup_lr_scheduler = torch.optim.lr_scheduler.CyclicLR( optimizer, base_lr=0.01, max_lr=args.lr, step_size_up=wamrup_epochs * len(train_loader), ) for epoch in range(wamrup_epochs): trainer( model, device, train_loader, criterion, optimizer, warmup_lr_scheduler, epoch, args, ) best_prec1 = 0 for p in optimizer.param_groups: p["lr"] = args.lr p["initial_lr"] = args.lr lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( optimizer, args.epochs * len(train_loader), 1e-4 ) for epoch in range(0, args.epochs): trainer( model, device, train_loader, criterion, optimizer, lr_scheduler, epoch, args ) prec1, _ = val(model, device, test_loader, criterion, args, epoch) # remember best accuracy and save checkpoint is_best = prec1 > best_prec1 best_prec1 = max(prec1, best_prec1) d = { "epoch": epoch + 1, "arch": args.arch, "state_dict": model.state_dict(), "best_prec1": best_prec1, "optimizer": optimizer.state_dict(), } save_checkpoint( d, is_best, os.path.join(result_sub_dir, "checkpoint"), ) if not (epoch + 1) % args.save_freq: save_checkpoint( d, is_best, os.path.join(result_sub_dir, "checkpoint"), filename=f"checkpoint_{epoch+1}.pth.tar", ) logger.info( f"Epoch {epoch}, validation accuracy {prec1}, best_prec {best_prec1}" ) # clone results to latest subdir (sync after every epoch) clone_results_to_latest_subdir( result_sub_dir, os.path.join(result_main_dir, "latest_exp") ) if __name__ == "__main__": main()
[ "os.mkdir", "numpy.random.seed", "argparse.ArgumentParser", "logging.basicConfig", "os.path.isdir", "torch.manual_seed", "losses.SupConLoss", "os.walk", "os.path.exists", "torch.cuda.manual_seed", "torch.nn.CrossEntropyLoss", "models.SupResNet", "torch.cuda.manual_seed_all", "models.SSLResNet", "warnings.warn", "torch.nn.DataParallel", "os.path.join", "logging.getLogger" ]
[((650, 703), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""SSD evaluation"""'}), "(description='SSD evaluation')\n", (673, 703), False, 'import argparse\n'), ((2631, 2676), 'os.path.join', 'os.path.join', (['args.results_dir', 'args.exp_name'], {}), '(args.results_dir, args.exp_name)\n', (2643, 2676), False, 'import os\n'), ((2685, 2716), 'os.path.exists', 'os.path.exists', (['result_main_dir'], {}), '(result_main_dir)\n', (2699, 2716), False, 'import os\n'), ((3378, 3439), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': '"""%(message)s"""'}), "(level=logging.INFO, format='%(message)s')\n", (3397, 3439), False, 'import logging\n'), ((3453, 3472), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (3470, 3472), False, 'import logging\n'), ((3621, 3649), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (3638, 3649), False, 'import torch\n'), ((3654, 3687), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['args.seed'], {}), '(args.seed)\n', (3676, 3687), False, 'import torch\n'), ((3692, 3729), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['args.seed'], {}), '(args.seed)\n', (3718, 3729), False, 'import torch\n'), ((3734, 3759), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (3748, 3759), True, 'import numpy as np\n'), ((2407, 2472), 'warnings.warn', 'warnings.warn', (['"""Use warmup training for larger batch-sizes > 256"""'], {}), "('Use warmup training for larger batch-sizes > 256')\n", (2420, 2472), False, 'import warnings\n'), ((2485, 2516), 'os.path.isdir', 'os.path.isdir', (['args.results_dir'], {}), '(args.results_dir)\n', (2498, 2516), False, 'import os\n'), ((2526, 2552), 'os.mkdir', 'os.mkdir', (['args.results_dir'], {}), '(args.results_dir)\n', (2534, 2552), False, 'import os\n'), ((3063, 3088), 'os.mkdir', 'os.mkdir', (['result_main_dir'], {}), '(result_main_dir)\n', (3071, 3088), False, 'import os\n'), ((3524, 3565), 'os.path.join', 'os.path.join', (['result_sub_dir', '"""setup.log"""'], {}), "(result_sub_dir, 'setup.log')\n", (3536, 3565), False, 'import os\n'), ((4130, 4166), 'torch.nn.DataParallel', 'torch.nn.DataParallel', (['model.encoder'], {}), '(model.encoder)\n', (4151, 4166), False, 'import torch\n'), ((6578, 6620), 'os.path.join', 'os.path.join', (['result_sub_dir', '"""checkpoint"""'], {}), "(result_sub_dir, 'checkpoint')\n", (6590, 6620), False, 'import os\n'), ((7132, 7175), 'os.path.join', 'os.path.join', (['result_main_dir', '"""latest_exp"""'], {}), "(result_main_dir, 'latest_exp')\n", (7144, 7175), False, 'import os\n'), ((3847, 3872), 'models.SSLResNet', 'SSLResNet', ([], {'arch': 'args.arch'}), '(arch=args.arch)\n', (3856, 3872), False, 'from models import SupResNet, SSLResNet\n'), ((4487, 4527), 'losses.SupConLoss', 'SupConLoss', ([], {'temperature': 'args.temperature'}), '(temperature=args.temperature)\n', (4497, 4527), False, 'from losses import SupConLoss\n'), ((4602, 4623), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (4621, 4623), True, 'import torch.nn as nn\n'), ((6767, 6809), 'os.path.join', 'os.path.join', (['result_sub_dir', '"""checkpoint"""'], {}), "(result_sub_dir, 'checkpoint')\n", (6779, 6809), False, 'import os\n'), ((2739, 2763), 'os.walk', 'os.walk', (['result_main_dir'], {}), '(result_main_dir)\n', (2746, 2763), False, 'import os\n'), ((3940, 3995), 'models.SupResNet', 'SupResNet', ([], {'arch': 'args.arch', 'num_classes': 'args.num_classes'}), '(arch=args.arch, num_classes=args.num_classes)\n', (3949, 3995), False, 'from models import SupResNet, SSLResNet\n')]
""" pytorch (0.3.1) miss some transforms, will be removed after official support. """ import torch import numpy as np from PIL import Image import torchvision.transforms.functional as F import torch.nn.functional as Func import random imagenet_pca = { 'eigval': np.asarray([0.2175, 0.0188, 0.0045]), 'eigvec': np.asarray([ [-0.5675, 0.7192, 0.4009], [-0.5808, -0.0045, -0.8140], [-0.5836, -0.6948, 0.4203], ]) } class Lighting(object): def __init__(self, alphastd, eigval=imagenet_pca['eigval'], eigvec=imagenet_pca['eigvec']): self.alphastd = alphastd assert eigval.shape == (3,) assert eigvec.shape == (3, 3) self.eigval = eigval self.eigvec = eigvec def __call__(self, img): if self.alphastd == 0.: return img rnd = np.random.randn(3) * self.alphastd rnd = rnd.astype('float32') v = rnd old_dtype = np.asarray(img).dtype v = v * self.eigval v = v.reshape((3, 1)) inc = np.dot(self.eigvec, v).reshape((3,)) img = np.add(img, inc) if old_dtype == np.uint8: img = np.clip(img, 0, 255) img = Image.fromarray(img.astype(old_dtype), 'RGB') return img def __repr__(self): return self.__class__.__name__ + '()' class InputList(object): def __init__(self, scales): self.scales = scales def __call__(self, img): # assert img.size[0] == self.scales[0], 'image shape should be equal to max scale' # input_list = [] # for i in range(len(self.scales)): # input_list.append(F.resize(img, self.scales[i])) assert img.size()[1] == self.scales[0], 'image shape should be equal to max scale' input_list = [] img = img[np.newaxis, :] for i in range(len(self.scales)): resized_img = Func.interpolate(img, (self.scales[i], self.scales[i]), mode='bilinear', align_corners=True) resized_img = torch.squeeze(resized_img) input_list.append(resized_img) return input_list class ListToTensor(object): def __call__(self, input_list): tensor_list = [] for i in range(len(input_list)): pic = input_list[i] tensor_list.append(F.to_tensor(pic).detach()) return tensor_list class ListNormalize(object): def __init__(self, mean, std, inplace=False): self.mean = mean self.std = std self.inplace = inplace def __call__(self, tensor_list): norm_list = [] for i in range(len(tensor_list)): norm_list.append(F.normalize(tensor_list[i], self.mean, self.std, self.inplace)) return norm_list
[ "torchvision.transforms.functional.to_tensor", "numpy.random.randn", "numpy.asarray", "numpy.clip", "torch.squeeze", "numpy.dot", "numpy.add", "torch.nn.functional.interpolate", "torchvision.transforms.functional.normalize" ]
[((268, 304), 'numpy.asarray', 'np.asarray', (['[0.2175, 0.0188, 0.0045]'], {}), '([0.2175, 0.0188, 0.0045])\n', (278, 304), True, 'import numpy as np\n'), ((320, 419), 'numpy.asarray', 'np.asarray', (['[[-0.5675, 0.7192, 0.4009], [-0.5808, -0.0045, -0.814], [-0.5836, -0.6948, \n 0.4203]]'], {}), '([[-0.5675, 0.7192, 0.4009], [-0.5808, -0.0045, -0.814], [-0.5836,\n -0.6948, 0.4203]])\n', (330, 419), True, 'import numpy as np\n'), ((1122, 1138), 'numpy.add', 'np.add', (['img', 'inc'], {}), '(img, inc)\n', (1128, 1138), True, 'import numpy as np\n'), ((870, 888), 'numpy.random.randn', 'np.random.randn', (['(3)'], {}), '(3)\n', (885, 888), True, 'import numpy as np\n'), ((977, 992), 'numpy.asarray', 'np.asarray', (['img'], {}), '(img)\n', (987, 992), True, 'import numpy as np\n'), ((1191, 1211), 'numpy.clip', 'np.clip', (['img', '(0)', '(255)'], {}), '(img, 0, 255)\n', (1198, 1211), True, 'import numpy as np\n'), ((1920, 2016), 'torch.nn.functional.interpolate', 'Func.interpolate', (['img', '(self.scales[i], self.scales[i])'], {'mode': '"""bilinear"""', 'align_corners': '(True)'}), "(img, (self.scales[i], self.scales[i]), mode='bilinear',\n align_corners=True)\n", (1936, 2016), True, 'import torch.nn.functional as Func\n'), ((2039, 2065), 'torch.squeeze', 'torch.squeeze', (['resized_img'], {}), '(resized_img)\n', (2052, 2065), False, 'import torch\n'), ((1071, 1093), 'numpy.dot', 'np.dot', (['self.eigvec', 'v'], {}), '(self.eigvec, v)\n', (1077, 1093), True, 'import numpy as np\n'), ((2676, 2738), 'torchvision.transforms.functional.normalize', 'F.normalize', (['tensor_list[i]', 'self.mean', 'self.std', 'self.inplace'], {}), '(tensor_list[i], self.mean, self.std, self.inplace)\n', (2687, 2738), True, 'import torchvision.transforms.functional as F\n'), ((2330, 2346), 'torchvision.transforms.functional.to_tensor', 'F.to_tensor', (['pic'], {}), '(pic)\n', (2341, 2346), True, 'import torchvision.transforms.functional as F\n')]
# -*- coding: utf-8 -*- """ Colored text tool for RNN visualization """ import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np class ColoredText(object): """ text: a sequence of characters vals: a float vector, (-1 , 1), The same length as text width: image width fontsize: fontname: nonproportional fontname disp_colorbar: TODO:Fix margins.The margins are correct only for width=1080 and fontsize=14. """ def __init__(self, text, vals, width, fontsize, fontname='Source Code Pro', disp_colorbar=True): assert len(text) == len(vals) self.text = text self.vals = (vals + 1) / 2 # (-1,1) to (0, 1) self.figsize_x = width / 90 self.fontsize = fontsize self.fontname = fontname self.disp_colorbar = disp_colorbar # self.font_w = fontsize self.font_h = 1.9 * self.font_w self.text_w = 0.95 * width self.cnt_oneline = int(self.text_w / self.font_w) - 1 self.text_h = np.ceil(len(text) / self.cnt_oneline) * self.font_h if self.disp_colorbar: self.text_h += .7 * self.font_h self.height = self.text_h + 50 self.text_bottom = 20 / self.height else: self.height = self.text_h + 30 self.text_bottom = 0 self.text_rh = self.text_h / self.height self.figsize_y = self.height / 90 self.suptitle_y = 1 - 10 / self.height self.font_rw = self.font_w / self.text_w self.font_rh = self.font_h / self.text_h self.text_val = self.split(self.cnt_oneline) def split(self, cnt): text_val = [(self.text[i:i+cnt], self.vals[i:i+cnt]) for i in range(0, len(self.text), cnt)] return text_val def disp_one_line(self, ax, subtext, subvals, height): cl_s = cm.bwr(subvals) for i, (ch, cl) in enumerate(zip(subtext, cl_s)): ax.text(0.01 + i * self.font_rw, height, ch, fontname=self.fontname, fontsize=self.fontsize, bbox={'facecolor': cl, 'edgecolor': cl, 'alpha': 0.8, 'pad': 1}) return ax def display(self, title=None, savefile=None): fig = plt.figure(figsize=(self.figsize_x, self.figsize_y), dpi=90) if title is not None: fig.suptitle(title, y=self.suptitle_y, fontsize=self.fontsize + 2) # colored text ax = fig.add_axes([0.02, self.text_bottom, 0.97, self.text_rh]) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) for j, (subtext, subvals) in enumerate(self.text_val): self.disp_one_line(ax, subtext, subvals, 1 - (j+0.6)*self.font_rh) if self.disp_colorbar: cax = fig.add_axes([0.02, self.text_bottom, 0.97, self.text_bottom]) gradient = np.linspace(0, 1, 101) gradient = np.vstack((gradient, gradient)) cax.imshow(gradient, aspect='auto', cmap=plt.get_cmap('bwr')) cax.set_xticks([0, 25, 50, 75, 100]) cax.set_xticklabels(map(str, (cax.get_xticks() - 50) / 50)) cax.get_yaxis().set_visible(False) if savefile is None: plt.show() else: plt.savefig(savefile) plt.close() if __name__ == '__main__': from itertools import product SAVE = True savefile = None paramsgrid = product([10, 113, 375, 819], # num of chars [540, 1080], # image width [10, 14, 18], # fontsize [True, False]) # disp_colorbar for n, width, fontsize, disp_colorbar in paramsgrid: text = ''.join([str(i % 10) for i in range(n)]) vals = (np.random.randn(n) / 5).clip(-1, 1) title = 'n:{:d} width:{:d} fontsize:{:d} cbar:{:d}'.format( n, width, fontsize, disp_colorbar) if SAVE: savefile = 'img/' + title.replace(':', '').replace(' ', '_') ct = ColoredText(text, vals, width, fontsize, disp_colorbar=disp_colorbar) ct.display(title=title, savefile=savefile)
[ "matplotlib.pyplot.savefig", "matplotlib.pyplot.show", "matplotlib.pyplot.get_cmap", "numpy.random.randn", "matplotlib.pyplot.close", "matplotlib.cm.bwr", "matplotlib.pyplot.figure", "numpy.linspace", "itertools.product", "numpy.vstack" ]
[((3643, 3713), 'itertools.product', 'product', (['[10, 113, 375, 819]', '[540, 1080]', '[10, 14, 18]', '[True, False]'], {}), '([10, 113, 375, 819], [540, 1080], [10, 14, 18], [True, False])\n', (3650, 3713), False, 'from itertools import product\n'), ((1974, 1989), 'matplotlib.cm.bwr', 'cm.bwr', (['subvals'], {}), '(subvals)\n', (1980, 1989), True, 'import matplotlib.cm as cm\n'), ((2397, 2457), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(self.figsize_x, self.figsize_y)', 'dpi': '(90)'}), '(figsize=(self.figsize_x, self.figsize_y), dpi=90)\n', (2407, 2457), True, 'import matplotlib.pyplot as plt\n'), ((3508, 3519), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (3517, 3519), True, 'import matplotlib.pyplot as plt\n'), ((3068, 3090), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(101)'], {}), '(0, 1, 101)\n', (3079, 3090), True, 'import numpy as np\n'), ((3115, 3146), 'numpy.vstack', 'np.vstack', (['(gradient, gradient)'], {}), '((gradient, gradient))\n', (3124, 3146), True, 'import numpy as np\n'), ((3438, 3448), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3446, 3448), True, 'import matplotlib.pyplot as plt\n'), ((3477, 3498), 'matplotlib.pyplot.savefig', 'plt.savefig', (['savefile'], {}), '(savefile)\n', (3488, 3498), True, 'import matplotlib.pyplot as plt\n'), ((3201, 3220), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""bwr"""'], {}), "('bwr')\n", (3213, 3220), True, 'import matplotlib.pyplot as plt\n'), ((4007, 4025), 'numpy.random.randn', 'np.random.randn', (['n'], {}), '(n)\n', (4022, 4025), True, 'import numpy as np\n')]
import sys import os from typing import Tuple from numpy.random.mtrand import random sys.path.append('C:\\Users\\coton\\Desktop\\github\\fema\\src\\') import numpy as np import math from fem_basis import Basis class FEMaSemiSupervisedClassifier: """ Class responsible to perform the classification using FEMa approach """ def __init__(self): self.train_x = None self.train_y = None self.uknw_x = None self.num_train_samples = 0 self.num_uknw_samples = 0 self.num_features = 0 self.num_classes = 0 self.k = 1 self.basis = None self.probability_class = None def __init__(self, k:int=2, basis=Basis.shepardBasis) -> None: """Constructor that receives the parameter to run the FEMa Args: k (int): Define the number of neighboor used to interpolate basis = The finite element basis """ self.train_x = None self.train_y = None self.uknw_x = None self.num_train_samples = 0 self.num_uknw_samples = 0 self.num_features = 0 self.num_classes = 0 self.k = k self.basis = basis self.probability_classes = None def fit(self, train_x:np.array, train_y:np.array, uknw_x:np.array, uknw_y:np.array=None, *args) -> None: """AI is creating summary for fit Args: train_x (np.array): [description] train_y (np.array): [description] uknw_x (np.array): [description] uknw_y (np.array, optional): [description]. Defaults to None. """ self.train_x = train_x self.train_y = train_y self.uknw_x = uknw_x self.uknw_y = uknw_y self.num_train_samples = len(train_y) self.num_uknw_samples = uknw_x.shape[0] self.num_features = self.train_x.shape[1] self.num_classes = len(set(train_y[:,0])) self.probability_classes = np.zeros((self.num_classes,self.num_train_samples)) for i in range(self.num_classes): self.probability_classes[i,:] = train_y[:,0] == i self.uknw_yhat = np.zeros(self.num_uknw_samples) self.uknw_confidence_level = np.zeros((self.num_uknw_samples, self.num_classes)) for i in range(self.num_uknw_samples): self.uknw_confidence_level[i,:] = [self.basis(train_x=self.train_x, train_y=self.probability_classes[c], test_one_sample=self.uknw_x[i], k=self.k, z=args[0]) for c in range(self.num_classes)] #self.uknw_yhat[i] = np.argmax(self.uknw_confidence_level[i,:]) def predict(self, test_x:np.array, *args) -> Tuple[np.array, np.array]: """AI is creating summary for predict Args: test_x (np.array): [description] Returns: Tuple[np.array, np.array]: [description] """ new_train_x = np.append(self.train_x, self.uknw_x,axis=0) new_probability_classes = np.append(self.probability_classes,self.uknw_confidence_level,axis=0) num_test_samples = len(test_x) labels = np.zeros(num_test_samples) confidence_level = np.zeros((num_test_samples, self.num_classes)) for i in range(num_test_samples): confidence_level[i,:] = [self.basis(train_x=new_train_x, train_y=new_probability_classes[c], test_one_sample=test_x[i], k=self.k, z=args[0]) for c in range(self.num_classes)] labels[i] = np.argmax(confidence_level[i,:]) return labels, confidence_level
[ "sys.path.append", "numpy.append", "numpy.zeros", "numpy.argmax" ]
[((88, 153), 'sys.path.append', 'sys.path.append', (['"""C:\\\\Users\\\\coton\\\\Desktop\\\\github\\\\fema\\\\src\\\\"""'], {}), "('C:\\\\Users\\\\coton\\\\Desktop\\\\github\\\\fema\\\\src\\\\')\n", (103, 153), False, 'import sys\n'), ((1993, 2045), 'numpy.zeros', 'np.zeros', (['(self.num_classes, self.num_train_samples)'], {}), '((self.num_classes, self.num_train_samples))\n', (2001, 2045), True, 'import numpy as np\n'), ((2176, 2207), 'numpy.zeros', 'np.zeros', (['self.num_uknw_samples'], {}), '(self.num_uknw_samples)\n', (2184, 2207), True, 'import numpy as np\n'), ((2245, 2296), 'numpy.zeros', 'np.zeros', (['(self.num_uknw_samples, self.num_classes)'], {}), '((self.num_uknw_samples, self.num_classes))\n', (2253, 2296), True, 'import numpy as np\n'), ((2935, 2979), 'numpy.append', 'np.append', (['self.train_x', 'self.uknw_x'], {'axis': '(0)'}), '(self.train_x, self.uknw_x, axis=0)\n', (2944, 2979), True, 'import numpy as np\n'), ((3021, 3092), 'numpy.append', 'np.append', (['self.probability_classes', 'self.uknw_confidence_level'], {'axis': '(0)'}), '(self.probability_classes, self.uknw_confidence_level, axis=0)\n', (3030, 3092), True, 'import numpy as np\n'), ((3147, 3173), 'numpy.zeros', 'np.zeros', (['num_test_samples'], {}), '(num_test_samples)\n', (3155, 3173), True, 'import numpy as np\n'), ((3201, 3247), 'numpy.zeros', 'np.zeros', (['(num_test_samples, self.num_classes)'], {}), '((num_test_samples, self.num_classes))\n', (3209, 3247), True, 'import numpy as np\n'), ((3502, 3535), 'numpy.argmax', 'np.argmax', (['confidence_level[i, :]'], {}), '(confidence_level[i, :])\n', (3511, 3535), True, 'import numpy as np\n')]
import numpy as np import math # TODO: Use anytree to represent the tree class TreeNode: def __init__(self, lb, ub, num_split, rand = False): self.lb = lb self.ub = ub self.x = 0.5 * (lb + ub) if not rand else np.random.uniform(lb, ub) self.y = np.nan self.children = [] self.num_split = num_split if not np.all(self.lb < self.ub): print("Error in the bound of node"); sys.exit(1) pass def is_leaf(self): return (not self.children) def expand(self, rand = False): if not self.is_leaf(): print("Can not expand node, the node is not a leaf") sys.exit(1) id = np.argmax(self.ub - self.lb) len = (self.ub[id] - self.lb[id]) / self.num_split for i in range(self.num_split): lb = self.lb.copy() ub = self.ub.copy() lb[id] = self.lb[id] + len * i; ub[id] = self.lb[id] + len * (i+1); self.children.append(TreeNode(lb, ub, self.num_split, rand)) def children_leaves(self): return list(filter(lambda c : c.is_leaf(), self.children)) def depth(self): if self.is_leaf(): return 1; else: max_sub_depth = 0; for c in self.children: max_sub_depth = max(max_sub_depth, c.depth()) return 1 + max_sub_depth
[ "numpy.random.uniform", "numpy.all", "numpy.argmax" ]
[((726, 754), 'numpy.argmax', 'np.argmax', (['(self.ub - self.lb)'], {}), '(self.ub - self.lb)\n', (735, 754), True, 'import numpy as np\n'), ((247, 272), 'numpy.random.uniform', 'np.random.uniform', (['lb', 'ub'], {}), '(lb, ub)\n', (264, 272), True, 'import numpy as np\n'), ((383, 408), 'numpy.all', 'np.all', (['(self.lb < self.ub)'], {}), '(self.lb < self.ub)\n', (389, 408), True, 'import numpy as np\n')]
#!/usr/bin/env python """ verlat numerical integration methods """ import numpy as np def velocity_verlat(x_init, acc, step, time): """ the velocity verlat method """ # finding count count = int(time / step) # initialization x = np.zeros(count) x_dot = np.zeros(count) x[0] = x_init x_dot[0] = 0 for i in range(count - 1): x[i + 1] = x[i] + x_dot[i] * step + 0.5 * step ** 2 * acc(x[i]) x_dot[i + 1] = x_dot[i] + 0.5 * (acc(x[i + 1]) + acc(x[i])) * step return x, x_dot, count def verlat(x_init, acc, step, time): """ the original verlat method """ # calc ing count count = int(time / step) # initialization x = np.zeros(count + 2) x_dot = np.zeros(count + 1) x[0:2] = x_init, x_init for i in range(1, count + 1): x[i + 1] = 2 * x[i] - x[i - 1] + acc(x[i]) * step ** 2 x_dot[i] = (x[i + 1] - x[i - 1]) / (2 * step) # tidy up x = np.delete(x, [0, -1]) x_dot = np.delete(x_dot, 0) return x, x_dot, count def euler(x_init, acc, step, time): """ euer method """ # finding count count = int(time / step) # initialization x = np.zeros(count) x_dot = np.zeros(count) x[0] = x_init for i in range(count - 1): x[i + 1] = x[i] + x_dot[i] * step x_dot[i + 1] = x_dot[i] + acc(x[i]) * step return x, x_dot, count def euler_cromer(x_init, acc, step, time): """ euer method """ # finding count count = int(time / step) # initialization x = np.zeros(count) x_dot = np.zeros(count) x[0] = x_init for i in range(count - 1): x_dot[i + 1] = x_dot[i] + acc(x[i]) * step x[i + 1] = x[i] + x_dot[i + 1] * step return x, x_dot, count def beeman(x_init, acc, step, time): """ beeman method """ # find count count = int(time / step) # initialize x = np.zeros(count + 1) x_dot = np.zeros(count + 1) x[0:2] = x_init x_dot[0] = 0 for i in range(1, count): x[i + 1] = x[i] + x_dot[i] * step + 1.0 / 6 \ * (4 * acc(x[i]) - acc(x[i - 1])) * step ** 2 x_dot[i + 1] = x_dot[i] + 1 / 6.0 \ * ( 2 * acc(x[i + 1]) + 5 * acc(x[i]) - acc(x[i - 1])) * step # clean x and x_dot x = np.delete(x, 0) x_dot = np.delete(x_dot, 0) return x, x_dot, count
[ "numpy.zeros", "numpy.delete" ]
[((254, 269), 'numpy.zeros', 'np.zeros', (['count'], {}), '(count)\n', (262, 269), True, 'import numpy as np\n'), ((282, 297), 'numpy.zeros', 'np.zeros', (['count'], {}), '(count)\n', (290, 297), True, 'import numpy as np\n'), ((698, 717), 'numpy.zeros', 'np.zeros', (['(count + 2)'], {}), '(count + 2)\n', (706, 717), True, 'import numpy as np\n'), ((730, 749), 'numpy.zeros', 'np.zeros', (['(count + 1)'], {}), '(count + 1)\n', (738, 749), True, 'import numpy as np\n'), ((953, 974), 'numpy.delete', 'np.delete', (['x', '[0, -1]'], {}), '(x, [0, -1])\n', (962, 974), True, 'import numpy as np\n'), ((987, 1006), 'numpy.delete', 'np.delete', (['x_dot', '(0)'], {}), '(x_dot, 0)\n', (996, 1006), True, 'import numpy as np\n'), ((1176, 1191), 'numpy.zeros', 'np.zeros', (['count'], {}), '(count)\n', (1184, 1191), True, 'import numpy as np\n'), ((1204, 1219), 'numpy.zeros', 'np.zeros', (['count'], {}), '(count)\n', (1212, 1219), True, 'import numpy as np\n'), ((1539, 1554), 'numpy.zeros', 'np.zeros', (['count'], {}), '(count)\n', (1547, 1554), True, 'import numpy as np\n'), ((1567, 1582), 'numpy.zeros', 'np.zeros', (['count'], {}), '(count)\n', (1575, 1582), True, 'import numpy as np\n'), ((1894, 1913), 'numpy.zeros', 'np.zeros', (['(count + 1)'], {}), '(count + 1)\n', (1902, 1913), True, 'import numpy as np\n'), ((1926, 1945), 'numpy.zeros', 'np.zeros', (['(count + 1)'], {}), '(count + 1)\n', (1934, 1945), True, 'import numpy as np\n'), ((2282, 2297), 'numpy.delete', 'np.delete', (['x', '(0)'], {}), '(x, 0)\n', (2291, 2297), True, 'import numpy as np\n'), ((2310, 2329), 'numpy.delete', 'np.delete', (['x_dot', '(0)'], {}), '(x_dot, 0)\n', (2319, 2329), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import cv2 import numpy as np camera = cv2.VideoCapture(0) gray = None while True: ret, frame = camera.read() if ret is False: print("Camera open failed") break newgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) display_img = newgray if gray is not None: #display_img =cv2.absdiff(newgray, gray) """ diff two picture, movement will be detected """ display_img =np.where(newgray > gray, newgray - gray, gray - newgray) gray = newgray cv2.imshow('hello', display_img) if cv2.waitKey(1) == ord('q'): break camera.release()
[ "cv2.cvtColor", "cv2.waitKey", "cv2.VideoCapture", "numpy.where", "cv2.imshow" ]
[((87, 106), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (103, 106), False, 'import cv2\n'), ((247, 286), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2GRAY'], {}), '(frame, cv2.COLOR_BGR2GRAY)\n', (259, 286), False, 'import cv2\n'), ((565, 597), 'cv2.imshow', 'cv2.imshow', (['"""hello"""', 'display_img'], {}), "('hello', display_img)\n", (575, 597), False, 'import cv2\n'), ((484, 540), 'numpy.where', 'np.where', (['(newgray > gray)', '(newgray - gray)', '(gray - newgray)'], {}), '(newgray > gray, newgray - gray, gray - newgray)\n', (492, 540), True, 'import numpy as np\n'), ((606, 620), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (617, 620), False, 'import cv2\n')]
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np from numpy import sin, cos, tan, arctan2, radians, degrees, sqrt from Quaternion import Quat def radec2eci(ra, dec): """ Convert from RA,Dec to ECI. The input ``ra`` and ``dec`` values can be 1-d arrays of length N in which case the output ``ECI`` will be an array with shape (3,N). :param ra: Right Ascension (degrees) :param dec: Declination (degrees) :returns: numpy array ECI (3-vector or 3xN array) """ r = radians(ra) d = radians(dec) return np.array([cos(r) * cos(d), sin(r) * cos(d), sin(d)]) def eci2radec(eci): """ Convert from ECI vector(s) to RA, Dec. The input ``eci`` value can be an array of 3-vectors having shape (3,N) in which case the output RA, Dec will be arrays of length N. :param eci: ECI as 3-vector or (3,N) array :rtype: list ra, dec (degrees) """ ra = degrees(arctan2(eci[1], eci[0])) dec = degrees(arctan2(eci[2], sqrt(eci[1]**2 + eci[0]**2))) ok = ra < 0 if isinstance(ok, np.ndarray): ra[ok] += 360 elif ok: ra += 360 return ra, dec def radec2yagzag(ra, dec, q): """ Given RA, Dec, and pointing quaternion, determine ACA Y-ang, Z-ang. The input ``ra`` and ``dec`` values can be 1-d arrays in which case the output ``yag`` and ``zag`` will be corresponding arrays of the same length. :param ra: Right Ascension (degrees) :param dec: Declination (degrees) :param q: Quaternion :rtype: list yag, zag (degrees) """ eci = radec2eci(ra, dec) d_aca = np.dot(q.transform.transpose(), eci) yag = degrees(arctan2(d_aca[1], d_aca[0])) zag = degrees(arctan2(d_aca[2], d_aca[0])) return yag, zag def yagzag2radec(yag, zag, q): """ Given ACA Y-ang, Z-ang and pointing quaternion determine RA, Dec. The input ``yag`` and ``zag`` values can be 1-d arrays in which case the output ``ra`` and ``dec`` will be corresponding arrays of the same length. :param yag: ACA Y angle (degrees) :param zag: ACA Z angle (degrees) :param q: Quaternion :rtype: list ra, dec (degrees) """ try: one = np.ones(len(yag)) except TypeError: one = 1.0 d_aca = np.array([one, tan(radians(yag)), tan(radians(zag))]) d_aca *= 1.0 / np.sum(d_aca**2) eci = np.dot(q.transform, d_aca) return eci2radec(eci) def norm(vec): return vec / np.sqrt(np.sum(vec**2)) def quat_x_to_vec(vec, method='radec'): """Generate quaternion that rotates X-axis into ``vec``. The ``method`` parameter can take one of three values: "shortest", "keep_z", or "radec" (default). The "shortest" method takes the shortest path between the two vectors. The "radec" method does the transformation as the corresponding (RA, Dec, Roll=0) attitude. The "keep_z" method does a roll about X-axis (followed by the "shortest" path) such that the transformed Z-axis is in the original X-Z plane. In equations:: T: "shortest" quaternion taking X-axis to vec Rx(theta): Rotation by theta about X-axis = [[1,0,0], [0,c,s], [0,-s,c]] Z: Z-axis [0,0,1] [T * Rx(theta) * Z]_y = 0 T[1,1] * sin(theta) + T[1,2]*cos(theta) = 0 theta = atan2(T[1,2], T[1,1]) :param vec: Input 3-vector :param method: method for determining path (shortest|keep_z|radec) :returns: Quaternion object """ x = np.array([1., 0, 0]) vec = norm(np.array(vec)) if method in ("shortest", "keep_z"): dot = np.dot(x, vec) if abs(dot) > 1 - 1e-8: x = norm(np.array([1., 0., 1e-7])) dot = np.dot(vec, x) angle = np.arccos(dot) axis = norm(np.cross(x, vec)) sin_a = np.sin(angle / 2) cos_a = np.cos(angle / 2) q = Quat([axis[0] * sin_a, axis[1] * sin_a, axis[2] * sin_a, cos_a]) if method == "keep_z": T = q.transform theta = np.arctan2(T[1, 2], T[1, 1]) qroll = Quat([0, 0, degrees(theta)]) q = q * qroll else: ra = np.degrees(np.arctan2(vec[1], vec[0])) dec = np.degrees(np.arcsin(vec[2])) q = Quat([ra, dec, 0]) return q
[ "numpy.radians", "numpy.sum", "numpy.arctan2", "Quaternion.Quat", "numpy.degrees", "numpy.cross", "numpy.arcsin", "numpy.sin", "numpy.array", "numpy.cos", "numpy.dot", "numpy.arccos", "numpy.sqrt" ]
[((535, 546), 'numpy.radians', 'radians', (['ra'], {}), '(ra)\n', (542, 546), False, 'from numpy import sin, cos, tan, arctan2, radians, degrees, sqrt\n'), ((555, 567), 'numpy.radians', 'radians', (['dec'], {}), '(dec)\n', (562, 567), False, 'from numpy import sin, cos, tan, arctan2, radians, degrees, sqrt\n'), ((2382, 2408), 'numpy.dot', 'np.dot', (['q.transform', 'd_aca'], {}), '(q.transform, d_aca)\n', (2388, 2408), True, 'import numpy as np\n'), ((3470, 3491), 'numpy.array', 'np.array', (['[1.0, 0, 0]'], {}), '([1.0, 0, 0])\n', (3478, 3491), True, 'import numpy as np\n'), ((955, 978), 'numpy.arctan2', 'arctan2', (['eci[1]', 'eci[0]'], {}), '(eci[1], eci[0])\n', (962, 978), False, 'from numpy import sin, cos, tan, arctan2, radians, degrees, sqrt\n'), ((1681, 1708), 'numpy.arctan2', 'arctan2', (['d_aca[1]', 'd_aca[0]'], {}), '(d_aca[1], d_aca[0])\n', (1688, 1708), False, 'from numpy import sin, cos, tan, arctan2, radians, degrees, sqrt\n'), ((1728, 1755), 'numpy.arctan2', 'arctan2', (['d_aca[2]', 'd_aca[0]'], {}), '(d_aca[2], d_aca[0])\n', (1735, 1755), False, 'from numpy import sin, cos, tan, arctan2, radians, degrees, sqrt\n'), ((2355, 2373), 'numpy.sum', 'np.sum', (['(d_aca ** 2)'], {}), '(d_aca ** 2)\n', (2361, 2373), True, 'import numpy as np\n'), ((3506, 3519), 'numpy.array', 'np.array', (['vec'], {}), '(vec)\n', (3514, 3519), True, 'import numpy as np\n'), ((3576, 3590), 'numpy.dot', 'np.dot', (['x', 'vec'], {}), '(x, vec)\n', (3582, 3590), True, 'import numpy as np\n'), ((3719, 3733), 'numpy.arccos', 'np.arccos', (['dot'], {}), '(dot)\n', (3728, 3733), True, 'import numpy as np\n'), ((3788, 3805), 'numpy.sin', 'np.sin', (['(angle / 2)'], {}), '(angle / 2)\n', (3794, 3805), True, 'import numpy as np\n'), ((3822, 3839), 'numpy.cos', 'np.cos', (['(angle / 2)'], {}), '(angle / 2)\n', (3828, 3839), True, 'import numpy as np\n'), ((3852, 3916), 'Quaternion.Quat', 'Quat', (['[axis[0] * sin_a, axis[1] * sin_a, axis[2] * sin_a, cos_a]'], {}), '([axis[0] * sin_a, axis[1] * sin_a, axis[2] * sin_a, cos_a])\n', (3856, 3916), False, 'from Quaternion import Quat\n'), ((4273, 4291), 'Quaternion.Quat', 'Quat', (['[ra, dec, 0]'], {}), '([ra, dec, 0])\n', (4277, 4291), False, 'from Quaternion import Quat\n'), ((623, 629), 'numpy.sin', 'sin', (['d'], {}), '(d)\n', (626, 629), False, 'from numpy import sin, cos, tan, arctan2, radians, degrees, sqrt\n'), ((1014, 1045), 'numpy.sqrt', 'sqrt', (['(eci[1] ** 2 + eci[0] ** 2)'], {}), '(eci[1] ** 2 + eci[0] ** 2)\n', (1018, 1045), False, 'from numpy import sin, cos, tan, arctan2, radians, degrees, sqrt\n'), ((2477, 2493), 'numpy.sum', 'np.sum', (['(vec ** 2)'], {}), '(vec ** 2)\n', (2483, 2493), True, 'import numpy as np\n'), ((3688, 3702), 'numpy.dot', 'np.dot', (['vec', 'x'], {}), '(vec, x)\n', (3694, 3702), True, 'import numpy as np\n'), ((3754, 3770), 'numpy.cross', 'np.cross', (['x', 'vec'], {}), '(x, vec)\n', (3762, 3770), True, 'import numpy as np\n'), ((4051, 4079), 'numpy.arctan2', 'np.arctan2', (['T[1, 2]', 'T[1, 1]'], {}), '(T[1, 2], T[1, 1])\n', (4061, 4079), True, 'import numpy as np\n'), ((4189, 4215), 'numpy.arctan2', 'np.arctan2', (['vec[1]', 'vec[0]'], {}), '(vec[1], vec[0])\n', (4199, 4215), True, 'import numpy as np\n'), ((4242, 4259), 'numpy.arcsin', 'np.arcsin', (['vec[2]'], {}), '(vec[2])\n', (4251, 4259), True, 'import numpy as np\n'), ((589, 595), 'numpy.cos', 'cos', (['r'], {}), '(r)\n', (592, 595), False, 'from numpy import sin, cos, tan, arctan2, radians, degrees, sqrt\n'), ((598, 604), 'numpy.cos', 'cos', (['d'], {}), '(d)\n', (601, 604), False, 'from numpy import sin, cos, tan, arctan2, radians, degrees, sqrt\n'), ((606, 612), 'numpy.sin', 'sin', (['r'], {}), '(r)\n', (609, 612), False, 'from numpy import sin, cos, tan, arctan2, radians, degrees, sqrt\n'), ((615, 621), 'numpy.cos', 'cos', (['d'], {}), '(d)\n', (618, 621), False, 'from numpy import sin, cos, tan, arctan2, radians, degrees, sqrt\n'), ((2301, 2313), 'numpy.radians', 'radians', (['yag'], {}), '(yag)\n', (2308, 2313), False, 'from numpy import sin, cos, tan, arctan2, radians, degrees, sqrt\n'), ((2320, 2332), 'numpy.radians', 'radians', (['zag'], {}), '(zag)\n', (2327, 2332), False, 'from numpy import sin, cos, tan, arctan2, radians, degrees, sqrt\n'), ((3644, 3671), 'numpy.array', 'np.array', (['[1.0, 0.0, 1e-07]'], {}), '([1.0, 0.0, 1e-07])\n', (3652, 3671), True, 'import numpy as np\n'), ((4112, 4126), 'numpy.degrees', 'degrees', (['theta'], {}), '(theta)\n', (4119, 4126), False, 'from numpy import sin, cos, tan, arctan2, radians, degrees, sqrt\n')]
import torch from torch import nn from torch.nn import functional as F from Utils.flags import FLAGS import numpy as np from torch.autograd import Variable crossentropy = nn.CrossEntropyLoss() softmax = nn.Softmax(1) logsoftmax = nn.LogSoftmax(1) # some utils TODO def update_average(model_tgt, model_src, beta=0.999): param_dict_src = dict(model_src.named_parameters()) for p_name, p_tgt in model_tgt.named_parameters(): p_src = param_dict_src[p_name] assert p_src is not p_tgt p_tgt.data.mul_(beta).add_((1 - beta) * p_src.data) def sigmoid_rampup(global_step, rampup_length): global_step = np.clip(global_step, 0, rampup_length) phase = 1.0 - global_step / rampup_length return np.exp(-5.0 * phase * phase) def sigmoid_rampdown(global_step, rampdown_length, training_length): if global_step >= training_length - rampdown_length: phase = 1.0 - (training_length - global_step) / rampdown_length return np.exp(-12.5 * phase * phase) else: return 1.0 def linear_rampup(current, rampup_length): """Linear rampup""" assert current >= 0 and rampup_length >= 0 if current >= rampup_length: return 1.0 else: return current / rampup_length def cosine_rampdown(current, rampdown_length, training_length): """Cosine rampdown from https://arxiv.org/abs/1608.03983""" assert 0 <= current <= training_length if current >= training_length - rampdown_length: return float(0.5 * (np.cos(np.pi * current / training_length) + 1)) else: return 1.0 def cosine_rampdown_1(current, rampdown_length): """Cosine rampdown from https://arxiv.org/abs/1608.03983""" assert 0 <= current <= rampdown_length return max(0.0, float(0.5 * (np.cos(np.pi * current / rampdown_length) + 1))) # losses def entropy(logits): prob = softmax(logits) logprob = logsoftmax(logits) return -torch.sum(prob * logprob, dim=1) def loss_cross_entropy(logits, label): loss = crossentropy(logits, label) return loss def loss_elr(netC, it, iter_l, device): data, label = iter_l.__next__() data, label = data.to(device), label.to(device) logit_l = netC(data) loss_l = loss_cross_entropy(logit_l, label) return loss_l def loss_elr_wrap(netC, netC_T, it, iter_l, itr, device): data, label = iter_l.__next__() data, label = data.to(device), label.to(device) logit_l = netC(data) loss_l = loss_cross_entropy(logit_l, label) return loss_l, loss_l, loss_l def loss_supervised(netC, netC_T, it, iter_l, iter_u, device): data, label = iter_l.__next__() data_u, _ = iter_u.__next__() data_u = data_u.to(device) logit_ut = netC_T(data_u).detach() data, label = data.to(device), label.to(device) logit_l = netC(data) loss_l = loss_cross_entropy(logit_l, label) return loss_l, loss_l.detach(), torch.zeros_like(loss_l.detach()) def loss_entropy_ssl(netC, netC_T, it, iter_l, iter_u, device): data, label = iter_l.__next__() data, label = data.to(device), label.to(device) data_u, _ = iter_u.__next__() data_u = data_u.to(device) logit_l = netC(data) logit_u = netC(data_u) logit_ut = netC_T(data_u).detach() loss_l = loss_cross_entropy(logit_l, label) loss_u = FLAGS.alpha_entropy * torch.mean(entropy(logit_u), dim=0) return loss_l + loss_u, loss_l.detach(), loss_u.detach() def loss_MT_double_ssl(netC, netC_T, it, iter_l, iter_u, device): if it == 0: print("Using Double MT SSL") data, label = iter_l.__next__() data, label = data.to(device), label.to(device) data_u, _ = iter_u.__next__() data_u = data_u.to(device) sigmoid_rampup_value = sigmoid_rampup(it, FLAGS.rampup_length) cons_coefficient = sigmoid_rampup_value * FLAGS.max_consistency_cost logit_l = netC(data) logit_u_1, logit_u_2 = netC(data_u, double=True) logit_ut = netC_T(data_u).detach() loss_l = loss_cross_entropy(logit_l, label) prob_u_2 = softmax(logit_u_2) prob_t = softmax(logit_ut) loss_u = cons_coefficient * torch.mean((prob_u_2 - prob_t) ** 2, dim=[0, 1]) loss_u = loss_u + FLAGS.alpha_mse * torch.mean( (logit_u_2 - logit_u_1) ** 2, dim=[0, 1] ) return loss_l + loss_u, loss_l.detach(), loss_u.detach() def loss_MT_ssl(netC, netC_T, it, iter_l, iter_u, device): data, label = iter_l.__next__() data, label = data.to(device), label.to(device) data_u, _ = iter_u.__next__() data_u = data_u.to(device) sigmoid_rampup_value = sigmoid_rampup(it, FLAGS.rampup_length) cons_coefficient = sigmoid_rampup_value * FLAGS.max_consistency_cost lpi = FLAGS.num_label_per_batch batch_input = torch.cat([data[:lpi], data_u[lpi:]], dim=0) logit = netC(batch_input) logit_ut = netC_T(batch_input).detach() logit_l = logit[:lpi] logit_u = logit # logit_l = netC(data) # logit_u = netC(data_u) # logit_ut = netC_T(data_u).detach() loss_l = loss_cross_entropy(logit_l, label[:lpi]) prob = softmax(logit_u) prob_t = softmax(logit_ut) loss_u = cons_coefficient * torch.mean((prob - prob_t) ** 2, dim=[0, 1]) return loss_l + loss_u, loss_l.detach(), loss_u.detach() def step_ramp(optim_c, netC, netC_T, it, tloss): sigmoid_rampup_value = sigmoid_rampup(it, FLAGS.rampup_length_lr) sigmoid_rampdown_value = sigmoid_rampdown(it, FLAGS.rampdown_length, FLAGS.n_iter) lr = FLAGS.c_lr * sigmoid_rampup_value * sigmoid_rampdown_value adam_beta_1 = ( sigmoid_rampdown_value * FLAGS.adam_beta_1_before_rampdown + (1 - sigmoid_rampdown_value) * FLAGS.adam_beta_1_after_rampdown ) if it < FLAGS.rampup_length: adam_beta_2 = FLAGS.adam_beta_2_during_rampup ema_decay = FLAGS.ema_decay_during_rampup else: adam_beta_2 = FLAGS.adam_beta_2_after_rampup ema_decay = FLAGS.ema_decay_after_rampup # update adam optim_c.param_groups[0]["betas"] = (adam_beta_1, adam_beta_2) optim_c.param_groups[0]["lr"] = lr # update student optim_c.zero_grad() tloss.backward() if FLAGS.clip_value > 0: torch.nn.utils.clip_grad_norm_(netC.parameters(), FLAGS.clip_value) optim_c.step() # update teacher update_average(netC_T, netC, ema_decay) def step_ramp_swa(optim_c, swa_optim, netC, netC_T, it, tloss): ema_decay = FLAGS.ema_decay_after_rampup linear_rampup_value = linear_rampup(it, FLAGS.rampup_length_lr) if it >= FLAGS.swa_start and (it - FLAGS.swa_start) % FLAGS.cycle_interval == 0: swa_optim.update(netC) if it < FLAGS.swa_start: # Cosine LR rampdown from https://arxiv.org/abs/1608.03983 assert FLAGS.rampdown_length >= FLAGS.swa_start cosine_rampdown_value = cosine_rampdown_1(it, FLAGS.rampdown_length) elif it >= FLAGS.swa_start: cosine_rampdown_value = cosine_rampdown_1( (FLAGS.swa_start - FLAGS.cycle_interval) + ((it - FLAGS.swa_start) % FLAGS.cycle_interval), FLAGS.rampdown_length, ) cosine_rampdown_value = cosine_rampdown(it, FLAGS.rampdown_length, FLAGS.n_iter) lr = FLAGS.c_lr * linear_rampup_value * cosine_rampdown_value # update adam optim_c.param_groups[0]["lr"] = lr # update student optim_c.zero_grad() tloss.backward() if FLAGS.clip_value > 0: torch.nn.utils.clip_grad_norm_(netC.parameters(), FLAGS.clip_value) optim_c.step() # update teacher update_average(netC_T, netC, ema_decay) def step_ramp_linear(optim_c, netC, netC_T, it, tloss): ema_decay = FLAGS.ema_decay_after_rampup linear_rampup_value = linear_rampup(it, FLAGS.rampup_length_lr) cosine_rampdown_value = cosine_rampdown(it, FLAGS.rampdown_length, FLAGS.n_iter) lr = FLAGS.c_lr * linear_rampup_value * cosine_rampdown_value # update adam optim_c.param_groups[0]["lr"] = lr # update student optim_c.zero_grad() tloss.backward() if FLAGS.clip_value > 0: torch.nn.utils.clip_grad_norm_(netC.parameters(), FLAGS.clip_value) optim_c.step() # update teacher update_average(netC_T, netC, ema_decay) def step_vat(optim_c, netC, netC_T, it, tloss): ema_decay = FLAGS.ema_decay_after_rampup if it > FLAGS.lr_anneal_num: decayed_lr = ( (FLAGS.n_iter - it) * FLAGS.c_lr / (FLAGS.n_iter - FLAGS.lr_anneal_num) ) optim_c.param_groups[0]["lr"] = decayed_lr # update student optim_c.zero_grad() tloss.backward() if FLAGS.clip_value > 0: torch.nn.utils.clip_grad_norm_(netC.parameters(), FLAGS.clip_value) optim_c.step() # update teacher update_average(netC_T, netC, ema_decay) def step_regular(optim_c, netC, netC_T, it, tloss): ema_decay = FLAGS.ema_decay_after_rampup if it > FLAGS.lr_anneal_num: times = (it - FLAGS.lr_anneal_num) // FLAGS.lr_anneal_interval lr = FLAGS.c_lr * (FLAGS.lr_anneal_coe ** times) optim_c.param_groups[0]["lr"] = lr # update student optim_c.zero_grad() tloss.backward() if FLAGS.clip_value > 0: torch.nn.utils.clip_grad_norm_(netC.parameters(), FLAGS.clip_value) optim_c.step() # update teacher update_average(netC_T, netC, ema_decay) def kl_div_with_logit(q_logit, p_logit): q = F.softmax(q_logit, dim=1) logq = F.log_softmax(q_logit, dim=1) logp = F.log_softmax(p_logit, dim=1) qlogq = (q * logq).sum(dim=1).mean(dim=0) qlogp = (q * logp).sum(dim=1).mean(dim=0) return qlogq - qlogp def vat_loss_ssl(netC, netC_T, it, iter_l, iter_u, device): data, label = iter_l.__next__() data, label = data.to(device), label.to(device) data_u, _ = iter_u.__next__() data_u = data_u.to(device) logit_l = netC(data) logit_u = netC(data_u) loss_u = vat_loss( netC, data_u, logit_u, FLAGS.vat_xi, FLAGS.vat_eps, FLAGS.vat_iters ) loss_u = loss_u + torch.mean(entropy(logit_u), dim=0) loss_l = loss_cross_entropy(logit_l, label) return loss_l + loss_u, loss_l.detach(), loss_u.detach() def _l2_normalize(d): d = d.numpy() d /= np.sqrt(np.sum(d ** 2, axis=(1, 2, 3))).reshape((-1, 1, 1, 1)) + 1e-16 return torch.from_numpy(d) def vat_loss(model, ul_x, ul_y, xi=1e-6, eps=2.5, num_iters=1): # find r_adv d = torch.Tensor(ul_x.size()).normal_() for i in range(num_iters): d = xi * _l2_normalize(d) d = Variable(d.cuda(), requires_grad=True) y_hat = model(ul_x + d) delta_kl = kl_div_with_logit(ul_y.detach(), y_hat) delta_kl.backward() d = d.grad.data.clone().cpu() model.zero_grad() d = _l2_normalize(d) d = Variable(d.cuda()) r_adv = eps * d # compute lds y_hat = model(ul_x + r_adv.detach()) delta_kl = kl_div_with_logit(ul_y.detach(), y_hat) return delta_kl c_loss_dict = { "crossentropy": loss_supervised, "entropyssl": loss_entropy_ssl, "mtssl": loss_MT_ssl, "mtdoublessl": loss_MT_double_ssl, "vatssl": vat_loss_ssl, "loss_elr_wrap": loss_elr_wrap, } c_step_func = { "ramp": step_ramp, "ramp_linear": step_ramp_linear, "regular": step_regular, "step_vat": step_vat, "ramp_swa": step_ramp_swa, }
[ "torch.mean", "numpy.sum", "torch.nn.LogSoftmax", "torch.nn.CrossEntropyLoss", "torch.cat", "numpy.clip", "torch.nn.functional.softmax", "torch.nn.Softmax", "numpy.exp", "torch.nn.functional.log_softmax", "numpy.cos", "torch.sum", "torch.from_numpy" ]
[((173, 194), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (192, 194), False, 'from torch import nn\n'), ((205, 218), 'torch.nn.Softmax', 'nn.Softmax', (['(1)'], {}), '(1)\n', (215, 218), False, 'from torch import nn\n'), ((232, 248), 'torch.nn.LogSoftmax', 'nn.LogSoftmax', (['(1)'], {}), '(1)\n', (245, 248), False, 'from torch import nn\n'), ((635, 673), 'numpy.clip', 'np.clip', (['global_step', '(0)', 'rampup_length'], {}), '(global_step, 0, rampup_length)\n', (642, 673), True, 'import numpy as np\n'), ((731, 759), 'numpy.exp', 'np.exp', (['(-5.0 * phase * phase)'], {}), '(-5.0 * phase * phase)\n', (737, 759), True, 'import numpy as np\n'), ((4729, 4773), 'torch.cat', 'torch.cat', (['[data[:lpi], data_u[lpi:]]'], {'dim': '(0)'}), '([data[:lpi], data_u[lpi:]], dim=0)\n', (4738, 4773), False, 'import torch\n'), ((9358, 9383), 'torch.nn.functional.softmax', 'F.softmax', (['q_logit'], {'dim': '(1)'}), '(q_logit, dim=1)\n', (9367, 9383), True, 'from torch.nn import functional as F\n'), ((9395, 9424), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['q_logit'], {'dim': '(1)'}), '(q_logit, dim=1)\n', (9408, 9424), True, 'from torch.nn import functional as F\n'), ((9436, 9465), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['p_logit'], {'dim': '(1)'}), '(p_logit, dim=1)\n', (9449, 9465), True, 'from torch.nn import functional as F\n'), ((10261, 10280), 'torch.from_numpy', 'torch.from_numpy', (['d'], {}), '(d)\n', (10277, 10280), False, 'import torch\n'), ((975, 1004), 'numpy.exp', 'np.exp', (['(-12.5 * phase * phase)'], {}), '(-12.5 * phase * phase)\n', (981, 1004), True, 'import numpy as np\n'), ((1926, 1958), 'torch.sum', 'torch.sum', (['(prob * logprob)'], {'dim': '(1)'}), '(prob * logprob, dim=1)\n', (1935, 1958), False, 'import torch\n'), ((4102, 4150), 'torch.mean', 'torch.mean', (['((prob_u_2 - prob_t) ** 2)'], {'dim': '[0, 1]'}), '((prob_u_2 - prob_t) ** 2, dim=[0, 1])\n', (4112, 4150), False, 'import torch\n'), ((5137, 5181), 'torch.mean', 'torch.mean', (['((prob - prob_t) ** 2)'], {'dim': '[0, 1]'}), '((prob - prob_t) ** 2, dim=[0, 1])\n', (5147, 5181), False, 'import torch\n'), ((4191, 4243), 'torch.mean', 'torch.mean', (['((logit_u_2 - logit_u_1) ** 2)'], {'dim': '[0, 1]'}), '((logit_u_2 - logit_u_1) ** 2, dim=[0, 1])\n', (4201, 4243), False, 'import torch\n'), ((1505, 1546), 'numpy.cos', 'np.cos', (['(np.pi * current / training_length)'], {}), '(np.pi * current / training_length)\n', (1511, 1546), True, 'import numpy as np\n'), ((1773, 1814), 'numpy.cos', 'np.cos', (['(np.pi * current / rampdown_length)'], {}), '(np.pi * current / rampdown_length)\n', (1779, 1814), True, 'import numpy as np\n'), ((10187, 10217), 'numpy.sum', 'np.sum', (['(d ** 2)'], {'axis': '(1, 2, 3)'}), '(d ** 2, axis=(1, 2, 3))\n', (10193, 10217), True, 'import numpy as np\n')]
"""libaray for multi-modal dataset loaders. Acknowledgements: `image_to_caption_collate_fn` is based on https://github.com/yalesong/pvse/blob/master/data.py """ import os import numpy as np import torch from torch.utils.data import DataLoader from datasets.coco import CocoCaptionsCap from datasets.cub import CUBCaption, CUBSampler from datasets.vocab import Vocabulary from datasets._transforms import imagenet_transform, caption_transform def image_to_caption_collate_fn(data): """Build mini-batch tensors from a list of (image, sentence) tuples. Args: data: list of (image, sentence) tuple. - image: torch tensor of shape (3, 256, 256) or (?, 3, 256, 256). - sentence: torch tensor of shape (?); variable length. Returns: images: torch tensor of shape (batch_size, 3, 256, 256) or (batch_size, padded_length, 3, 256, 256). targets: torch tensor of shape (batch_size, padded_length). lengths: list; valid length for each padded sentence. """ # Sort a data list by sentence length data.sort(key=lambda x: len(x[1]), reverse=True) images, sentences, ann_ids, image_ids = zip(*data) # Merge images (convert tuple of 3D tensor to 4D tensor) images = torch.stack(images, 0) # Merge sentences (convert tuple of 1D tensor to 2D tensor) cap_lengths = [len(cap) for cap in sentences] targets = torch.zeros(len(sentences), max(cap_lengths)).long() for i, cap in enumerate(sentences): end = cap_lengths[i] targets[i, :end] = cap[:end] cap_lengths = torch.Tensor(cap_lengths).long() return images, targets, cap_lengths, ann_ids, image_ids def load_vocab(vocab_path): if isinstance(vocab_path, str): vocab = Vocabulary() vocab.load_from_pickle(vocab_path) else: vocab = vocab_path return vocab def _get_cub_file_paths(dataset_name, dataset_root, caption_root): """Select proper train / val classes and omit id files. The split is based on CVPR'17 Zero-Shot Learning -- The Good, the Bad and the Ugly See more details in https://arxiv.org/abs/1703.04394 https://www.mpi-inf.mpg.de/departments/computer-vision-and-machine-learning/research/zero-shot-learning/zero-shot-learning-the-good-the-bad-and-the-ugly Args: dataset_name: name of dataset - cub_trainval{idx} (idx in [1, 2, 3]): 3-fold validation splits to search hyperparameters. Each split contains 100 train classes / 50 validation classes. - cub: The final split used for the final benchmark. This split conntains 150 train classes / 50 unseen test classes (not in trainval) """ if dataset_name == 'cub_trainval1': train_classes = './datasets/annotations/cub/trainclasses1.txt' val_classes = './datasets/annotations/cub/valclasses1.txt' omit_ids = './datasets/annotations/cub/seen_test_images.txt' elif dataset_name == 'cub_trainval2': train_classes = './datasets/annotations/cub/trainclasses2.txt' val_classes = './datasets/annotations/cub/valclasses2.txt' omit_ids = './datasets/annotations/cub/seen_test_images.txt' elif dataset_name == 'cub_trainval3': train_classes = './datasets/annotations/cub/trainclasses3.txt' val_classes = './datasets/annotations/cub/valclasses3.txt' omit_ids = './datasets/annotations/cub/seen_test_images.txt' elif dataset_name == 'cub': train_classes = './datasets/annotations/cub/trainvalclasses.txt' val_classes = './datasets/annotations/cub/testclasses.txt' omit_ids = './datasets/annotations/cub/seen_test_images.txt' else: raise ValueError(f'Invalide dataset_name: {dataset_name}') image_root = os.path.join(dataset_root, 'images/') return train_classes, val_classes, omit_ids, image_root, caption_root def _get_cub_loader(image_root, caption_root, data_classes, vocab, num_workers, batch_size=64, train=False, omit_ids=None, ids=None, cutout_prob=0.0, caption_drop_prob=0.0): cub_dataset = CUBCaption(image_root, caption_root, data_classes, imagenet_transform(random_erasing_prob=cutout_prob), caption_transform(vocab, caption_drop_prob), omit_ids=omit_ids, ids=ids) if train: sampler = CUBSampler(cub_dataset, len(cub_dataset.target_classes)) dataloader = DataLoader(cub_dataset, batch_sampler=sampler, num_workers=num_workers, collate_fn=image_to_caption_collate_fn, pin_memory=True) else: dataloader = DataLoader(cub_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers, collate_fn=image_to_caption_collate_fn, pin_memory=True) print(f'Loading CUB Caption: n_images {cub_dataset.n_images} n_captions {len(cub_dataset.targets)}...') return dataloader def prepare_cub_dataloaders(dataloader_config, dataset_name, dataset_root, caption_root, vocab_path='./vocabs/cub_vocab.pkl', num_workers=6): """Prepare CUB Caption train / val / test dataloaders CUB Caption loader has a fixed batch size - train loader: # classes (trainval = 100, full = 150) - test loader: 64 (hard coded at L#203) Args: dataloader_config (dict): configuration file which should contain "batch_size" dataset_name (str): name of dataset - cub_trainval{idx} (idx in [1, 2, 3]): 3-fold validation splits to search hyperparameters. Each split contains 100 train classes / 50 validation classes. - cub: The final split used for the final benchmark. This split conntains 150 train classes / 50 unseen test classes (not in trainval) dataset_root (str): root of your CUB images (see README.md for detailed dataset hierarchy) caption_root (str): root of your CUB captions (see README.md for detailed dataset hierarchy) vocab_path (str, optional): path for vocab pickle file (default: ./vocabs/cub_vocab.pkl). num_workers (int, optional): num_workers for the dataloaders (default: 6) Returns: dataloaders (dict): keys = ["train", "val", "val_in"], values are the corresponding dataloaders. vocab (Vocabulary object): vocab object """ vocab = load_vocab(vocab_path) train_classes, val_classes, omit_ids, image_root, caption_root = _get_cub_file_paths( dataset_name, dataset_root, caption_root) cutout_prob = dataloader_config.get('random_erasing_prob', 0.0) caption_drop_prob = dataloader_config.get('caption_drop_prob', 0.0) dataloaders = {} dataloaders['train'] = _get_cub_loader( image_root, caption_root, train_classes, vocab, num_workers, train=True, omit_ids=omit_ids, cutout_prob=cutout_prob, caption_drop_prob=caption_drop_prob, ) dataloaders['val'] = _get_cub_loader( image_root, caption_root, val_classes, vocab, num_workers, train=False, ) dataloaders['val_in'] = _get_cub_loader( image_root, caption_root, train_classes, vocab, num_workers, train=False, ids=omit_ids ) return dataloaders, vocab def _get_coco_loader(image_root, annotation_path, ids, vocab, num_workers, batch_size=64, train=False, extra_ids=None, extra_annotation_path=None, cutout_prob=0.0, caption_drop_prob=0.0): _image_transform = imagenet_transform( random_resize_crop=train, random_erasing_prob=cutout_prob, ) _caption_transform = caption_transform(vocab, caption_drop_prob) coco_dataset = CocoCaptionsCap(image_root, annotation_path, extra_annFile=extra_annotation_path, ids=ids, extra_ids=extra_ids, transform=_image_transform, target_transform=_caption_transform) dataloader = DataLoader(coco_dataset, batch_size=batch_size, shuffle=train, num_workers=num_workers, collate_fn=image_to_caption_collate_fn, pin_memory=True) print(f'Loading COCO Caption: n_images {coco_dataset.n_images} n_captions {len(coco_dataset)}...') return dataloader def _get_coco_file_paths(dataset_root): """Select proper train / val classes and omit id files. """ train_ids = np.load('./datasets/annotations/coco_train_ids.npy') train_extra_ids = np.load('./datasets/annotations/coco_restval_ids.npy') val_ids = np.load('./datasets/annotations/coco_dev_ids.npy')[:5000] te_ids = np.load('./datasets/annotations/coco_test_ids.npy') image_root = os.path.join(dataset_root, 'images/trainval35k') train_ann = os.path.join(dataset_root, 'annotations/annotations/captions_train2014.json') val_ann = os.path.join(dataset_root, 'annotations/annotations/captions_val2014.json') return train_ids, train_extra_ids, val_ids, te_ids, image_root, train_ann, val_ann def prepare_coco_dataloaders(dataloader_config, dataset_root, vocab_path='./vocabs/coco_vocab.pkl', num_workers=6): """Prepare MS-COCO Caption train / val / test dataloaders Args: dataloader_config (dict): configuration file which should contain "batch_size" dataset_root (str): root of your MS-COCO dataset (see README.md for detailed dataset hierarchy) vocab_path (str, optional): path for vocab pickle file (default: ./vocabs/coco_vocab.pkl). num_workers (int, optional): num_workers for the dataloaders (default: 6) Returns: dataloaders (dict): keys = ["train", "val", "te"], values are the corresponding dataloaders. vocab (Vocabulary object): vocab object """ batch_size = dataloader_config['batch_size'] tr_cutout_prob = dataloader_config.get('random_erasing_prob', 0.0) tr_caption_drop_prob = dataloader_config.get('caption_drop_prob', 0.0) eval_batch_size = dataloader_config.get('eval_batch_size', batch_size) vocab = load_vocab(vocab_path) train_ids, train_extra_ids, val_ids, te_ids, image_root, train_ann, val_ann = _get_coco_file_paths(dataset_root) dataloaders = {} dataloaders['train'] = _get_coco_loader( image_root, train_ann, train_ids, vocab, num_workers=num_workers, batch_size=batch_size, train=True, extra_annotation_path=val_ann, extra_ids=train_extra_ids, cutout_prob=tr_cutout_prob, caption_drop_prob=tr_caption_drop_prob, ) dataloaders['val'] = _get_coco_loader( image_root, val_ann, val_ids, vocab, num_workers=num_workers, batch_size=eval_batch_size, train=False, ) dataloaders['te'] = _get_coco_loader( image_root, val_ann, te_ids, vocab, num_workers=num_workers, batch_size=eval_batch_size, train=False, ) return dataloaders, vocab
[ "numpy.load", "torch.stack", "torch.utils.data.DataLoader", "datasets.coco.CocoCaptionsCap", "datasets._transforms.imagenet_transform", "datasets.vocab.Vocabulary", "torch.Tensor", "datasets._transforms.caption_transform", "os.path.join" ]
[((1247, 1269), 'torch.stack', 'torch.stack', (['images', '(0)'], {}), '(images, 0)\n', (1258, 1269), False, 'import torch\n'), ((3785, 3822), 'os.path.join', 'os.path.join', (['dataset_root', '"""images/"""'], {}), "(dataset_root, 'images/')\n", (3797, 3822), False, 'import os\n'), ((8301, 8378), 'datasets._transforms.imagenet_transform', 'imagenet_transform', ([], {'random_resize_crop': 'train', 'random_erasing_prob': 'cutout_prob'}), '(random_resize_crop=train, random_erasing_prob=cutout_prob)\n', (8319, 8378), False, 'from datasets._transforms import imagenet_transform, caption_transform\n'), ((8427, 8470), 'datasets._transforms.caption_transform', 'caption_transform', (['vocab', 'caption_drop_prob'], {}), '(vocab, caption_drop_prob)\n', (8444, 8470), False, 'from datasets._transforms import imagenet_transform, caption_transform\n'), ((8534, 8720), 'datasets.coco.CocoCaptionsCap', 'CocoCaptionsCap', (['image_root', 'annotation_path'], {'extra_annFile': 'extra_annotation_path', 'ids': 'ids', 'extra_ids': 'extra_ids', 'transform': '_image_transform', 'target_transform': '_caption_transform'}), '(image_root, annotation_path, extra_annFile=\n extra_annotation_path, ids=ids, extra_ids=extra_ids, transform=\n _image_transform, target_transform=_caption_transform)\n', (8549, 8720), False, 'from datasets.coco import CocoCaptionsCap\n'), ((8904, 9053), 'torch.utils.data.DataLoader', 'DataLoader', (['coco_dataset'], {'batch_size': 'batch_size', 'shuffle': 'train', 'num_workers': 'num_workers', 'collate_fn': 'image_to_caption_collate_fn', 'pin_memory': '(True)'}), '(coco_dataset, batch_size=batch_size, shuffle=train, num_workers=\n num_workers, collate_fn=image_to_caption_collate_fn, pin_memory=True)\n', (8914, 9053), False, 'from torch.utils.data import DataLoader\n'), ((9440, 9492), 'numpy.load', 'np.load', (['"""./datasets/annotations/coco_train_ids.npy"""'], {}), "('./datasets/annotations/coco_train_ids.npy')\n", (9447, 9492), True, 'import numpy as np\n'), ((9515, 9569), 'numpy.load', 'np.load', (['"""./datasets/annotations/coco_restval_ids.npy"""'], {}), "('./datasets/annotations/coco_restval_ids.npy')\n", (9522, 9569), True, 'import numpy as np\n'), ((9655, 9706), 'numpy.load', 'np.load', (['"""./datasets/annotations/coco_test_ids.npy"""'], {}), "('./datasets/annotations/coco_test_ids.npy')\n", (9662, 9706), True, 'import numpy as np\n'), ((9725, 9773), 'os.path.join', 'os.path.join', (['dataset_root', '"""images/trainval35k"""'], {}), "(dataset_root, 'images/trainval35k')\n", (9737, 9773), False, 'import os\n'), ((9790, 9867), 'os.path.join', 'os.path.join', (['dataset_root', '"""annotations/annotations/captions_train2014.json"""'], {}), "(dataset_root, 'annotations/annotations/captions_train2014.json')\n", (9802, 9867), False, 'import os\n'), ((9882, 9957), 'os.path.join', 'os.path.join', (['dataset_root', '"""annotations/annotations/captions_val2014.json"""'], {}), "(dataset_root, 'annotations/annotations/captions_val2014.json')\n", (9894, 9957), False, 'import os\n'), ((1752, 1764), 'datasets.vocab.Vocabulary', 'Vocabulary', ([], {}), '()\n', (1762, 1764), False, 'from datasets.vocab import Vocabulary\n'), ((4361, 4412), 'datasets._transforms.imagenet_transform', 'imagenet_transform', ([], {'random_erasing_prob': 'cutout_prob'}), '(random_erasing_prob=cutout_prob)\n', (4379, 4412), False, 'from datasets._transforms import imagenet_transform, caption_transform\n'), ((4443, 4486), 'datasets._transforms.caption_transform', 'caption_transform', (['vocab', 'caption_drop_prob'], {}), '(vocab, caption_drop_prob)\n', (4460, 4486), False, 'from datasets._transforms import imagenet_transform, caption_transform\n'), ((4684, 4816), 'torch.utils.data.DataLoader', 'DataLoader', (['cub_dataset'], {'batch_sampler': 'sampler', 'num_workers': 'num_workers', 'collate_fn': 'image_to_caption_collate_fn', 'pin_memory': '(True)'}), '(cub_dataset, batch_sampler=sampler, num_workers=num_workers,\n collate_fn=image_to_caption_collate_fn, pin_memory=True)\n', (4694, 4816), False, 'from torch.utils.data import DataLoader\n'), ((4940, 5088), 'torch.utils.data.DataLoader', 'DataLoader', (['cub_dataset'], {'batch_size': 'batch_size', 'shuffle': '(False)', 'num_workers': 'num_workers', 'collate_fn': 'image_to_caption_collate_fn', 'pin_memory': '(True)'}), '(cub_dataset, batch_size=batch_size, shuffle=False, num_workers=\n num_workers, collate_fn=image_to_caption_collate_fn, pin_memory=True)\n', (4950, 5088), False, 'from torch.utils.data import DataLoader\n'), ((9584, 9634), 'numpy.load', 'np.load', (['"""./datasets/annotations/coco_dev_ids.npy"""'], {}), "('./datasets/annotations/coco_dev_ids.npy')\n", (9591, 9634), True, 'import numpy as np\n'), ((1577, 1602), 'torch.Tensor', 'torch.Tensor', (['cap_lengths'], {}), '(cap_lengths)\n', (1589, 1602), False, 'import torch\n')]
""" This module contains functions to average mdtraj-object data """ from copy import deepcopy import numpy as np from ase.data import chemical_symbols as symbols def average_energies(mdtraj_list, tstart): """ function to compute averages of a selection of mdtraj objects sorted by their composition Parameters ---------- mdtraj_list : list list of mdtraj objects tstart : int time after when to evalute (in time units of mdtraj) Returns ------- edat : dictionay dictionary with entries `ekin`, `epot`, `etot` and each composition including the average and standard deviation """ # get trajectory composition and bundle trajectories ekeys = ['etot', 'epot', 'ekin'] comps = {traj.get_traj_composition():[] for traj in mdtraj_list} edat = {ek:deepcopy(comps) for ek in ekeys} for traj in mdtraj_list: comp = traj.get_traj_composition() ed = traj.get_traj_energies() for ek in ekeys: edat[ek][comp].append(np.mean(ed[ek][tstart:])) for ek in edat: for comp in edat[ek]: edat[ek][comp] = {'mean':np.mean(edat[ek][comp]), \ 'std':np.std(edat[ek][comp])/np.sqrt(len(edat[ek][comp]))} return(edat) def sort_energies(mdtraj_list): """ function to sort energy data and return it sorted by composition Parameters ---------- mdtraj_list : list list of mdtraj objects Returns ------- edat : dictionay dictionary with with entries `ekin`, `epot`, `etot` per composition """ ekeys = ['etot', 'epot', 'ekin'] comps = {traj.get_traj_composition():[] for traj in mdtraj_list} edat = {ek:deepcopy(comps) for ek in ekeys} timedat = {'timestep':[],'timeunit':[]} for traj in mdtraj_list: comp = traj.get_traj_composition() ed = traj.get_traj_energies() for ek in ekeys: edat[ek][comp].append(ed[ek]) # store time data for k in timedat: timedat[k].append(ed[k]) # check consistency in time data: for k in timedat: assert len(list(set(timedat[k]))) == 1 for k in timedat: edat.update({k:list(set(timedat[k]))[0]}) return(edat) def average_densities(mdtraj_list, height_axis=2, tstart=0): """ function to average density profiles. Densities are aligned to end of substrate Parameters ---------- mdtraj_list : list list of mdtraj objects height_axis : int axis along which to process the density profile tstart : int time after when to evalute (in time units of mdtraj) Returns ------- dens_data : dictionary included: `binc` center of bins of density, `hists` histograms of density for each element and separated solvent (tag=solv) in mol/cm3 """ # sort mdtraj_list by composition comps = [traj.get_traj_composition() for traj in mdtraj_list] comp_dict= {c:[mdtraj_list[i] for i in range(len(mdtraj_list)) \ if comps[i] == c] for c in set(comps)} comp_dens = {} # compute densities for each composition and average for comp in comp_dict: av_dens = {'hists':{}, 'binc':[]} for mdsub in comp_dict[comp]: # get inividual density dens = mdsub.get_density_profile(height_axis=height_axis, \ tstart=tstart, savepkl=True) # determine substrate species esub = [symbols[i] for i in mdsub.get_substrate_types()] if len(esub) > 1: raise NotImplementedError("multi-elemental substrate found") dens = align_density_to_substrate(dens, esub[0]) # update av_dens with bin centers if len(av_dens['binc']) == 0: av_dens['binc'] = deepcopy(dens['binc']) # sum-up values - first profile determines shape for k in dens['hists'].keys(): if k not in av_dens['hists']: av_dens['hists'].update({k:np.zeros(dens['hists'][k].shape)}) lk = min(dens['hists'][k].size, av_dens['hists'][k].size) av_dens['hists'][k][:lk] += dens['hists'][k][:lk] # average by number of summed up histograms for k in av_dens['hists']: av_dens['hists'][k] /= len(comp_dict[comp]) # add k_substrate - should all be same av_dens.update({'k_substrate':dens['k_substrate']}) comp_dens.update({comp:av_dens}) return(comp_dens) def align_density_to_substrate(dens, esub): """ helper function to align density histogram including substrate """ # find where substrate is in density profile indm = np.where(dens['hists'][esub] != 0.0)[0] dens['binc'] = dens['binc'][indm[0]:] for k in dens['hists']: dens['hists'][k] = dens['hists'][k][indm[0]:] return(dens)
[ "copy.deepcopy", "numpy.std", "numpy.zeros", "numpy.mean", "numpy.where" ]
[((876, 891), 'copy.deepcopy', 'deepcopy', (['comps'], {}), '(comps)\n', (884, 891), False, 'from copy import deepcopy\n'), ((1781, 1796), 'copy.deepcopy', 'deepcopy', (['comps'], {}), '(comps)\n', (1789, 1796), False, 'from copy import deepcopy\n'), ((4878, 4914), 'numpy.where', 'np.where', (["(dens['hists'][esub] != 0.0)"], {}), "(dens['hists'][esub] != 0.0)\n", (4886, 4914), True, 'import numpy as np\n'), ((1083, 1107), 'numpy.mean', 'np.mean', (['ed[ek][tstart:]'], {}), '(ed[ek][tstart:])\n', (1090, 1107), True, 'import numpy as np\n'), ((1197, 1220), 'numpy.mean', 'np.mean', (['edat[ek][comp]'], {}), '(edat[ek][comp])\n', (1204, 1220), True, 'import numpy as np\n'), ((3947, 3969), 'copy.deepcopy', 'deepcopy', (["dens['binc']"], {}), "(dens['binc'])\n", (3955, 3969), False, 'from copy import deepcopy\n'), ((1246, 1268), 'numpy.std', 'np.std', (['edat[ek][comp]'], {}), '(edat[ek][comp])\n', (1252, 1268), True, 'import numpy as np\n'), ((4180, 4212), 'numpy.zeros', 'np.zeros', (["dens['hists'][k].shape"], {}), "(dens['hists'][k].shape)\n", (4188, 4212), True, 'import numpy as np\n')]
import re import os import glob import shutil import random import logging import torch import numpy as np logger = logging.getLogger(__name__) def _rotate_checkpoints(args, checkpoint_prefix, use_mtime=False): if not args.save_total_limit: return if args.save_total_limit <= 0: return # Check if we should delete older checkpoint(s) glob_checkpoints = glob.glob(os.path.join( args.output_dir, '{}-*'.format(checkpoint_prefix))) if len(glob_checkpoints) <= args.save_total_limit: return ordering_and_checkpoint_path = [] for path in glob_checkpoints: if use_mtime: ordering_and_checkpoint_path.append((os.path.getmtime(path), path)) else: regex_match = re.match( '.*{}-([0-9]+)'.format(checkpoint_prefix), path) if regex_match and regex_match.groups(): ordering_and_checkpoint_path.append( (int(regex_match.groups()[0]), path)) checkpoints_sorted = sorted(ordering_and_checkpoint_path) checkpoints_sorted = [checkpoint[1] for checkpoint in checkpoints_sorted] number_of_checkpoints_to_delete = max( 0, len(checkpoints_sorted) - args.save_total_limit) checkpoints_to_be_deleted = checkpoints_sorted[:number_of_checkpoints_to_delete] for checkpoint in checkpoints_to_be_deleted: logger.info( "Deleting older checkpoint [{}] due to args.save_total_limit".format(checkpoint)) shutil.rmtree(checkpoint) def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(args.seed)
[ "numpy.random.seed", "torch.manual_seed", "torch.cuda.manual_seed_all", "torch.cuda.is_available", "random.seed", "os.path.getmtime", "shutil.rmtree", "logging.getLogger" ]
[((118, 145), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (135, 145), False, 'import logging\n'), ((1551, 1573), 'random.seed', 'random.seed', (['args.seed'], {}), '(args.seed)\n', (1562, 1573), False, 'import random\n'), ((1578, 1603), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (1592, 1603), True, 'import numpy as np\n'), ((1608, 1636), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (1625, 1636), False, 'import torch\n'), ((1644, 1669), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1667, 1669), False, 'import torch\n'), ((1499, 1524), 'shutil.rmtree', 'shutil.rmtree', (['checkpoint'], {}), '(checkpoint)\n', (1512, 1524), False, 'import shutil\n'), ((1679, 1716), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['args.seed'], {}), '(args.seed)\n', (1705, 1716), False, 'import torch\n'), ((688, 710), 'os.path.getmtime', 'os.path.getmtime', (['path'], {}), '(path)\n', (704, 710), False, 'import os\n')]
import numpy as np from numba import jit np.random.seed(1) class rocket_engine(): def __init__(self, dimensions = 3, temperature = 10000, N = 1E5, mass = 1.67e-27, length = 1e-6): self.k = 1.38064852e-23 self.T = temperature self.N = N self.m = mass self.L = length self.dim = dimensions self.sigma = np.sqrt((self.k*self.T)/self.m) self.x = self.position() self.v = self.velocities() def velocities(self): return np.random.normal(0,self.sigma, size=(int(self.N),self.dim)) def position(self): return np.random.uniform(0,self.L, size=(int(self.N),self.dim)) #Calculating the mean velocity @jit(nopython=True) def meanvel(self): self.v_s = 0 for i in range(int(self.N)): self.v_s += np.sqrt(self.v[i,0]**2+self.v[i,1]**2+self.v[i,2]**2) return self.v_s def meankin(self): m = self.m vel = 0 for i in range(int(self.N)): vel += self.v[i,0]**2 + self.v[i,1]**2 + self.v[i,2]**2 return 0.5 * m * vel def test_mean(self): """ making a test function that runs meankin() and meanvel() and checks the computed velocity and kinetic energy and the relative error between them anything below 1% is perfectly acceptable """ m = self.m analytical_mean = 1.5*self.T*self.k computed_mean = 0 for j in self.v: computed_mean += self.meankin() computed_mean = computed_mean/self.N relative_error = abs(analytical_mean - computed_mean)/analytical_mean print("----------Kinetic energy----------") print("{:<20}{:g}".format("Computed mean:", computed_mean)) print("{:<20}{:g}".format("Analytical mean:", analytical_mean)) print("{:<20}{:.2f}%".format("Relative error:", relative_error * 100)) print("-----------------------------") break assert relative_error < 0.002, "the mean kinetic energy is off" print("----------Velocity----------") analytical_vel = np.sqrt(8*self.k*self.T/(np.pi*m)) computed_vel = 0 for i in self.v: computed_vel += self.meanvel() computed_vel = computed_vel/self.N relative_error = abs(analytical_vel - computed_vel)/analytical_vel print("{:<20}{:g}".format("Computed velocity:", computed_vel)) print("{:<20}{:g}".format("Analytical velocity:", analytical_vel)) print("{:<20}{:.2f}%".format("Relative error:", relative_error *100)) print("-----------------------------") break assert relative_error < 0.02, "the mean velocity is off" def box_escape(self, steps = 1e4, t_end = 1e-9, dt = 1e-12): """ Checking how much of the particles actually escape the rocket steps: t_end: dt: """ x, v = self.x,self.v exiting = 0.0 exiting_velocities = 0.0 for t in range(int(t_end/dt)): x += v * dt v_exiting = np.abs(v[:,2]) collision_points = np.logical_or(np.less_equal(x, 0.), np.greater_equal(x, self.L)) x_mask = np.logical_or(np.greater_equal(x[:,0], 0.25*self.L), np.less_equal(x[:,0], 0.75*self.L)) y_mask = np.logical_and(np.greater_equal(x[:,0], 0.25*self.L), np.less_equal(x[:,0], 0.75*self.L)) exit_points = np.logical_and(x_mask, y_mask) exit_points = np.logical_and(np.less_equal(x[:,2], 0), exit_points) exit_indices = np.where(exit_points == True) not_exit_indices = np.where(exit_points == False) v_exiting[not_exit_indices] = 0. exiting_velocities += np.sum(v_exiting) collision_indices = np.where(collision_points == True) exiting += len(exit_indices[0]) s_matrix = np.ones_like(x) s_matrix[collision_indices] = -1 s_matrix[:,2][exit_indices] = 1 r_matrix = np.zeros_like(x) x[:,2][exit_indices] += 0.99*self.L v = np.multiply(v,s_matrix) particle_per_second = exiting_velocities/t_end return exiting_velocities, exiting, particle_per_second if __name__ == "__main__": A = rocket_engine() #result2 = A.box_escape() result3 = A.test_mean()
[ "numpy.less_equal", "numpy.zeros_like", "numpy.abs", "numpy.random.seed", "numpy.logical_and", "numpy.sum", "numpy.ones_like", "numpy.multiply", "numpy.where", "numba.jit", "numpy.greater_equal", "numpy.sqrt" ]
[((43, 60), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (57, 60), True, 'import numpy as np\n'), ((734, 752), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (737, 752), False, 'from numba import jit\n'), ((379, 412), 'numpy.sqrt', 'np.sqrt', (['(self.k * self.T / self.m)'], {}), '(self.k * self.T / self.m)\n', (386, 412), True, 'import numpy as np\n'), ((2227, 2269), 'numpy.sqrt', 'np.sqrt', (['(8 * self.k * self.T / (np.pi * m))'], {}), '(8 * self.k * self.T / (np.pi * m))\n', (2234, 2269), True, 'import numpy as np\n'), ((862, 928), 'numpy.sqrt', 'np.sqrt', (['(self.v[i, 0] ** 2 + self.v[i, 1] ** 2 + self.v[i, 2] ** 2)'], {}), '(self.v[i, 0] ** 2 + self.v[i, 1] ** 2 + self.v[i, 2] ** 2)\n', (869, 928), True, 'import numpy as np\n'), ((3268, 3283), 'numpy.abs', 'np.abs', (['v[:, 2]'], {}), '(v[:, 2])\n', (3274, 3283), True, 'import numpy as np\n'), ((3632, 3662), 'numpy.logical_and', 'np.logical_and', (['x_mask', 'y_mask'], {}), '(x_mask, y_mask)\n', (3646, 3662), True, 'import numpy as np\n'), ((3772, 3801), 'numpy.where', 'np.where', (['(exit_points == True)'], {}), '(exit_points == True)\n', (3780, 3801), True, 'import numpy as np\n'), ((3834, 3864), 'numpy.where', 'np.where', (['(exit_points == False)'], {}), '(exit_points == False)\n', (3842, 3864), True, 'import numpy as np\n'), ((3947, 3964), 'numpy.sum', 'np.sum', (['v_exiting'], {}), '(v_exiting)\n', (3953, 3964), True, 'import numpy as np\n'), ((4000, 4034), 'numpy.where', 'np.where', (['(collision_points == True)'], {}), '(collision_points == True)\n', (4008, 4034), True, 'import numpy as np\n'), ((4104, 4119), 'numpy.ones_like', 'np.ones_like', (['x'], {}), '(x)\n', (4116, 4119), True, 'import numpy as np\n'), ((4236, 4252), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (4249, 4252), True, 'import numpy as np\n'), ((4321, 4345), 'numpy.multiply', 'np.multiply', (['v', 's_matrix'], {}), '(v, s_matrix)\n', (4332, 4345), True, 'import numpy as np\n'), ((3329, 3350), 'numpy.less_equal', 'np.less_equal', (['x', '(0.0)'], {}), '(x, 0.0)\n', (3342, 3350), True, 'import numpy as np\n'), ((3351, 3378), 'numpy.greater_equal', 'np.greater_equal', (['x', 'self.L'], {}), '(x, self.L)\n', (3367, 3378), True, 'import numpy as np\n'), ((3416, 3456), 'numpy.greater_equal', 'np.greater_equal', (['x[:, 0]', '(0.25 * self.L)'], {}), '(x[:, 0], 0.25 * self.L)\n', (3432, 3456), True, 'import numpy as np\n'), ((3455, 3492), 'numpy.less_equal', 'np.less_equal', (['x[:, 0]', '(0.75 * self.L)'], {}), '(x[:, 0], 0.75 * self.L)\n', (3468, 3492), True, 'import numpy as np\n'), ((3528, 3568), 'numpy.greater_equal', 'np.greater_equal', (['x[:, 0]', '(0.25 * self.L)'], {}), '(x[:, 0], 0.25 * self.L)\n', (3544, 3568), True, 'import numpy as np\n'), ((3567, 3604), 'numpy.less_equal', 'np.less_equal', (['x[:, 0]', '(0.75 * self.L)'], {}), '(x[:, 0], 0.75 * self.L)\n', (3580, 3604), True, 'import numpy as np\n'), ((3705, 3730), 'numpy.less_equal', 'np.less_equal', (['x[:, 2]', '(0)'], {}), '(x[:, 2], 0)\n', (3718, 3730), True, 'import numpy as np\n')]
import numpy as np import pickle import sys import seaborn as sns import pandas as pd # import pkg_resources # pkg_resources.require("scanpy==1.3") import scanpy as sc print(sc.__version__) import os import scipy.stats import scipy.sparse import matplotlib.pyplot as plt import sklearn.preprocessing from sklearn.metrics import roc_curve, auc from sklearn.model_selection import train_test_split from sklearn.preprocessing import label_binarize from sklearn.multiclass import OneVsRestClassifier from scipy import interp from sklearn.metrics import roc_auc_score from multiprocessing import Pool from sklearn.preprocessing import binarize import gc def average_for_each_cluster(X, y_cluster): X = pd.DataFrame(X) X.index = y_cluster X.index = X.index.rename('index') mX = X.reset_index().groupby(by='index').mean() return mX.values, mX.index def average_for_each_cluster_less_memory(X, y_cluster): print('Cluster_computation') index = sorted(list(set(y_cluster))) conv_mat = np.array([[1 if i == y else 0 for y in y_cluster] for i in index]) weight = conv_mat.sum(axis=0) print('averaging', conv_mat.shape, X.shape) mX = np.dot(conv_mat, X.reshape((X.shape[0], (X.shape[1] if len(X.shape) == 2 else 1)))) mX = np.array([(mX[i,:]/weight[i]).reshape(-1)[0] for i in range(mX.shape[0])]) mX = np.squeeze(mX) return mX, index def compute_pvalue(gene, answer, pdata, ndata, header): pp, np, pn, nn = sum(pdata), len(pdata)-sum(pdata), sum(ndata), len(ndata)-sum(ndata) assert len(pdata) >= sum(pdata) and len(ndata)-sum(ndata) oddsratio, pvalue = scipy.stats.fisher_exact([[pp, np], [pn, nn]]) return 'pvalue '+header+' '+gene+' '+str(pvalue)+' '+str(oddsratio) def compute_auc(gene, answer, pdata, ndata, header): fpr, tpr, _ = roc_curve(answer, np.concatenate((pdata, ndata), axis=0)) roc_auc = auc(fpr, tpr) del pdata del ndata del fpr del tpr return 'auc '+header+' '+gene+' '+str(roc_auc) def convert_sparse_to_array(mat): if isinstance(mat, np.number): return np.asarray([mat]) if scipy.sparse.issparse(mat): return np.squeeze(np.asarray(mat.todense())) else: return np.squeeze(np.asarray(mat)) def compute_auc_parallel(adata, positive, negative, column, header, cores=4, fisher=False): pdata = adata[adata.obs[column] == positive,:] pool = Pool(processes=cores) if negative is not None: ndata = adata[adata.obs[column] == negative,:] else: ndata = adata[adata.obs[column] != positive,:] ndata = ndata[[((x == x) & ('NA' not in x)) for x in ndata.obs[column]],:] y_true = np.array(([1]*pdata.shape[0])+([0]*ndata.shape[0])) # print(adata.obs[column]) # print(pdata.shape, ndata.shape) # print(adata.shape) # print(adata.var) # print(adata.var.loc[:,'cov']) # print(adata.obs[column]) # print(adata.var.loc[:,'cov'].mean(), adata.var.loc[:,'cov'].max(), adata.var.loc[:,'cov'].median()) if 'cov' in adata.var.columns: genes = [gene for gene in adata.var.index if adata.var.loc[gene,'cov'] > 5] else: genes = [gene for gene in adata.var.index] step = 500 # print(len(genes)) with open(header, 'w') as f: for start in range(0, len(genes), step): tgenes = genes[start:min(len(genes), start+step)] print('#', start, len(tgenes)) if cores > 1: if fisher: results = pool.starmap(compute_auc, [(gene, y_true, convert_sparse_to_array(pdata[:,gene].X), convert_sparse_to_array(ndata[:,gene].X), header) for gene in tgenes]) else: results = pool.starmap(compute_pvalue, [(gene, y_true, convert_sparse_to_array(pdata[:,gene].X), convert_sparse_to_array(ndata[:,gene].X), header) for gene in tgenes]) else: if fisher: results = [compute_pvalue(gene, y_true, convert_sparse_to_array(pdata[:,gene].X), convert_sparse_to_array(ndata[:,gene].X), header) for gene in tgenes] else: results = [compute_auc(gene, y_true, convert_sparse_to_array(pdata[:,gene].X), convert_sparse_to_array(ndata[:,gene].X), header) for gene in tgenes] gc.collect() count = 0 for res in results: f.write(res+'\n') count += 1 assert count == step or count == len(genes)-start pool.close() pool.join() del pool del ndata, pdata def reset_celltype(adata): def get_celltype(celltype): if celltype == celltype: if celltype in ['IN', 'EX']: return celltype else: return 'NN' else: return 'NA' df = pd.read_csv('/data/rkawaguc/data/191003_BICCN_sf_marker_more/cluster_annotation/GSE111586_icluster_celltype_annotation_curated.csv') print(df) celltype_labels = adata.obs.cluster celltype_dict = dict([(row['cluster'], get_celltype(row['celltype'])) for i, row in df.iterrows()]) adata.obs.loc[:,'celltype'] = [celltype_dict[x] for x in celltype_labels] return adata def convert_celltype_labels_to_target(cluster, celltype_labels): if cluster in ['cluster', 'celltype']: return celltype_labels elif cluster == 'neuron': dict = {'EX':'P', 'IN':'P', 'NN':'N', 'NA':'NA'} return [dict[x] if x in dict else x for x in celltype_labels] elif cluster == 'inex': dict = {'EX':'EX', 'IN':'IN', 'NN':'NA'} return [dict[x] if x in dict else x for x in celltype_labels] def convert_to_raw_celltype(X): celltype_without_num = [x.split('_')[-1] if x == x else x for x in X] celltype_without_var = [x if x in ['IN', 'EX'] else 'NA' if x != x or x in ['NA', 'Mis'] else 'NN' for x in celltype_without_num] return celltype_without_var def set_celltyppe_for_all_problems(cdata, gse, curration=False): cdata.obs['celltype'] = convert_to_raw_celltype(cdata.obs['celltype'].values) if gse == 'GSE111' and GSE111_NEWANN: cdata = reset_celltype(cdata) cdata.obs['neuron'] = convert_celltype_labels_to_target('neuron', cdata.obs['celltype']) cdata.obs['inex'] = convert_celltype_labels_to_target('inex', cdata.obs['celltype']) print(cdata.obs) return cdata def initialize_argument(argv): celltype_list = ['celltype', 'neuron', 'inex'] cell_list = ['EX', 'IN', 'NN'] CLUSTER, PEAK, PVALUE = False, False, False gse_set = None if len(argv) >= 2: gse_set = argv[1] if len(argv) >= 3: if argv[2] == 'cell': pass elif argv[2] == 'cluster': CLUSTER = True elif argv[2] == 'peak': PEAK = True elif argv[2] == 'pvalue': PEAK, PVALUE = True, True if len(argv) >= 4: if argv[3] in ['IN', 'EX', 'NN']: celltype_list = ['celltype'] cell_list = [argv[3]] else: celltype_list = [argv[3]] return gse_set, PEAK, CLUSTER, PVALUE, celltype_list, cell_list dir = "output/scobj/" cluster_annotation = ["GSE111586_icluster_celltype_annotation.csv", "GSE123576_cluster_celltype_annotation.csv", "GSE126074_icluster_celltype_annotation.csv", "GSE127257_cluster_celltype_annotation.csv", "BICCN2_cluster_celltype_annotation.csv", "GSE1303990_cluster_celltype_annotation.csv"] clust_dir = "/data/rkawaguc/data/191003_BICCN_sf_marker_more/cluster_annotation/" cores = 1 GSE111_CORTEX = False GSE111_NEWANN = False gses = ['GSE111', 'GSE123', 'GSE126', 'GSE127', 'BICCN2', 'GSE130'] scobjs = ["GSE111586_"+('cortex' if GSE111_CORTEX else 'gene')+"_id_order_gene__all_scanpy_obj.pyn", "GSE123576_gene_id_order_gene__all_scanpy_obj.pyn", "GSE126074_gene_id_order_gene__all_scanpy_obj.pyn", "GSE127257_distal_id_gene_order__all_scanpy_obj.pyn", "BICCN2_gene_id_order_gene__all_scanpy_obj.pyn", "GSE1303990_gene_id_order_gene__all_scanpy_obj.pyn"] gse_set, PEAK, CLUSTER, PVALUE, celltype_list, cell_list = initialize_argument(sys.argv) if PEAK: scobj_dict = {'GSE111':'GSE111586', 'GSE123':'GSE123576', 'GSE126':'GSE126074', 'GSE130':'GSE1303990', 'BICCN2':'BICCN2'} for gse, scobj in zip(gses, scobjs): if gse_set is not None and gse != gse_set: continue if CLUSTER: # cluster-level analysis with open(os.path.join("output/scobj/", scobj), "rb") as f: print(scobj) anndata=pickle.load(f) mX, index = average_for_each_cluster_less_memory(anndata.X.todense(), anndata.obs['Ident'] if 'Ident' in anndata.obs.columns and gse != 'GSE130' else anndata.obs['cluster']) print(anndata.obs.loc[:,['cluster', 'Ident']]) cluster_annotation_list = pd.read_csv(os.path.join(clust_dir, cluster_annotation[gses.index(gse)]), index_col=0) clust_cell = [cluster_annotation_list.loc[x,:][0] for x in index] print(len(clust_cell), mX.shape) obs = pd.DataFrame([index, clust_cell], index=['cluster', 'celltype']).transpose() cdata = sc.AnnData(mX, obs) cdata.var = anndata.var cdata = set_celltype_for_all_problems(cdata, gse, GSE111_NEWANN) for ann in celltype_list: if ann == 'celltype': for x in cdata.obs['celltype'].unique(): if x != x or 'NA' in x: continue if x not in cell_list: continue positive, negative = x, None compute_auc_parallel(cdata, positive, negative, ann, gse+'_'+ann+'_'+str(x)+'_cluster', cores) else: if ann == 'neuron': positive, negative = 'P', 'N' else: positive, negative = 'IN', 'EX' compute_auc_parallel(cdata, positive, negative, ann, gse+'_'+ann+'_cluster', cores) else: # cell-level analysis if PEAK and gse == 'GSE127': continue peak_scobj = scobj_dict[gse]+'_'+('cortex' if gse == 'GSE111' and GSE111_CORTEX else 'gene')+'_global_index_5000__all_scanpy_obj.pyn' with open(os.path.join("output/scobj/", peak_scobj), "rb") as f: print(peak_scobj) anndata=pickle.load(f) if PEAK: anndata.X = binarize(anndata.X, threshold=1).astype(int) anndata = anndata[:,anndata.var.index[~pd.isnull(anndata.var.loc[:,'chr'])]] anndata.var.index = [str(row['chr'])+'_'+str(int(np.round(row['start'])))+'_'+str(int(np.round(row['end']))) for i, row in anndata.var.iterrows()] anndata = set_celltype_for_all_problems(anndata, gse, GSE111_NEWANN) tail = ('_peak' if PEAK else '') for ann in celltype_list: if ann == 'celltype': for x in anndata.obs['celltype'].unique(): if x != x or 'NA' in x: continue if x not in cell_list: continue positive, negative = x, None compute_auc_parallel(anndata, positive, negative, ann, gse+'_'+ann+'_'+str(x)+tail, cores, fisher=(PEAK and PVALUE)) else: if ann == 'neuron': positive, negative = 'P', 'N' else: positive, negative = 'IN', 'EX' compute_auc_parallel(anndata, positive, negative, ann, gse+'_'+ann+tail, cores, fisher=(PEAK and PVALUE))
[ "pandas.DataFrame", "scanpy.AnnData", "sklearn.preprocessing.binarize", "pandas.read_csv", "numpy.asarray", "pandas.isnull", "sklearn.metrics.auc", "gc.collect", "pickle.load", "numpy.array", "multiprocessing.Pool", "numpy.squeeze", "numpy.round", "os.path.join", "numpy.concatenate" ]
[((703, 718), 'pandas.DataFrame', 'pd.DataFrame', (['X'], {}), '(X)\n', (715, 718), True, 'import pandas as pd\n'), ((1010, 1078), 'numpy.array', 'np.array', (['[[(1 if i == y else 0) for y in y_cluster] for i in index]'], {}), '([[(1 if i == y else 0) for y in y_cluster] for i in index])\n', (1018, 1078), True, 'import numpy as np\n'), ((1345, 1359), 'numpy.squeeze', 'np.squeeze', (['mX'], {}), '(mX)\n', (1355, 1359), True, 'import numpy as np\n'), ((1877, 1890), 'sklearn.metrics.auc', 'auc', (['fpr', 'tpr'], {}), '(fpr, tpr)\n', (1880, 1890), False, 'from sklearn.metrics import roc_curve, auc\n'), ((2393, 2414), 'multiprocessing.Pool', 'Pool', ([], {'processes': 'cores'}), '(processes=cores)\n', (2397, 2414), False, 'from multiprocessing import Pool\n'), ((2660, 2713), 'numpy.array', 'np.array', (['([1] * pdata.shape[0] + [0] * ndata.shape[0])'], {}), '([1] * pdata.shape[0] + [0] * ndata.shape[0])\n', (2668, 2713), True, 'import numpy as np\n'), ((4766, 4908), 'pandas.read_csv', 'pd.read_csv', (['"""/data/rkawaguc/data/191003_BICCN_sf_marker_more/cluster_annotation/GSE111586_icluster_celltype_annotation_curated.csv"""'], {}), "(\n '/data/rkawaguc/data/191003_BICCN_sf_marker_more/cluster_annotation/GSE111586_icluster_celltype_annotation_curated.csv'\n )\n", (4777, 4908), True, 'import pandas as pd\n'), ((1823, 1861), 'numpy.concatenate', 'np.concatenate', (['(pdata, ndata)'], {'axis': '(0)'}), '((pdata, ndata), axis=0)\n', (1837, 1861), True, 'import numpy as np\n'), ((2079, 2096), 'numpy.asarray', 'np.asarray', (['[mat]'], {}), '([mat])\n', (2089, 2096), True, 'import numpy as np\n'), ((9112, 9131), 'scanpy.AnnData', 'sc.AnnData', (['mX', 'obs'], {}), '(mX, obs)\n', (9122, 9131), True, 'import scanpy as sc\n'), ((2221, 2236), 'numpy.asarray', 'np.asarray', (['mat'], {}), '(mat)\n', (2231, 2236), True, 'import numpy as np\n'), ((8517, 8531), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (8528, 8531), False, 'import pickle\n'), ((10264, 10278), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (10275, 10278), False, 'import pickle\n'), ((4280, 4292), 'gc.collect', 'gc.collect', ([], {}), '()\n', (4290, 4292), False, 'import gc\n'), ((8422, 8458), 'os.path.join', 'os.path.join', (['"""output/scobj/"""', 'scobj'], {}), "('output/scobj/', scobj)\n", (8434, 8458), False, 'import os\n'), ((9019, 9083), 'pandas.DataFrame', 'pd.DataFrame', (['[index, clust_cell]'], {'index': "['cluster', 'celltype']"}), "([index, clust_cell], index=['cluster', 'celltype'])\n", (9031, 9083), True, 'import pandas as pd\n'), ((10159, 10200), 'os.path.join', 'os.path.join', (['"""output/scobj/"""', 'peak_scobj'], {}), "('output/scobj/', peak_scobj)\n", (10171, 10200), False, 'import os\n'), ((10320, 10352), 'sklearn.preprocessing.binarize', 'binarize', (['anndata.X'], {'threshold': '(1)'}), '(anndata.X, threshold=1)\n', (10328, 10352), False, 'from sklearn.preprocessing import binarize\n'), ((10416, 10452), 'pandas.isnull', 'pd.isnull', (["anndata.var.loc[:, 'chr']"], {}), "(anndata.var.loc[:, 'chr'])\n", (10425, 10452), True, 'import pandas as pd\n'), ((10552, 10572), 'numpy.round', 'np.round', (["row['end']"], {}), "(row['end'])\n", (10560, 10572), True, 'import numpy as np\n'), ((10515, 10537), 'numpy.round', 'np.round', (["row['start']"], {}), "(row['start'])\n", (10523, 10537), True, 'import numpy as np\n')]
"""Tests for the log_normal_distribution module""" # Copyright 2019 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import unittest from ..log_normal_distribution import LogNormalDistribution from .assertions import assert_close class TestLogNormalDistribution(unittest.TestCase): """Tests for the LogNormalDistribution class""" def setUp(self): np.seterr(all="raise") self.assert_close = assert_close.__get__(self, self.__class__) def test_get_derivatives_var_1(self): """Test LogNormalDistribution(mu, 1).get_derivatives()""" mu = np.array([0.0, 1.0, 2.0]) x = np.array([1.0, 1.0, 1.0]) dist = LogNormalDistribution(mu, 1.0) d1, d2 = dist.get_derivatives(x) self.assert_close([0.0, 1.0, 2.0], d1, "d1") self.assert_close([-1.0, -1.0, -1.0], d2, "d2") def test_get_derivatives_var_2(self): """Test LogNormalDistribution(0, 2).get_derivatives()""" x = np.exp([0.0, 1.0, 2.0]) dist = LogNormalDistribution(0.0, 2.0) d1, d2 = dist.get_derivatives(x) self.assert_close([0.0, -0.5, -1.0], d1, "d1") self.assert_close([-0.5, -0.5, -0.5], d2, "d2")
[ "numpy.seterr", "numpy.array", "numpy.exp" ]
[((891, 913), 'numpy.seterr', 'np.seterr', ([], {'all': '"""raise"""'}), "(all='raise')\n", (900, 913), True, 'import numpy as np\n'), ((1107, 1132), 'numpy.array', 'np.array', (['[0.0, 1.0, 2.0]'], {}), '([0.0, 1.0, 2.0])\n', (1115, 1132), True, 'import numpy as np\n'), ((1145, 1170), 'numpy.array', 'np.array', (['[1.0, 1.0, 1.0]'], {}), '([1.0, 1.0, 1.0])\n', (1153, 1170), True, 'import numpy as np\n'), ((1487, 1510), 'numpy.exp', 'np.exp', (['[0.0, 1.0, 2.0]'], {}), '([0.0, 1.0, 2.0])\n', (1493, 1510), True, 'import numpy as np\n')]
import os, fnmatch, sys import dill as pickle import scipy.interpolate as interp import numpy as np import matplotlib.pyplot as plt import matplotlib.mlab as mlab import bead_util as bu import configuration as config dir1 = '/data/20180618/bead1/tf_20180618/freq_comb_elec5_10V' dir1 = '/data/20180618/bead1/discharge/fine3/' dir1 = '/data/20180625/bead1/grav_data/shield/X50-75um_Z15-25um_17Hz' dir1 = '/data/20180625/bead1/tf_20180625/freq_comb_elec3' files = bu.find_all_fnames(dir1) for file in files: df = bu.DataFile() df.load(file) freqs = np.fft.rfftfreq(len(df.amp[0]), d=1.0/df.fsamp) plt.figure(1) plt.loglog(freqs, np.abs(np.fft.rfft(df.pos_data_3[0])) * 1000, label='offline X') plt.loglog(freqs, np.abs(np.fft.rfft(df.pos_data_2[0])) * 1000, label='FPGA X2') plt.loglog(freqs, np.abs(np.fft.rfft(df.pos_data[0])), label='FPGA X1') plt.xlabel('Frequency [Hz]') plt.ylabel('sqrt(PSD) [arb]') plt.legend() plt.figure(4) plt.loglog(freqs, np.abs(np.fft.rfft(df.electrode_data[3]))) plt.xlabel('Frequency [Hz]') plt.ylabel('sqrt(PSD) [arb]') fig, axarr = plt.subplots(2,1,sharex=True,sharey=False) fig2, axarr2 = plt.subplots(2,1,sharex=True,sharey=False) for quad in [0,1,2,3]: print(type(df.amp[quad])) fft = np.fft.rfft(df.amp[quad]) fft2 = np.fft.rfft(df.phase[quad]) #plt.figure(2) axarr[0].plot(df.amp[quad]) #plt.figure(3) axarr2[0].loglog(freqs, np.abs(fft), label='Quadrant ' + str(quad)) #plt.figure(5) axarr[1].plot(df.phase[quad]) #plt.figure(6) axarr2[1].loglog(freqs, np.abs(fft2), label='Quadrant ' + str(quad)) plt.legend() plt.figure(3) plt.xlabel('Frequency [Hz]') plt.ylabel('sqrt(PSD) [arb]') plt.show()
[ "numpy.fft.rfft", "matplotlib.pyplot.show", "numpy.abs", "matplotlib.pyplot.legend", "bead_util.find_all_fnames", "matplotlib.pyplot.figure", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.subplots", "bead_util.DataFile" ]
[((470, 494), 'bead_util.find_all_fnames', 'bu.find_all_fnames', (['dir1'], {}), '(dir1)\n', (488, 494), True, 'import bead_util as bu\n'), ((524, 537), 'bead_util.DataFile', 'bu.DataFile', ([], {}), '()\n', (535, 537), True, 'import bead_util as bu\n'), ((622, 635), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (632, 635), True, 'import matplotlib.pyplot as plt\n'), ((888, 916), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Frequency [Hz]"""'], {}), "('Frequency [Hz]')\n", (898, 916), True, 'import matplotlib.pyplot as plt\n'), ((921, 950), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""sqrt(PSD) [arb]"""'], {}), "('sqrt(PSD) [arb]')\n", (931, 950), True, 'import matplotlib.pyplot as plt\n'), ((955, 967), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (965, 967), True, 'import matplotlib.pyplot as plt\n'), ((973, 986), 'matplotlib.pyplot.figure', 'plt.figure', (['(4)'], {}), '(4)\n', (983, 986), True, 'import matplotlib.pyplot as plt\n'), ((1056, 1084), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Frequency [Hz]"""'], {}), "('Frequency [Hz]')\n", (1066, 1084), True, 'import matplotlib.pyplot as plt\n'), ((1089, 1118), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""sqrt(PSD) [arb]"""'], {}), "('sqrt(PSD) [arb]')\n", (1099, 1118), True, 'import matplotlib.pyplot as plt\n'), ((1137, 1182), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {'sharex': '(True)', 'sharey': '(False)'}), '(2, 1, sharex=True, sharey=False)\n', (1149, 1182), True, 'import matplotlib.pyplot as plt\n'), ((1199, 1244), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {'sharex': '(True)', 'sharey': '(False)'}), '(2, 1, sharex=True, sharey=False)\n', (1211, 1244), True, 'import matplotlib.pyplot as plt\n'), ((1717, 1729), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1727, 1729), True, 'import matplotlib.pyplot as plt\n'), ((1735, 1748), 'matplotlib.pyplot.figure', 'plt.figure', (['(3)'], {}), '(3)\n', (1745, 1748), True, 'import matplotlib.pyplot as plt\n'), ((1753, 1781), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Frequency [Hz]"""'], {}), "('Frequency [Hz]')\n", (1763, 1781), True, 'import matplotlib.pyplot as plt\n'), ((1786, 1815), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""sqrt(PSD) [arb]"""'], {}), "('sqrt(PSD) [arb]')\n", (1796, 1815), True, 'import matplotlib.pyplot as plt\n'), ((1821, 1831), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1829, 1831), True, 'import matplotlib.pyplot as plt\n'), ((1322, 1347), 'numpy.fft.rfft', 'np.fft.rfft', (['df.amp[quad]'], {}), '(df.amp[quad])\n', (1333, 1347), True, 'import numpy as np\n'), ((1363, 1390), 'numpy.fft.rfft', 'np.fft.rfft', (['df.phase[quad]'], {}), '(df.phase[quad])\n', (1374, 1390), True, 'import numpy as np\n'), ((837, 864), 'numpy.fft.rfft', 'np.fft.rfft', (['df.pos_data[0]'], {}), '(df.pos_data[0])\n', (848, 864), True, 'import numpy as np\n'), ((1016, 1049), 'numpy.fft.rfft', 'np.fft.rfft', (['df.electrode_data[3]'], {}), '(df.electrode_data[3])\n', (1027, 1049), True, 'import numpy as np\n'), ((1506, 1517), 'numpy.abs', 'np.abs', (['fft'], {}), '(fft)\n', (1512, 1517), True, 'import numpy as np\n'), ((1667, 1679), 'numpy.abs', 'np.abs', (['fft2'], {}), '(fft2)\n', (1673, 1679), True, 'import numpy as np\n'), ((665, 694), 'numpy.fft.rfft', 'np.fft.rfft', (['df.pos_data_3[0]'], {}), '(df.pos_data_3[0])\n', (676, 694), True, 'import numpy as np\n'), ((752, 781), 'numpy.fft.rfft', 'np.fft.rfft', (['df.pos_data_2[0]'], {}), '(df.pos_data_2[0])\n', (763, 781), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- u""" :copyright: Copyright (c) 2020 RadiaSoft LLC. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function import time import os import yaml import numpy as np def record_time(func, time_list, *args, **kwargs): t1 = time.time() func(*args, **kwargs) t2 = time.time() time_list.append(t2 - t1) class SteadyState: def __init__(self, top, cond, interval, tol=0.1): # Analyze if we are in steady-state regime by means of FFT. # Use estimated crossing time as the interval period and then look at self.top = top self.cond = cond self.tol = tol self.n = 0 self.level = 1 tstart = (self.top.it - interval) * self.top.dt _, collector_current = cond.get_current_history(js=None, l_lost=1, l_emit=0, l_image=0, tmin=tstart, tmax=None, nt=top.it) self.y0 = np.abs(np.fft.rfft(collector_current)[1]) def __call__(self, interval): tstart = (self.top.it - interval) * self.top.dt _, collector_current = self.cond.get_current_history(js=None, l_lost=1, l_emit=0, l_image=0, tmin=tstart, tmax=None, nt=interval) y = np.abs(np.fft.rfft(collector_current)[1]) self.level = y / self.y0 if self.level <= self.tol: return 1 else: return -1 class ExternalCircuit: def __init__(self, top, solver, rho, contact_potential, area, conductors, voltage_stride=20, debug=False): self.top = top self.solver = solver self.rho = rho self.contact_potential = contact_potential self.area = area # in cm**2 self.voltage_stride = voltage_stride self.debug = debug # TODO: these seem to remain empty when running warp in parallel self.voltage_history = [] self.current_history = [] try: conductors[0] self.conductors = conductors except TypeError: self.conductors = [conductors] def getvolt(self, t): # t is dummy variable if self.top.it % self.voltage_stride == 0: # This will tell the solver to update voltage on all conductors self.solver.gridmode = 0 tmin = (self.top.it - self.voltage_stride) * self.top.dt for cond in self.conductors: times, current = cond.get_current_history(js=None, l_lost=1, l_emit=0, l_image=0, tmin=tmin, tmax=None, nt=1) # Using many bins for the current sometimes gives erroneous zeros. # Using a single bin has consistently given a result ~1/2 expected current, hence the sum of the two values current = np.sum(current) voltage = self.contact_potential + current / self.area * self.rho self.voltage_history.append(voltage) self.current_history.append(current / self.area) if self.debug: print("Current/voltage at step: {} = {}, {}".format(self.top.it, current / self.area, voltage)) return voltage def write_parameter_file(pars, filename=None): path, filename = os.path.split(filename) if not filename: try: filename = 'run_attributes_{}.yaml'.format(pars['run_id'], pars['run_id']) except KeyError: print("No Filename or run_id, attributes will not be saved") return if path: filename = os.path.join(path, filename) else: if os.path.splitext(filename)[-1] != '.yaml': filename = os.path.splitext(filename)[0] + '.yaml' if path: filename = os.path.join(path, filename) else: filename = os.path.join(path, filename) tec_keys = ['x_struts', 'y_struts', 'V_grid', 'grid_height', 'strut_width', 'strut_height', 'rho_ew', 'T_em', 'phi_em', 'T_coll', 'phi_coll', 'rho_cw', 'gap_distance', 'rho_load', 'run_id'] simulation_keys = ['injection_type', 'random_seed', 'install_grid', 'install_circuit', 'max_wall_time', 'particle_diagnostic_switch', 'field_diagnostic_switch', 'lost_diagnostic_switch', 'channel_width'] tec_parameters = {} simulation_parameters = {} other_parameters = {} for key in pars: if key in tec_keys: tec_parameters[key] = pars[key] elif key in simulation_keys: simulation_parameters[key] = pars[key] else: other_parameters[key] = pars[key] pars = {'tec': tec_parameters, 'simulation': simulation_parameters, 'other': other_parameters} with open(filename, 'w') as outputfile: yaml.dump(pars, outputfile, default_flow_style=False) def read_parameter_file(filename): parameters = yaml.safe_load(open(filename, 'r')) input_deck = {} for key0 in parameters: for key1, val in parameters[key0].items(): input_deck[key1] = val return input_deck
[ "numpy.fft.rfft", "numpy.sum", "yaml.dump", "time.time", "os.path.splitext", "os.path.split", "os.path.join" ]
[((340, 351), 'time.time', 'time.time', ([], {}), '()\n', (349, 351), False, 'import time\n'), ((387, 398), 'time.time', 'time.time', ([], {}), '()\n', (396, 398), False, 'import time\n'), ((3357, 3380), 'os.path.split', 'os.path.split', (['filename'], {}), '(filename)\n', (3370, 3380), False, 'import os\n'), ((4885, 4938), 'yaml.dump', 'yaml.dump', (['pars', 'outputfile'], {'default_flow_style': '(False)'}), '(pars, outputfile, default_flow_style=False)\n', (4894, 4938), False, 'import yaml\n'), ((2919, 2934), 'numpy.sum', 'np.sum', (['current'], {}), '(current)\n', (2925, 2934), True, 'import numpy as np\n'), ((3659, 3687), 'os.path.join', 'os.path.join', (['path', 'filename'], {}), '(path, filename)\n', (3671, 3687), False, 'import os\n'), ((3855, 3883), 'os.path.join', 'os.path.join', (['path', 'filename'], {}), '(path, filename)\n', (3867, 3883), False, 'import os\n'), ((3921, 3949), 'os.path.join', 'os.path.join', (['path', 'filename'], {}), '(path, filename)\n', (3933, 3949), False, 'import os\n'), ((1032, 1062), 'numpy.fft.rfft', 'np.fft.rfft', (['collector_current'], {}), '(collector_current)\n', (1043, 1062), True, 'import numpy as np\n'), ((1376, 1406), 'numpy.fft.rfft', 'np.fft.rfft', (['collector_current'], {}), '(collector_current)\n', (1387, 1406), True, 'import numpy as np\n'), ((3709, 3735), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (3725, 3735), False, 'import os\n'), ((3775, 3801), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (3791, 3801), False, 'import os\n')]
import numpy as np from abc import ABCMeta, abstractmethod from ratcave.utils.observers import IterObservable import itertools from operator import setitem from scipy.spatial.transform import Rotation as R class Coordinates(IterObservable): coords = {'x': 0, 'y': 1, 'z': 2} def __init__(self, *args, **kwargs): " Returns a Coordinates object" super(Coordinates, self).__init__(**kwargs) self._array = np.array(args, dtype=np.float32) self._init_coord_properties() def __repr__(self): arg_str = ', '.join(['{}={}'.format(*el) for el in zip('xyz', self._array)]) return "{cls}({coords})".format(cls=self.__class__.__name__, coords=arg_str) def _init_coord_properties(self): """ Generates combinations of named coordinate values, mapping them to the internal array. For Example: x, xy, xyz, y, yy, zyx, etc """ def gen_getter_setter_funs(*args): indices = [self.coords[coord] for coord in args] def getter(self): return tuple(self._array[indices]) if len(args) > 1 else self._array[indices[0]] def setter(self, value): setitem(self._array, indices, value) self.notify_observers() return getter, setter for n_repeats in range(1, len(self.coords)+1): for args in itertools.product(self.coords.keys(), repeat=n_repeats): getter, setter = gen_getter_setter_funs(*args) setattr(self.__class__, ''.join(args), property(fget=getter, fset=setter)) def __getitem__(self, item): if type(item) == slice: return tuple(self._array[item]) else: return self._array[item] def __setitem__(self, idx, value): self._array[idx] = value super(Coordinates, self).__setitem__(idx, value) class RotationBase(object): __metaclass__ = ABCMeta @abstractmethod def to_quaternion(self): pass @abstractmethod def to_euler(self, units='rad'): pass @abstractmethod def to_matrix(self): pass @classmethod def from_matrix(cls, matrix): pass def rotate(self, vector): """Takes a vector and returns it rotated by self.""" return np.dot(self.to_matrix()[:3, :3], vector).flatten() class RotationEuler(RotationBase, Coordinates): def __init__(self, x, y, z, axes='rxyz', **kwargs): super(RotationEuler, self).__init__(x, y, z, **kwargs) self.axes = axes class RotationEulerRadians(RotationEuler): def to_radians(self): return self def to_degrees(self): return RotationEulerDegrees(*np.degrees(self._array), axes=self.axes) def to_quaternion(self): return RotationQuaternion(*R.from_euler(self._axes[1:],self._array,degrees=False).as_quat()) def to_matrix(self): mat = np.eye(4) mat[:3, :3] = R.from_euler(self.axes[1:],self._array,degrees=False).as_dcm() # scipy as_matrix() not available return mat def to_euler(self, units='rad'): assert units.lower() in ['rad', 'deg'] if units.lower() == 'rad': return RotationEulerRadians(*self._array, axes=self.axes) else: return RotationEulerDegrees(*np.degrees(self._array), axes=self.axes) @classmethod def from_matrix(cls, matrix, axes='rxyz'): coords = R.from_matrix(matrix[:3, :3]).as_euler(axes[1:], degrees=False) return cls(*coords) class RotationEulerDegrees(RotationEuler): def to_radians(self): return RotationEulerRadians(*np.radians(self._array), axes=self.axes) def to_degrees(self): return self def to_quaternion(self): return self.to_radians().to_quaternion() def to_euler(self, units='rad'): return self.to_radians().to_euler(units=units) def to_matrix(self): return self.to_radians().to_matrix() @classmethod def from_matrix(cls, matrix, axes='rxyz'): coords = R.from_matrix(matrix[:3, :3]).as_euler(axes[1:], degrees=True) return cls(*coords) class RotationQuaternion(RotationBase, Coordinates): coords = {'w': 0, 'x': 1, 'y': 2, 'z': 3} def __init__(self, w, x, y, z, **kwargs): super(RotationQuaternion, self).__init__(w, x, y, z) def __repr__(self): arg_str = ', '.join(['{}={}'.format(*el) for el in zip('wxyz', self._array)]) return "{cls}({coords})".format(cls=self.__class__.__name__, coords=arg_str) def to_quaternion(self): return self def to_matrix(self): mat = np.eye(4, 4) mat[:3, :3] = R.from_quat(self).as_matrix() return mat def to_euler(self, units='rad'): euler_data = R.from_quat(self).as_euler(axes='xyz',degrees=False) assert units.lower() in ['rad', 'deg'] if units.lower() == 'rad': return RotationEulerRadians(*euler_data) else: return RotationEulerDegrees(*np.degrees(euler_data)) @classmethod def from_matrix(cls, matrix): return cls(*R.from_matrix(matrix[:3, :3]).as_quat()) class Translation(Coordinates): def __init__(self, *args, **kwargs): assert len(args) == 3, "Must be xyz coordinates" super(Translation, self).__init__(*args, **kwargs) def __add__(self, other): oth = other.xyz if isinstance(other, Translation) else other if len(oth) != 3: raise ValueError("Other must have length of 3") return Translation(*tuple(a + b for (a, b) in zip(self.xyz, oth))) def __sub__(self, other): oth = other.xyz if isinstance(other, Translation) else other if len(oth) != 3: raise ValueError("Other must have length of 3") return Translation(*tuple(a - b for (a, b) in zip(self.xyz, other.xyz))) def to_matrix(self): mat = np.eye(4,4) mat[:3,3] = self._array return mat @classmethod def from_matrix(cls, matrix): """Returns a Translation from a 4x4 model matrix (the first three rows of the last column).""" return cls(*matrix[:3, 3]) class Scale(Coordinates): def __init__(self, *args, **kwargs): vals = args * 3 if len(args) == 1 else args assert len(vals) == 3, "Must be xyz coordinates" super(self.__class__, self).__init__(*vals, **kwargs) def to_matrix(self): return np.diag((self._array[0], self._array[1], self._array[2], 1.)) @classmethod def from_matrix(cls, matrix): return cls(*np.linalg.norm(matrix[:3, :3], axis=0)) def cross_product_matrix(vec): """Returns a 3x3 cross-product matrix from a 3-element vector.""" return np.array([[0, -vec[2], vec[1]], [vec[2], 0, -vec[0]], [-vec[1], vec[0], 0]]) def rotation_matrix_between_vectors(from_vec, to_vec): """ Returns a rotation matrix to rotate from 3d vector "from_vec" to 3d vector "to_vec". Equation from https://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d """ a, b = (vec/np.linalg.norm(vec) for vec in (from_vec, to_vec)) v = np.cross(a, b) cos = np.dot(a, b) if cos == -1.: raise ValueError("Orientation in complete opposite direction") v_cpm = cross_product_matrix(v) rot_mat = np.identity(3) + v_cpm + np.dot(v_cpm, v_cpm) * (1. / 1. + cos) return rot_mat
[ "numpy.radians", "numpy.eye", "numpy.degrees", "scipy.spatial.transform.Rotation.from_euler", "numpy.cross", "numpy.identity", "numpy.array", "numpy.linalg.norm", "scipy.spatial.transform.Rotation.from_matrix", "scipy.spatial.transform.Rotation.from_quat", "numpy.dot", "operator.setitem", "numpy.diag" ]
[((6717, 6793), 'numpy.array', 'np.array', (['[[0, -vec[2], vec[1]], [vec[2], 0, -vec[0]], [-vec[1], vec[0], 0]]'], {}), '([[0, -vec[2], vec[1]], [vec[2], 0, -vec[0]], [-vec[1], vec[0], 0]])\n', (6725, 6793), True, 'import numpy as np\n'), ((7202, 7216), 'numpy.cross', 'np.cross', (['a', 'b'], {}), '(a, b)\n', (7210, 7216), True, 'import numpy as np\n'), ((7227, 7239), 'numpy.dot', 'np.dot', (['a', 'b'], {}), '(a, b)\n', (7233, 7239), True, 'import numpy as np\n'), ((437, 469), 'numpy.array', 'np.array', (['args'], {'dtype': 'np.float32'}), '(args, dtype=np.float32)\n', (445, 469), True, 'import numpy as np\n'), ((2895, 2904), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (2901, 2904), True, 'import numpy as np\n'), ((4611, 4623), 'numpy.eye', 'np.eye', (['(4)', '(4)'], {}), '(4, 4)\n', (4617, 4623), True, 'import numpy as np\n'), ((5893, 5905), 'numpy.eye', 'np.eye', (['(4)', '(4)'], {}), '(4, 4)\n', (5899, 5905), True, 'import numpy as np\n'), ((6428, 6490), 'numpy.diag', 'np.diag', (['(self._array[0], self._array[1], self._array[2], 1.0)'], {}), '((self._array[0], self._array[1], self._array[2], 1.0))\n', (6435, 6490), True, 'import numpy as np\n'), ((7142, 7161), 'numpy.linalg.norm', 'np.linalg.norm', (['vec'], {}), '(vec)\n', (7156, 7161), True, 'import numpy as np\n'), ((7380, 7394), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\n', (7391, 7394), True, 'import numpy as np\n'), ((7405, 7425), 'numpy.dot', 'np.dot', (['v_cpm', 'v_cpm'], {}), '(v_cpm, v_cpm)\n', (7411, 7425), True, 'import numpy as np\n'), ((1196, 1232), 'operator.setitem', 'setitem', (['self._array', 'indices', 'value'], {}), '(self._array, indices, value)\n', (1203, 1232), False, 'from operator import setitem\n'), ((2683, 2706), 'numpy.degrees', 'np.degrees', (['self._array'], {}), '(self._array)\n', (2693, 2706), True, 'import numpy as np\n'), ((2927, 2982), 'scipy.spatial.transform.Rotation.from_euler', 'R.from_euler', (['self.axes[1:]', 'self._array'], {'degrees': '(False)'}), '(self.axes[1:], self._array, degrees=False)\n', (2939, 2982), True, 'from scipy.spatial.transform import Rotation as R\n'), ((3411, 3440), 'scipy.spatial.transform.Rotation.from_matrix', 'R.from_matrix', (['matrix[:3, :3]'], {}), '(matrix[:3, :3])\n', (3424, 3440), True, 'from scipy.spatial.transform import Rotation as R\n'), ((3612, 3635), 'numpy.radians', 'np.radians', (['self._array'], {}), '(self._array)\n', (3622, 3635), True, 'import numpy as np\n'), ((4025, 4054), 'scipy.spatial.transform.Rotation.from_matrix', 'R.from_matrix', (['matrix[:3, :3]'], {}), '(matrix[:3, :3])\n', (4038, 4054), True, 'from scipy.spatial.transform import Rotation as R\n'), ((4646, 4663), 'scipy.spatial.transform.Rotation.from_quat', 'R.from_quat', (['self'], {}), '(self)\n', (4657, 4663), True, 'from scipy.spatial.transform import Rotation as R\n'), ((4754, 4771), 'scipy.spatial.transform.Rotation.from_quat', 'R.from_quat', (['self'], {}), '(self)\n', (4765, 4771), True, 'from scipy.spatial.transform import Rotation as R\n'), ((6562, 6600), 'numpy.linalg.norm', 'np.linalg.norm', (['matrix[:3, :3]'], {'axis': '(0)'}), '(matrix[:3, :3], axis=0)\n', (6576, 6600), True, 'import numpy as np\n'), ((3288, 3311), 'numpy.degrees', 'np.degrees', (['self._array'], {}), '(self._array)\n', (3298, 3311), True, 'import numpy as np\n'), ((4997, 5019), 'numpy.degrees', 'np.degrees', (['euler_data'], {}), '(euler_data)\n', (5007, 5019), True, 'import numpy as np\n'), ((2789, 2845), 'scipy.spatial.transform.Rotation.from_euler', 'R.from_euler', (['self._axes[1:]', 'self._array'], {'degrees': '(False)'}), '(self._axes[1:], self._array, degrees=False)\n', (2801, 2845), True, 'from scipy.spatial.transform import Rotation as R\n'), ((5093, 5122), 'scipy.spatial.transform.Rotation.from_matrix', 'R.from_matrix', (['matrix[:3, :3]'], {}), '(matrix[:3, :3])\n', (5106, 5122), True, 'from scipy.spatial.transform import Rotation as R\n')]
import numpy as np ''' Includes blood glucose level proxy for diabetes: 0-3 (lo2 - counts as abnormal, lo1, normal, hi1, hi2 - counts as abnormal) Initial distribution: [.05, .15, .6, .15, .05] for non-diabetics and [.01, .05, .15, .6, .19] for diabetics ''' class State(object): NUM_OBS_STATES = 720 NUM_HID_STATES = 2 # Binary value of diabetes NUM_PROJ_OBS_STATES = int(NUM_OBS_STATES / 5) # Marginalizing over glucose NUM_FULL_STATES = int(NUM_OBS_STATES * NUM_HID_STATES) PHI_DIM = 5 # the phi(s,a) dimension. See get_phi_vector() # Used for min-max normalization. The last dim is just uniform noise PHI_MAX = [2, 2, 1, 4, 1] PHI_MIN = [0, 0, 0, 0, 0] def __init__(self, state_idx = None, idx_type = 'obs', diabetic_idx = None, state_categs = None): assert state_idx is not None or state_categs is not None assert ((diabetic_idx is not None and diabetic_idx in [0, 1]) or (state_idx is not None and idx_type == 'full')) assert idx_type in ['obs', 'full', 'proj_obs'] if state_idx is not None: self.set_state_by_idx( state_idx, idx_type=idx_type, diabetic_idx=diabetic_idx) elif state_categs is not None: self.set_state_by_categs(state_categs, diabetic_idx) def check_absorbing_state(self): num_abnormal = self.get_num_abnormal() if num_abnormal >= 3: return True elif num_abnormal == 0 and not self.on_treatment(): return True return False def set_state_by_categs(self, state_categs, diabetic_idx): assert len(state_categs) == 7, "must specify 7 state variables" self.hr_state = state_categs[0] self.sysbp_state = state_categs[1] self.percoxyg_state = state_categs[2] self.glucose_state = state_categs[3] self.antibiotic_state = state_categs[4] self.vaso_state = state_categs[5] self.vent_state = state_categs[6] self.diabetic_idx = diabetic_idx def set_state_by_idx(self, state_idx, idx_type, diabetic_idx=None): """set_state_by_idx The state index is determined by using "bit" arithmetic, with the complication that not every state is binary :param state_idx: Given index :param idx_type: Index type, either observed (720), projected (144) or full (1440) :param diabetic_idx: If full state index not given, this is required """ if idx_type == 'obs': term_base = self.NUM_OBS_STATES/3 # Starts with heart rate elif idx_type == 'proj_obs': term_base = self.NUM_PROJ_OBS_STATES/3 elif idx_type == 'full': term_base = self.NUM_FULL_STATES/2 # Starts with diab # Start with the given state index mod_idx = state_idx if idx_type == 'full': self.diabetic_idx = np.floor(mod_idx/term_base).astype(int) mod_idx %= term_base term_base /= 3 # This is for heart rate, the next item else: assert diabetic_idx is not None self.diabetic_idx = diabetic_idx self.hr_state = np.floor(mod_idx/term_base).astype(int) mod_idx %= term_base term_base /= 3 self.sysbp_state = np.floor(mod_idx/term_base).astype(int) mod_idx %= term_base term_base /= 2 self.percoxyg_state = np.floor(mod_idx/term_base).astype(int) if idx_type == 'proj_obs': self.glucose_state = 2 else: mod_idx %= term_base term_base /= 5 self.glucose_state = np.floor(mod_idx/term_base).astype(int) mod_idx %= term_base term_base /= 2 self.antibiotic_state = np.floor(mod_idx/term_base).astype(int) mod_idx %= term_base term_base /= 2 self.vaso_state = np.floor(mod_idx/term_base).astype(int) mod_idx %= term_base term_base /= 2 self.vent_state = np.floor(mod_idx/term_base).astype(int) def get_state_idx(self, idx_type='obs'): ''' returns integer index of state: significance order as in categorical array ''' if idx_type == 'obs': categ_num = np.array([3,3,2,5,2,2,2]) state_categs = [ self.hr_state, self.sysbp_state, self.percoxyg_state, self.glucose_state, self.antibiotic_state, self.vaso_state, self.vent_state] elif idx_type == 'proj_obs': categ_num = np.array([3,3,2,2,2,2]) state_categs = [ self.hr_state, self.sysbp_state, self.percoxyg_state, self.antibiotic_state, self.vaso_state, self.vent_state] elif idx_type == 'full': categ_num = np.array([2,3,3,2,5,2,2,2]) state_categs = [ self.diabetic_idx, self.hr_state, self.sysbp_state, self.percoxyg_state, self.glucose_state, self.antibiotic_state, self.vaso_state, self.vent_state] sum_idx = 0 prev_base = 1 for i in range(len(state_categs)): idx = len(state_categs) - 1 - i sum_idx += prev_base*state_categs[idx] prev_base *= categ_num[idx] return sum_idx def __eq__(self, other): ''' override equals: two states equal if all internal states same ''' return isinstance(other, self.__class__) and \ self.hr_state == other.hr_state and \ self.sysbp_state == other.sysbp_state and \ self.percoxyg_state == other.percoxyg_state and \ self.glucose_state == other.glucose_state and \ self.antibiotic_state == other.antibiotic_state and \ self.vaso_state == other.vaso_state and \ self.vent_state == other.vent_state def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return self.get_state_idx() def get_num_abnormal(self): ''' returns number of abnormal conditions ''' num_abnormal = 0 if self.hr_state != 1: num_abnormal += 1 if self.sysbp_state != 1: num_abnormal += 1 if self.percoxyg_state != 1: num_abnormal += 1 if self.glucose_state != 2: num_abnormal += 1 return num_abnormal def on_treatment(self): ''' returns True iff any of 3 treatments active ''' if self.antibiotic_state == 0 and \ self.vaso_state == 0 and self.vent_state == 0: return False return True def on_antibiotics(self): ''' returns True iff antibiotics active ''' return self.antibiotic_state == 1 def on_vasopressors(self): ''' returns True iff vasopressors active ''' return self.vaso_state == 1 def on_ventilation(self): ''' returns True iff ventilation active ''' return self.vent_state == 1 def copy_state(self): return self.__class__(state_categs = [ self.hr_state, self.sysbp_state, self.percoxyg_state, self.glucose_state, self.antibiotic_state, self.vaso_state, self.vent_state], diabetic_idx=self.diabetic_idx) def get_state_vector(self): return np.array([self.hr_state, self.sysbp_state, self.percoxyg_state, self.glucose_state, self.antibiotic_state, self.vaso_state, self.vent_state, self.diabetic_idx]).astype(int) def get_phi_vector(self): ''' My own definition for phi that only includes states but not treatments. Used in IRL ''' obs = self.get_state_vector()[:4] noise_obs = np.random.rand() obs = np.concatenate([obs, [noise_obs]]) # add noise dim return obs class ConfoundState(State): ''' We add a spurious correlation that the reward is correlated with such feature. - Need new transitions? - A reward causing which states it will get? A new transition model in disc state? ''' NUM_OBS_STATES = State.NUM_OBS_STATES * 2 NUM_HID_STATES = 2 # Binary value of diabetes NUM_PROJ_OBS_STATES = int(NUM_OBS_STATES / 5) # Marginalizing over glucose NUM_FULL_STATES = int(NUM_OBS_STATES * NUM_HID_STATES) PHI_DIM = 5 # the phi(s,a) dimension. See get_phi_vector() # Used for min-max normalization. The last dim is the confounded state PHI_MAX = [2, 2, 1, 4, 1] PHI_MIN = [0, 0, 0, 0, 0] # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) def set_state_by_idx(self, state_idx, idx_type, diabetic_idx=None): """set_state_by_idx The state index is determined by using "bit" arithmetic, with the complication that not every state is binary :param state_idx: Given index :param idx_type: Index type, either observed (720), projected (144) or full (1440) :param diabetic_idx: If full state index not given, this is required """ term_base = (self.NUM_FULL_STATES // 2) self.confound_state = state_idx // term_base state_idx = state_idx % term_base return super().set_state_by_idx(state_idx, idx_type, diabetic_idx=diabetic_idx) def set_state_by_categs(self, state_categs, diabetic_idx): assert len(state_categs) == 8, "must specify 8 state variables" self.confound_state = state_categs[-1] return super().set_state_by_categs( state_categs=state_categs[:-1], diabetic_idx=diabetic_idx, ) def get_phi_vector(self): ''' My own definition for phi that only includes states but not treatments. Used in IRL ''' obs = self.get_state_vector()[:4] # Add an additional obs = np.concatenate([obs, [self.confound_state]]) return obs def copy_state(self): return self.__class__(state_categs = [ self.hr_state, self.sysbp_state, self.percoxyg_state, self.glucose_state, self.antibiotic_state, self.vaso_state, self.vent_state, self.confound_state], diabetic_idx=self.diabetic_idx)
[ "numpy.random.rand", "numpy.floor", "numpy.array", "numpy.concatenate" ]
[((8262, 8278), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (8276, 8278), True, 'import numpy as np\n'), ((8293, 8327), 'numpy.concatenate', 'np.concatenate', (['[obs, [noise_obs]]'], {}), '([obs, [noise_obs]])\n', (8307, 8327), True, 'import numpy as np\n'), ((10379, 10423), 'numpy.concatenate', 'np.concatenate', (['[obs, [self.confound_state]]'], {}), '([obs, [self.confound_state]])\n', (10393, 10423), True, 'import numpy as np\n'), ((4283, 4314), 'numpy.array', 'np.array', (['[3, 3, 2, 5, 2, 2, 2]'], {}), '([3, 3, 2, 5, 2, 2, 2])\n', (4291, 4314), True, 'import numpy as np\n'), ((3212, 3241), 'numpy.floor', 'np.floor', (['(mod_idx / term_base)'], {}), '(mod_idx / term_base)\n', (3220, 3241), True, 'import numpy as np\n'), ((3332, 3361), 'numpy.floor', 'np.floor', (['(mod_idx / term_base)'], {}), '(mod_idx / term_base)\n', (3340, 3361), True, 'import numpy as np\n'), ((3455, 3484), 'numpy.floor', 'np.floor', (['(mod_idx / term_base)'], {}), '(mod_idx / term_base)\n', (3463, 3484), True, 'import numpy as np\n'), ((3798, 3827), 'numpy.floor', 'np.floor', (['(mod_idx / term_base)'], {}), '(mod_idx / term_base)\n', (3806, 3827), True, 'import numpy as np\n'), ((3917, 3946), 'numpy.floor', 'np.floor', (['(mod_idx / term_base)'], {}), '(mod_idx / term_base)\n', (3925, 3946), True, 'import numpy as np\n'), ((4036, 4065), 'numpy.floor', 'np.floor', (['(mod_idx / term_base)'], {}), '(mod_idx / term_base)\n', (4044, 4065), True, 'import numpy as np\n'), ((4670, 4698), 'numpy.array', 'np.array', (['[3, 3, 2, 2, 2, 2]'], {}), '([3, 3, 2, 2, 2, 2])\n', (4678, 4698), True, 'import numpy as np\n'), ((7788, 7957), 'numpy.array', 'np.array', (['[self.hr_state, self.sysbp_state, self.percoxyg_state, self.glucose_state,\n self.antibiotic_state, self.vaso_state, self.vent_state, self.diabetic_idx]'], {}), '([self.hr_state, self.sysbp_state, self.percoxyg_state, self.\n glucose_state, self.antibiotic_state, self.vaso_state, self.vent_state,\n self.diabetic_idx])\n', (7796, 7957), True, 'import numpy as np\n'), ((2944, 2973), 'numpy.floor', 'np.floor', (['(mod_idx / term_base)'], {}), '(mod_idx / term_base)\n', (2952, 2973), True, 'import numpy as np\n'), ((3673, 3702), 'numpy.floor', 'np.floor', (['(mod_idx / term_base)'], {}), '(mod_idx / term_base)\n', (3681, 3702), True, 'import numpy as np\n'), ((5011, 5045), 'numpy.array', 'np.array', (['[2, 3, 3, 2, 5, 2, 2, 2]'], {}), '([2, 3, 3, 2, 5, 2, 2, 2])\n', (5019, 5045), True, 'import numpy as np\n')]
''' Assorted functions used in the machine learning codes during the Blue Stars project Created by: <NAME> (<EMAIL>) ''' #External packages and functions used from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Activation from tensorflow.keras.optimizers import Adam from sklearn.preprocessing import StandardScaler from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestRegressor from sklearn.tree import DecisionTreeRegressor from sklearn.model_selection import RepeatedKFold from sklearn.pipeline import Pipeline from sklearn.metrics import (mean_absolute_error, r2_score, max_error, mean_squared_error) from itertools import combinations import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import tensorflow as tf import time #Sets of filters and corrections used Filters = {'JPLUS': ['uJAVA', 'J0378', 'J0395', 'J0410', 'J0430', 'gSDSS', 'J0515', 'rSDSS', 'J0660', 'iSDSS', 'J0861', 'zSDSS'], 'WISE': ['W1', 'W2', 'W3', 'W4'], 'GALEX': ['NUVmag'], 'GAIA': ['G', 'BP', 'RP'] } Corrections = {'JPLUS': [('Ax_' + Filter) for Filter in Filters['JPLUS']]} def MagnitudeCorrection(df, FilterSet, CorrectionSet, NewDF): ''' Correct the magnitudes of a set of filters inside a dataframe Keyword Arguments: df - Dataframe with uncorrected magnitudes FilterSet - Set of filters to correct CorrectionSet - Set of corrections NewDF - If True, a new dataframe is returned with just the corrected values; If False, the function returns the complete original dataframe with the uncorrected values replaced by the corrected ones. ''' if NewDF == True: TempDF = pd.DataFrame() for Index in range(0, len(FilterSet)): TempDF[FilterSet[Index]] = df[FilterSet[Index]] - df[CorrectionSet[Index]] return TempDF else: for Index in range(0, len(FilterSet)): df[FilterSet[Index]] = df[FilterSet[Index]] - df[CorrectionSet[Index]] return df def CreateColors(df, FilterSet, NewDF): ''' Create all the possible filter combinations (colors) for a set of filters inside a dataframe Keyword arguments: df - Dataframe with the magnitudes FilterSet - Set of filters to combine NewDF - If True, a new dataframe is returned with just the combined values; If False, the function returns the complete original dataframe with the combinations added. ''' CombinationsList = list(combinations(FilterSet, 2)) if NewDF == True: TempDF = pd.DataFrame() for Combination in CombinationsList: CombinationName = '(' + Combination[0] + ' - ' + Combination[1] + ')' TempDF[CombinationName] = (df[Combination[0]] - df[Combination[1]]) return TempDF else: for Combination in CombinationsList: CombinationName = '(' + Combination[0] + ' - ' + Combination[1] + ')' df[CombinationName] = (df[Combination[0]] - df[Combination[1]]) return df def CreateCombinations(df, FilterSet, NewDF): ''' Create all the possible color combinations for a set of filters inside a dataframe Keyword arguments: df - Dataframe with the magnitudes FilterSet - Set of filters to combine NewDF - If True, a new dataframe is returned with just the combined values; If False, the function returns the complete original dataframe with the combinations added. ''' CombinationsList = list(combinations(FilterSet, 4)) if NewDF == True: TempDF = pd.DataFrame() for Combination in CombinationsList: CombinationName = '(' + Combination[0] + ' - ' + Combination[1] + ') - (' + Combination[2] + ' - ' + Combination[3] + ')' TempDF[CombinationName] = (df[Combination[0]] - df[Combination[1]]) - (df[Combination[2]] - df[Combination[3]]) return TempDF else: for Combination in CombinationsList: CombinationName = '(' + Combination[0] + ' - ' + Combination[1] + ') - (' + Combination[2] + ' - ' + Combination[3] + ')' df[CombinationName] = (df[Combination[0]] - df[Combination[1]]) - (df[Combination[2]] - df[Combination[3]]) return df def ReindexDF(df): ''' Create a column by combining the TILE_ID and the NUMBER of each star and set it as the new index of the dataframe Keyword arguments: df - Dataframe to reindex ''' #Function to create the new column def CreateID(df): return (str(df[0]) + ', ' + str(df[1])) #Create a new column with the TILE_ID and the NUMBER to identify each star individually df['ID NUMBER'] = df[['TILE_ID', 'NUMBER']].apply(CreateID, axis = 1) #Set the ID NUMBER column as the new index df = df.set_index('ID NUMBER', drop = False) #Drop any duplicates df = df.drop_duplicates(subset = ['ID NUMBER']) return df def AssembleWorkingDF(df, addWISE, addGALEX, addGAIA, Colors, Combinations): ''' Assemble a dataframe with JPLUS magnitudes and, when asked, colors and color combinations. Keyword arguments: df - Dataframe with the magnitudes addWISE - If True, WISE filters will also be used to make the colors and combinations Colors - If True, all the possible colors will be added to the returnde dataframe Combinations - If True all the possible color combinations will be added to the returned dataframe ''' #Set the index of the dataframe as a combination of the TILE_ID and NUMBER of each star df = ReindexDF(df) magnitudes_df = df[Filters['JPLUS']] #If asked for, the WISE filters are added to the dataframe if addWISE is True: magnitudes_df = pd.concat([magnitudes_df, df[Filters['WISE']]], axis = 1) #If asked for, the GALEX filters are added to the dataframe if addGALEX is True: magnitudes_df = pd.concat([magnitudes_df, df[Filters['GALEX']]], axis = 1) if addGAIA is True: magnitudes_df = pd.concat([magnitudes_df, df[Filters['GAIA']]], axis = 1) WorkingDF = magnitudes_df #If asked for, create a dataframe with all the possible colors and add it to the working dataframe if Colors is True: ColorsDF = CreateColors(magnitudes_df, magnitudes_df.columns, NewDF = True) WorkingDF = pd.concat([WorkingDF, ColorsDF], axis = 1) #If asked for, create a dataframe with all the possible color combinations and add it to the working dataframe if Combinations is True: CombinationsDF = CreateCombinations(magnitudes_df, magnitudes_df.columns, NewDF = True) WorkingDF = pd.concat([WorkingDF, CombinationsDF], axis = 1) #Return the resulting dataframe return (df, WorkingDF) def NeuralNetRegressor(InputSize, Layers, learning_rate, beta1, beta2, epsilon): ''' Create, compile and return a regressor neural network with a specified input size and internal layer structure. Keyword arguments: InputSize - Number of features given to the network as input LayerStructure - A list where each item is the number of nodes in the respective internal layer (e.g., for a network with two layers of 8 nodes each, the list passed would be LayerStructure = [8, 8]) learning_rate - Learning rate to be used on the network optimizer ''' # Initialize the neural Network object NeuralNet = Sequential() # Add the input and first internal layers NeuralNet.add(Dense(Layers[0], input_dim = InputSize, activation = tf.keras.layers.LeakyReLU())) # Start a loop to add all the other internal layers for LayerSize in Layers[1:]: # For each item in the LayerStructure list, add a new layer NeuralNet.add(Dense(LayerSize, activation = tf.keras.layers.LeakyReLU())) # Add the output layer NeuralNet.add(Dense(1, activation = 'linear')) # Compile the Neutal Network with the mean squared error as the loss metric and the adam optimizer optimizer = tf.keras.optimizers.Adam(learning_rate = learning_rate, beta_1 = beta1, beta_2 = beta2, epsilon = epsilon) NeuralNet.compile(loss='mse', optimizer=optimizer) # Return the compiled Neural Network return NeuralNet def rf_evaluator(HyperParams, X, y, n_splits, n_repeats, verbose = 0): ''' Evaluate a STEPE-RF model (Feature Selector + Random Forest) initialized with a certain combination of hyperparameters by using a k-fold n-repeat cross validation and return the average values and standard deviations of a set of metrics (MAE, RMSE, MaxError, R2 Score and elapsed time). Keyword arguments: Hyperparams - A list containing the combination of hyperpameters to test, in the format [n_features, n_trees, min_samples_leaf, max_features, criterion] X - Dataframe containing the input values of the development sample (will be split into training and validation samples) y - Dataframe containing the target values of the development sample (will be split into training and validation samples) n_splits - Number of samples that the data will be split into during the k-fold, n-repeat cross-validation (corresponds to k) n_repeats - Number of times that the data will be shuffled and split again during the k-fold, n-repeat cross-validation (corresponds to n) verbose - Indicates whether the function will print information on the screen or not ''' # Get the hyperparameters from the list n_features, n_trees, min_samples_leaf, max_features, criterion = HyperParams # If asked for, print a message indicating the combination beign evaluated if verbose == 1: init_message = ('Starting Random Forest {}-Fold, {} repeat CV with: n_features = {}, ' + 'n_trees = {}, min_samples_leaf = {} , max_features = {}, criterion = {}...') print(init_message.format(n_splits, n_repeats, n_features, n_trees, min_samples_leaf, max_features, criterion)) # Initialize a list for each error metric and the time MAEs = [] RMSEs = [] MaxEs = [] R2s = [] Times = [] # Initialize the cross-validation function KFSplitter = RepeatedKFold(n_splits = n_splits, n_repeats = n_repeats) # Initialize a variable to count the current iteration Index = 0 # Loop through all the training/validation combinations given by the cross-validation function for train_index, validation_index in KFSplitter.split(X): Index = Index + 1 # If asked for, print a message indication the current iteration if verbose == 1: print('Current Fold: {}/{}'.format(Index, n_splits * n_repeats)) # Get the training and validation samples x_train, x_validation = X.iloc[train_index], X.iloc[validation_index] y_train, y_validation = y.iloc[train_index], y.iloc[validation_index] # Initialize the feature selector using the given hyperparameters FeatureSelector = RFE(estimator=DecisionTreeRegressor(), n_features_to_select = n_features, verbose = 0, step = 20) # Initialize the random forest using the given hyperparameters RF = RandomForestRegressor(n_estimators=n_trees, min_samples_leaf = min_samples_leaf, max_features=max_features, criterion=criterion) # Create a pipeline with the feature selector and the random forest RFPipeline = Pipeline(steps = [('Feature Selector', FeatureSelector),('Model', RF)]) # Start a timer to time the process StartTime = time.time() # Fit the pipeline to the training data RFPipeline = RFPipeline.fit(x_train, y_train.values.reshape(len(y_train))) # Predict the target values of the validation sample Predictions = RFPipeline.predict(x_validation) # Stop the timer EndTime = time.time() # Calculate the error metrics and append them to their lists MAE = mean_absolute_error(y_validation, Predictions) RMSE = np.sqrt(mean_squared_error(y_validation, Predictions)) MaxE = max_error(y_validation, Predictions) R2 = r2_score(y_validation, Predictions) MAEs.append(MAE) RMSEs.append(RMSE) MaxEs.append(MaxE) R2s.append(R2) # Append the value of the elapsed time to its list Times.append(EndTime - StartTime) # Calculate the mean and standard deviation for all the error metrics MAEs = np.array(MAEs) MeanMAE = MAEs.mean() StdMAE = MAEs.std() RMSEs = np.array(RMSEs) MeanRMSE = RMSEs.mean() StdRMSE = RMSEs.std() MaxEs = np.array(MaxEs) MeanMaxE = MaxEs.mean() StdMaxE = MaxEs.std() R2s = np.array(R2s) MeanR2 = R2s.mean() StdR2 = R2s.std() Times = np.array(Times) MeanTime = Times.mean() StdTime = Times.std() # If asked for, print the results to the screen if verbose == 1: print('CV Process Finished! Results:') print('Mean Absolute Error: {:.3f} ({:.3f})'.format(MeanMAE, StdMAE)) print('Root Mean Squared Error: {:.3f} ({:.3f})'.format(MeanRMSE, StdRMSE)) print('Max Error: {:.3f} ({:.3f})'.format(MeanMaxE, StdMaxE)) print('R2 Score: {:.3f} ({:.3f})'.format(MeanR2, StdR2)) print('Time Elapsed: {:.3f} ({:.3f}) s'.format(MeanTime, StdTime)) print('\n') # Return the results return MeanMAE, StdMAE, MeanRMSE, StdRMSE, MeanMaxE, StdMaxE, MeanR2, StdR2, MeanTime, StdTime def nn_evaluator(HyperParams, X, y, n_splits, n_repeats, verbose = 0): ''' Evaluate a STEPE-NN model (Scaler + Feature Selector + Neural Network) initialized with a certain combination of hyperparameters by using a k-fold n-repeat cross-validation and return the average values and standard deviations of a set of metrics (MAE, RMSE, MaxError, R2 Score and elapsed time). Keyword arguments: Hyperparams - A list containing the combination of hyperpameters to test, in the format [FeaturesSize, Epochs, BatchSize, learning_rate, beta1, beta2, epsilon, structure] X - Dataframe containing the input values of the development sample (will be split into training and validation samples) y - Dataframe containing the target values of the development sample (will be split into training and validation samples) n_splits - Number of samples that the data will be split into during the k-fold, n-repeat cross-validation (corresponds to k) n_repeats - Number of times that the data will be shuffled and split again during the k-fold, n-repeat cross-validation (corresponds to n) verbose - Indicates whether the function will print information on the screen or not ''' # Get the hyperparameters from the list FeaturesSize, Epochs, BatchSize, learning_rate, beta1, beta2, epsilon, structure = HyperParams # If asked for, print a message indicating the combination beign evaluated if verbose == 1: init_message = ('Starting Neural Network {}-Fold, {} repeat CV process with: FeaturesSize = {}, ' + 'Epochs = {}, BatchSize = {}, LearningRate = {}, Beta1 = {}, ' + 'Beta2 = {}, epsilon = {}, structure = {}') print(init_message.format(n_splits, n_repeats, FeaturesSize, Epochs, BatchSize, learning_rate, beta1, beta2, epsilon, structure)) # Initialize a list for each error metric and the time MAEs = [] RMSEs = [] MaxEs = [] R2s = [] Times = [] # Initialize the cross-validation function KFSplitter = RepeatedKFold(n_splits = n_splits, n_repeats = n_repeats) # Initialize a variable to count the current iteration Index = 0 # Loop through all the training/validation combinations given by the cross-validation function for train_index, validation_index in KFSplitter.split(X): Index = Index + 1 # If asked for, print a message indication the current iteration if verbose == 1: print('Current Fold: {}/{}'.format(Index, int(n_splits * n_repeats))) # Get the training and validation samples x_train, x_validation = X.iloc[train_index], X.iloc[validation_index] y_train, y_validation = y.iloc[train_index], y.iloc[validation_index] # Start a timer to time the process StartTime = time.time() # Initialize the standard scaler Scaler = StandardScaler() # Fit the scaler to the training data Scaler.fit(x_train) # Scale the training and validation data x_train = Scaler.transform(x_train) x_validation = Scaler.transform(x_validation) # Initialize the feature selector using the given hyperparameters FeatureSelector = RFE(estimator=DecisionTreeRegressor(), n_features_to_select = FeaturesSize, verbose = 0, step = 200) # Fit the feature selector to the training data FeatureSelector.fit(x_train, y_train) # Transform the training data according with the fitted feature selector x_train = FeatureSelector.transform(x_train) x_validation = FeatureSelector.transform(x_validation) # Initialize the neural network with the given hyperparameters NeuralNet = NeuralNetRegressor(FeaturesSize, structure, learning_rate, beta1, beta2, epsilon) # Fit the neural network to the training data using the given hyperparameters NeuralNet.fit(x=x_train, y=y_train.values, validation_data=(x_validation, y_validation.values), batch_size=BatchSize, epochs=Epochs, verbose=0) # Predict the target values of the validation sample and reshape the result Predictions = NeuralNet.predict(x_validation) Predictions = Predictions.reshape(len(Predictions)) # Stop the timer EndTime = time.time() # Calculate the error metrics and append them to their lists MAE = mean_absolute_error(y_validation, Predictions) RMSE = np.sqrt(mean_squared_error(y_validation, Predictions)) MaxE = max_error(y_validation, Predictions) R2 = r2_score(y_validation, Predictions) MAEs.append(MAE) RMSEs.append(RMSE) MaxEs.append(MaxE) R2s.append(R2) # Append the value of the elapsed time to its list Times.append(EndTime - StartTime) # Calculate the mean and standard deviation for all the error metrics MAEs = np.array(MAEs) MeanMAE = MAEs.mean() StdMAE = MAEs.std() RMSEs = np.array(RMSEs) MeanRMSE = RMSEs.mean() StdRMSE = RMSEs.std() MaxEs = np.array(MaxEs) MeanMaxE = MaxEs.mean() StdMaxE = MaxEs.std() R2s = np.array(R2s) MeanR2 = R2s.mean() StdR2 = R2s.std() Times = np.array(Times) MeanTime = Times.mean() StdTime = Times.std() # If asked for, print the results to the screen if verbose == 1: print('CV Process Finished! Results:') print('Mean Absolute Error: {:.3f} ({:.3f})'.format(MeanMAE, StdMAE)) print('Root Mean Squared Error: {:.3f} ({:.3f})'.format(MeanRMSE, StdRMSE)) print('Max Error: {:.3f} ({:.3f})'.format(MeanMaxE, StdMaxE)) print('R2 Score: {:.3f} ({:.3f})'.format(MeanR2, StdR2)) print('Time Elapsed: {:.3f} ({:.3f}) s'.format(MeanTime, StdTime)) print('\n') # Return the results return MeanMAE, StdMAE, MeanRMSE, StdRMSE, MeanMaxE, StdMaxE, MeanR2, StdR2, MeanTime, StdTime def create_heatmap_matrix(data, conditions, x_axis, y_axis, value_label): ''' Create a dataframe containing a certain type of value and with the given x and y axes by applying a set of conditions to another dataframe Keyword arguments: data - Dataframe from which the final dataframe will be created conditions - Dictionary containing a set of conditions that, when applied to the dataframe, results in a len(x_axis) x len(y_axis) dataframe. The format for this dict is {"variable_1": value_1, "variable_2": value_2} x_axis - Dictionary containing the name of the variable and a list of values to use as the x-axis. The format for this dict is {"variable_x": [x_1, x_2, ...]} y_axis - Dictionary containing the name of the variable and a list of values to use as the y-axis. The format for this dict is {"variable_y": [y_1, y_2, ...]} value_label - The label of the variable that will be inside the final dataframe ''' # Get the label and the values of each axis x_label, x_values = list(x_axis.items())[0] y_label, y_values = list(y_axis.items())[0] # Initialize an empty dataframe that will receive the values heatmap = pd.DataFrame(index = y_values, columns = x_values, dtype = float) # Loop through all the given conditions and apply them to the initial dataframe for condition_label in conditions: condition_value = conditions[condition_label] data = data[data[condition_label] == condition_value] # Loop through all the positions inside the final dataframe for x_value in x_values: for y_value in y_values: # For each position, get the corresponsing value inside the initial dataframe matrix_value = data[(data[x_label] == x_value) & (data[y_label] == y_value)][value_label] # If there is a value inside the initial dataframe, put it inside the final # one, and if there isn't, put 0. try: heatmap.at[y_value, x_value] = matrix_value.values[0] except: heatmap.at[y_value, x_value] = 0 # Return the final dataframe return heatmap def plot_heatmaps(left_top_matrix, left_top_label, left_bottom_matrix, left_bottom_label, right_top_matrix, right_top_label, right_bottom_matrix, right_bottom_label, x_label, y_label, value_format, cmap, v_min, v_max, colorbar_label, colorbar_ticks): hp_space_heatmap = plt.figure(figsize=(10.0, 10.0)) hp_space_heatmap.patch.set_facecolor('white') left_top_ax = hp_space_heatmap.add_axes([0.075, 0.575, 0.38, 0.375]) left_bottom_ax = hp_space_heatmap.add_axes([0.075, 0.075, 0.38, 0.375]) right_top_ax = hp_space_heatmap.add_axes([0.475, 0.575, 0.38, 0.375]) right_bottom_ax = hp_space_heatmap.add_axes([0.475, 0.075, 0.38, 0.375]) cbar_ax = hp_space_heatmap.add_axes([0.9, 0.075, 0.025, 0.875]) left_top_heatmap = sns.heatmap(data = left_top_matrix, vmin = v_min, vmax = v_max, ax = left_top_ax, cbar = 1, cbar_ax = cbar_ax, cbar_kws = {'ticks':np.linspace(v_min, v_max, colorbar_ticks)}, linewidths=1.0, annot = True, fmt = value_format, annot_kws = {'size': 14}, cmap = cmap) left_top_ax.set_xticklabels(left_top_matrix.columns, size = 14) left_top_ax.set_yticklabels(left_top_matrix.index, rotation = 0, size = 14) left_top_ax.set_title(left_top_label, fontsize = 20, pad = 5) left_top_ax.set_xlabel(x_label, fontsize = 18) left_top_ax.set_ylabel(y_label, fontsize = 18) left_bottom_heatmap = sns.heatmap(data = left_bottom_matrix, vmin = v_min, vmax = v_max, ax = left_bottom_ax, cbar = 0, linewidths=1.0, annot = True, fmt = value_format, annot_kws = {'size': 14}, cmap = cmap) left_bottom_ax.set_xticklabels(left_bottom_matrix.columns, size = 14) left_bottom_ax.set_yticklabels(left_bottom_matrix.index, rotation = 0, size = 14) left_bottom_ax.set_title(left_bottom_label, fontsize = 20, pad = 5) left_bottom_ax.set_xlabel(x_label, fontsize = 18) left_bottom_ax.set_ylabel(y_label, fontsize = 18) right_top_heatmap = sns.heatmap(data = right_top_matrix, vmin = v_min, vmax = v_max, ax = right_top_ax, cbar = 0, annot = True, yticklabels = False, fmt = value_format, linewidths=1.0, annot_kws = {'size': 14}, cmap = cmap) right_top_ax.set_xticklabels(right_top_matrix.columns, size = 14) right_top_ax.set_title(right_top_label, fontsize = 20, pad = 5) right_top_ax.set_xlabel(x_label, fontsize = 18) right_top_ax.set_ylabel('', fontsize = 0) right_bottom_heatmap = sns.heatmap(data = right_bottom_matrix, vmin = v_min, vmax = v_max, ax = right_bottom_ax, cbar = 0, annot = True, yticklabels = False, fmt = value_format, linewidths=1.0, annot_kws = {'size': 14}, cmap = cmap) right_bottom_ax.set_xticklabels(right_bottom_matrix.columns, size = 14) right_bottom_ax.set_title(right_bottom_label, fontsize = 20, pad = 5) right_bottom_ax.set_xlabel(x_label, fontsize = 18) right_bottom_ax.set_ylabel('', fontsize = 0) cbar = left_top_heatmap.collections[0].colorbar cbar.ax.tick_params(labelsize=14) cbar_ax.set_title(colorbar_label, fontsize = 16, pad = 15) return hp_space_heatmap def plot_heatmaps_single_line(left_matrix, left_label, right_matrix, right_label, x_label, y_label, value_format, cmap, v_min, v_max, colorbar_label, colorbar_ticks): hp_space_heatmap = plt.figure(figsize=(10.0, 5.0)) hp_space_heatmap.patch.set_facecolor('white') left_ax = hp_space_heatmap.add_axes([0.075, 0.125, 0.38, 0.77]) right_ax = hp_space_heatmap.add_axes([0.475, 0.125, 0.38, 0.77]) cbar_ax = hp_space_heatmap.add_axes([0.875, 0.125, 0.025, 0.77]) left_heatmap = sns.heatmap(data = left_matrix, vmin = v_min, vmax = v_max, ax = left_ax, cbar = 1, cbar_ax = cbar_ax, cbar_kws = {'ticks':np.linspace(v_min, v_max, colorbar_ticks)}, linewidths=1.0, annot = True, fmt = value_format, annot_kws = {'size': 14}, cmap = cmap) left_ax.set_xticklabels(left_matrix.columns, size = 14) left_ax.set_yticklabels(left_matrix.index, rotation = 0, size = 14) left_ax.set_title(left_label, fontsize = 20, pad = 15) left_ax.set_xlabel(x_label, fontsize = 18) left_ax.set_ylabel(y_label, fontsize = 18) right_heatmap = sns.heatmap(data = right_matrix, vmin = v_min, vmax = v_max, ax = right_ax, cbar = 0, annot = True, yticklabels = False, fmt = value_format, linewidths=1.0, annot_kws = {'size': 14}, cmap = cmap) right_ax.set_xticklabels(left_matrix.columns, size = 14) right_ax.set_title(right_label, fontsize = 20, pad = 15) right_ax.set_xlabel(x_label, fontsize = 18) right_ax.set_ylabel('', fontsize = 0) cbar = left_heatmap.collections[0].colorbar cbar.ax.tick_params(labelsize=14) cbar_ax.set_title(colorbar_label, fontsize = 16, pad = 15) return hp_space_heatmap def plot_test_graphs(y_test, predictions, parameter_label, parameter_range, error_range, color): test_graphs = plt.figure(1, figsize = [12.8, 6.4]) test_graphs.patch.set_facecolor('white') predictions_plot = test_graphs.add_axes([0.1, 0.325, 0.45, 0.625]) errors_plot = test_graphs.add_axes([0.1, 0.1, 0.45, 0.2]) errors_distribution = test_graphs.add_axes([0.64, 0.1, 0.35, 0.85]) predictions_plot.scatter(x = y_test, y = predictions, color = color, s = 2.5, alpha = 0.25) predictions_plot.plot([parameter_range[0], parameter_range[1]], [parameter_range[0], parameter_range[1]], color = 'k', linewidth = 1.25) predictions_plot.grid() predictions_plot.set_xlim(parameter_range[0], parameter_range[1]) predictions_plot.tick_params(axis = 'x', labelsize = 0) predictions_plot.set_ylim(parameter_range[0], parameter_range[1]) predictions_plot.tick_params(axis = 'y', labelsize = 16) predictions_plot.set_ylabel(r'Predicted ' + parameter_label, fontsize = 20, labelpad = 15) errors_plot.scatter(x = y_test, y = y_test - predictions, color = color, s = 2.5, alpha = 0.25) errors_plot.plot([parameter_range[0], parameter_range[1]], [0, 0], color = 'k', linewidth = 1.25) errors_plot.grid() errors_plot.set_xlim(parameter_range[0], parameter_range[1]) errors_plot.tick_params(axis = 'x', labelsize = 16) errors_plot.set_xlabel(r'LAMOST ' + parameter_label, fontsize = 20) errors_plot.set_ylim(error_range[0], error_range[1]) errors_plot.tick_params(axis = 'y', labelsize = 16) errors_plot.set_ylabel(r'Error', fontsize = 20) errors_distribution.hist(y_test - predictions, bins = 50, histtype = 'bar', ec = 'black', color = color) errors_distribution.set_xlim(error_range[0], error_range[1]) errors_distribution.tick_params(axis = 'x', labelsize = 16) errors_distribution.set_xlabel(r'Error', fontsize = 20) errors_distribution.tick_params(axis = 'y', labelsize = 16) errors_distribution.set_ylabel(r'Count', fontsize = 20) return test_graphs
[ "seaborn.heatmap", "sklearn.preprocessing.StandardScaler", "tensorflow.keras.layers.Dense", "sklearn.metrics.r2_score", "sklearn.metrics.mean_absolute_error", "tensorflow.keras.layers.LeakyReLU", "matplotlib.pyplot.figure", "sklearn.metrics.max_error", "tensorflow.keras.models.Sequential", "sklearn.model_selection.RepeatedKFold", "pandas.DataFrame", "sklearn.tree.DecisionTreeRegressor", "tensorflow.keras.optimizers.Adam", "numpy.linspace", "pandas.concat", "sklearn.metrics.mean_squared_error", "sklearn.ensemble.RandomForestRegressor", "itertools.combinations", "sklearn.pipeline.Pipeline", "time.time", "numpy.array" ]
[((7666, 7678), 'tensorflow.keras.models.Sequential', 'Sequential', ([], {}), '()\n', (7676, 7678), False, 'from tensorflow.keras.models import Sequential\n'), ((8303, 8406), 'tensorflow.keras.optimizers.Adam', 'tf.keras.optimizers.Adam', ([], {'learning_rate': 'learning_rate', 'beta_1': 'beta1', 'beta_2': 'beta2', 'epsilon': 'epsilon'}), '(learning_rate=learning_rate, beta_1=beta1, beta_2=\n beta2, epsilon=epsilon)\n', (8327, 8406), True, 'import tensorflow as tf\n'), ((10557, 10610), 'sklearn.model_selection.RepeatedKFold', 'RepeatedKFold', ([], {'n_splits': 'n_splits', 'n_repeats': 'n_repeats'}), '(n_splits=n_splits, n_repeats=n_repeats)\n', (10570, 10610), False, 'from sklearn.model_selection import RepeatedKFold\n'), ((13089, 13103), 'numpy.array', 'np.array', (['MAEs'], {}), '(MAEs)\n', (13097, 13103), True, 'import numpy as np\n'), ((13171, 13186), 'numpy.array', 'np.array', (['RMSEs'], {}), '(RMSEs)\n', (13179, 13186), True, 'import numpy as np\n'), ((13258, 13273), 'numpy.array', 'np.array', (['MaxEs'], {}), '(MaxEs)\n', (13266, 13273), True, 'import numpy as np\n'), ((13343, 13356), 'numpy.array', 'np.array', (['R2s'], {}), '(R2s)\n', (13351, 13356), True, 'import numpy as np\n'), ((13420, 13435), 'numpy.array', 'np.array', (['Times'], {}), '(Times)\n', (13428, 13435), True, 'import numpy as np\n'), ((16315, 16368), 'sklearn.model_selection.RepeatedKFold', 'RepeatedKFold', ([], {'n_splits': 'n_splits', 'n_repeats': 'n_repeats'}), '(n_splits=n_splits, n_repeats=n_repeats)\n', (16328, 16368), False, 'from sklearn.model_selection import RepeatedKFold\n'), ((19275, 19289), 'numpy.array', 'np.array', (['MAEs'], {}), '(MAEs)\n', (19283, 19289), True, 'import numpy as np\n'), ((19357, 19372), 'numpy.array', 'np.array', (['RMSEs'], {}), '(RMSEs)\n', (19365, 19372), True, 'import numpy as np\n'), ((19444, 19459), 'numpy.array', 'np.array', (['MaxEs'], {}), '(MaxEs)\n', (19452, 19459), True, 'import numpy as np\n'), ((19529, 19542), 'numpy.array', 'np.array', (['R2s'], {}), '(R2s)\n', (19537, 19542), True, 'import numpy as np\n'), ((19606, 19621), 'numpy.array', 'np.array', (['Times'], {}), '(Times)\n', (19614, 19621), True, 'import numpy as np\n'), ((21575, 21634), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'y_values', 'columns': 'x_values', 'dtype': 'float'}), '(index=y_values, columns=x_values, dtype=float)\n', (21587, 21634), True, 'import pandas as pd\n'), ((23017, 23049), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10.0, 10.0)'}), '(figsize=(10.0, 10.0))\n', (23027, 23049), True, 'import matplotlib.pyplot as plt\n'), ((24180, 24357), 'seaborn.heatmap', 'sns.heatmap', ([], {'data': 'left_bottom_matrix', 'vmin': 'v_min', 'vmax': 'v_max', 'ax': 'left_bottom_ax', 'cbar': '(0)', 'linewidths': '(1.0)', 'annot': '(True)', 'fmt': 'value_format', 'annot_kws': "{'size': 14}", 'cmap': 'cmap'}), "(data=left_bottom_matrix, vmin=v_min, vmax=v_max, ax=\n left_bottom_ax, cbar=0, linewidths=1.0, annot=True, fmt=value_format,\n annot_kws={'size': 14}, cmap=cmap)\n", (24191, 24357), True, 'import seaborn as sns\n'), ((24775, 24966), 'seaborn.heatmap', 'sns.heatmap', ([], {'data': 'right_top_matrix', 'vmin': 'v_min', 'vmax': 'v_max', 'ax': 'right_top_ax', 'cbar': '(0)', 'annot': '(True)', 'yticklabels': '(False)', 'fmt': 'value_format', 'linewidths': '(1.0)', 'annot_kws': "{'size': 14}", 'cmap': 'cmap'}), "(data=right_top_matrix, vmin=v_min, vmax=v_max, ax=right_top_ax,\n cbar=0, annot=True, yticklabels=False, fmt=value_format, linewidths=1.0,\n annot_kws={'size': 14}, cmap=cmap)\n", (24786, 24966), True, 'import seaborn as sns\n'), ((25319, 25518), 'seaborn.heatmap', 'sns.heatmap', ([], {'data': 'right_bottom_matrix', 'vmin': 'v_min', 'vmax': 'v_max', 'ax': 'right_bottom_ax', 'cbar': '(0)', 'annot': '(True)', 'yticklabels': '(False)', 'fmt': 'value_format', 'linewidths': '(1.0)', 'annot_kws': "{'size': 14}", 'cmap': 'cmap'}), "(data=right_bottom_matrix, vmin=v_min, vmax=v_max, ax=\n right_bottom_ax, cbar=0, annot=True, yticklabels=False, fmt=\n value_format, linewidths=1.0, annot_kws={'size': 14}, cmap=cmap)\n", (25330, 25518), True, 'import seaborn as sns\n'), ((26275, 26306), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10.0, 5.0)'}), '(figsize=(10.0, 5.0))\n', (26285, 26306), True, 'import matplotlib.pyplot as plt\n'), ((27218, 27401), 'seaborn.heatmap', 'sns.heatmap', ([], {'data': 'right_matrix', 'vmin': 'v_min', 'vmax': 'v_max', 'ax': 'right_ax', 'cbar': '(0)', 'annot': '(True)', 'yticklabels': '(False)', 'fmt': 'value_format', 'linewidths': '(1.0)', 'annot_kws': "{'size': 14}", 'cmap': 'cmap'}), "(data=right_matrix, vmin=v_min, vmax=v_max, ax=right_ax, cbar=0,\n annot=True, yticklabels=False, fmt=value_format, linewidths=1.0,\n annot_kws={'size': 14}, cmap=cmap)\n", (27229, 27401), True, 'import seaborn as sns\n'), ((28001, 28035), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {'figsize': '[12.8, 6.4]'}), '(1, figsize=[12.8, 6.4])\n', (28011, 28035), True, 'import matplotlib.pyplot as plt\n'), ((1801, 1815), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (1813, 1815), True, 'import pandas as pd\n'), ((2629, 2655), 'itertools.combinations', 'combinations', (['FilterSet', '(2)'], {}), '(FilterSet, 2)\n', (2641, 2655), False, 'from itertools import combinations\n'), ((2701, 2715), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (2713, 2715), True, 'import pandas as pd\n'), ((3684, 3710), 'itertools.combinations', 'combinations', (['FilterSet', '(4)'], {}), '(FilterSet, 4)\n', (3696, 3710), False, 'from itertools import combinations\n'), ((3756, 3770), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (3768, 3770), True, 'import pandas as pd\n'), ((5951, 6006), 'pandas.concat', 'pd.concat', (["[magnitudes_df, df[Filters['WISE']]]"], {'axis': '(1)'}), "([magnitudes_df, df[Filters['WISE']]], axis=1)\n", (5960, 6006), True, 'import pandas as pd\n'), ((6127, 6183), 'pandas.concat', 'pd.concat', (["[magnitudes_df, df[Filters['GALEX']]]"], {'axis': '(1)'}), "([magnitudes_df, df[Filters['GALEX']]], axis=1)\n", (6136, 6183), True, 'import pandas as pd\n'), ((6243, 6298), 'pandas.concat', 'pd.concat', (["[magnitudes_df, df[Filters['GAIA']]]"], {'axis': '(1)'}), "([magnitudes_df, df[Filters['GAIA']]], axis=1)\n", (6252, 6298), True, 'import pandas as pd\n'), ((6575, 6615), 'pandas.concat', 'pd.concat', (['[WorkingDF, ColorsDF]'], {'axis': '(1)'}), '([WorkingDF, ColorsDF], axis=1)\n', (6584, 6615), True, 'import pandas as pd\n'), ((6887, 6933), 'pandas.concat', 'pd.concat', (['[WorkingDF, CombinationsDF]'], {'axis': '(1)'}), '([WorkingDF, CombinationsDF], axis=1)\n', (6896, 6933), True, 'import pandas as pd\n'), ((8146, 8175), 'tensorflow.keras.layers.Dense', 'Dense', (['(1)'], {'activation': '"""linear"""'}), "(1, activation='linear')\n", (8151, 8175), False, 'from tensorflow.keras.layers import Dense, Activation\n'), ((11638, 11769), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': 'n_trees', 'min_samples_leaf': 'min_samples_leaf', 'max_features': 'max_features', 'criterion': 'criterion'}), '(n_estimators=n_trees, min_samples_leaf=\n min_samples_leaf, max_features=max_features, criterion=criterion)\n', (11659, 11769), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((11981, 12051), 'sklearn.pipeline.Pipeline', 'Pipeline', ([], {'steps': "[('Feature Selector', FeatureSelector), ('Model', RF)]"}), "(steps=[('Feature Selector', FeatureSelector), ('Model', RF)])\n", (11989, 12051), False, 'from sklearn.pipeline import Pipeline\n'), ((12126, 12137), 'time.time', 'time.time', ([], {}), '()\n', (12135, 12137), False, 'import time\n'), ((12455, 12466), 'time.time', 'time.time', ([], {}), '()\n', (12464, 12466), False, 'import time\n'), ((12560, 12606), 'sklearn.metrics.mean_absolute_error', 'mean_absolute_error', (['y_validation', 'Predictions'], {}), '(y_validation, Predictions)\n', (12579, 12606), False, 'from sklearn.metrics import mean_absolute_error, r2_score, max_error, mean_squared_error\n'), ((12692, 12728), 'sklearn.metrics.max_error', 'max_error', (['y_validation', 'Predictions'], {}), '(y_validation, Predictions)\n', (12701, 12728), False, 'from sklearn.metrics import mean_absolute_error, r2_score, max_error, mean_squared_error\n'), ((12742, 12777), 'sklearn.metrics.r2_score', 'r2_score', (['y_validation', 'Predictions'], {}), '(y_validation, Predictions)\n', (12750, 12777), False, 'from sklearn.metrics import mean_absolute_error, r2_score, max_error, mean_squared_error\n'), ((17088, 17099), 'time.time', 'time.time', ([], {}), '()\n', (17097, 17099), False, 'import time\n'), ((17159, 17175), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (17173, 17175), False, 'from sklearn.preprocessing import StandardScaler\n'), ((18662, 18673), 'time.time', 'time.time', ([], {}), '()\n', (18671, 18673), False, 'import time\n'), ((18758, 18804), 'sklearn.metrics.mean_absolute_error', 'mean_absolute_error', (['y_validation', 'Predictions'], {}), '(y_validation, Predictions)\n', (18777, 18804), False, 'from sklearn.metrics import mean_absolute_error, r2_score, max_error, mean_squared_error\n'), ((18890, 18926), 'sklearn.metrics.max_error', 'max_error', (['y_validation', 'Predictions'], {}), '(y_validation, Predictions)\n', (18899, 18926), False, 'from sklearn.metrics import mean_absolute_error, r2_score, max_error, mean_squared_error\n'), ((18940, 18975), 'sklearn.metrics.r2_score', 'r2_score', (['y_validation', 'Predictions'], {}), '(y_validation, Predictions)\n', (18948, 18975), False, 'from sklearn.metrics import mean_absolute_error, r2_score, max_error, mean_squared_error\n'), ((12630, 12675), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['y_validation', 'Predictions'], {}), '(y_validation, Predictions)\n', (12648, 12675), False, 'from sklearn.metrics import mean_absolute_error, r2_score, max_error, mean_squared_error\n'), ((18828, 18873), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['y_validation', 'Predictions'], {}), '(y_validation, Predictions)\n', (18846, 18873), False, 'from sklearn.metrics import mean_absolute_error, r2_score, max_error, mean_squared_error\n'), ((7826, 7853), 'tensorflow.keras.layers.LeakyReLU', 'tf.keras.layers.LeakyReLU', ([], {}), '()\n', (7851, 7853), True, 'import tensorflow as tf\n'), ((11403, 11426), 'sklearn.tree.DecisionTreeRegressor', 'DecisionTreeRegressor', ([], {}), '()\n', (11424, 11426), False, 'from sklearn.tree import DecisionTreeRegressor\n'), ((17514, 17537), 'sklearn.tree.DecisionTreeRegressor', 'DecisionTreeRegressor', ([], {}), '()\n', (17535, 17537), False, 'from sklearn.tree import DecisionTreeRegressor\n'), ((23669, 23710), 'numpy.linspace', 'np.linspace', (['v_min', 'v_max', 'colorbar_ticks'], {}), '(v_min, v_max, colorbar_ticks)\n', (23680, 23710), True, 'import numpy as np\n'), ((26743, 26784), 'numpy.linspace', 'np.linspace', (['v_min', 'v_max', 'colorbar_ticks'], {}), '(v_min, v_max, colorbar_ticks)\n', (26754, 26784), True, 'import numpy as np\n'), ((8066, 8093), 'tensorflow.keras.layers.LeakyReLU', 'tf.keras.layers.LeakyReLU', ([], {}), '()\n', (8091, 8093), True, 'import tensorflow as tf\n')]
import argparse import cv2 import numpy as np from typing import Tuple def str2bool(v): if isinstance(v, bool): return v if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.') def depth2colorjet(depth: np.ndarray) -> np.ndarray: """ Given a 2d numpy array of floats ranging from 0 - 1, turn it into a uint8 2d numpy array with jet color mapping """ depth = -1 * np.log(depth) depth = (depth / np.max(depth) * 255).astype(np.uint8) rgb = cv2.applyColorMap(depth, cv2.COLORMAP_JET) return rgb def flip(img: np.ndarray, steering_angle: float) -> Tuple[np.ndarray, float]: return np.fliplr(img), -steering_angle def crop_roi(img: np.ndarray, min_x: int, min_y: int, max_x: int, max_y: int): return img[min_x:max_x, min_y:max_y] def random_flip(image, steering_angle): """ Randomly flipt the image left <-> right, and adjust the steering angle. """ if np.random.rand() < 0.5: image = cv2.flip(image, 1) steering_angle = -steering_angle return image, steering_angle def depthToLogDepth(depth_image): output = np.log(depth_image) output = 1 - (output / np.min(output)) return output if __name__ == '__main__': from pathlib import Path import glob import os img_dir = Path("/data/output_oct_10/front_depth") img_paths = [p for p in sorted(img_dir.glob("*.npy", ), key=os.path.getmtime)] for img_path in img_paths: im = np.load(img_path.as_posix()) cv2.imshow("depth image", im) cv2.imshow("log depth", depthToLogDepth(im)) k = cv2.waitKey(1) if k == ord('q') or k == 27: break
[ "numpy.log", "cv2.waitKey", "numpy.fliplr", "pathlib.Path", "numpy.min", "numpy.max", "cv2.applyColorMap", "numpy.random.rand", "cv2.flip", "cv2.imshow", "argparse.ArgumentTypeError" ]
[((651, 693), 'cv2.applyColorMap', 'cv2.applyColorMap', (['depth', 'cv2.COLORMAP_JET'], {}), '(depth, cv2.COLORMAP_JET)\n', (668, 693), False, 'import cv2\n'), ((1276, 1295), 'numpy.log', 'np.log', (['depth_image'], {}), '(depth_image)\n', (1282, 1295), True, 'import numpy as np\n'), ((1458, 1497), 'pathlib.Path', 'Path', (['"""/data/output_oct_10/front_depth"""'], {}), "('/data/output_oct_10/front_depth')\n", (1462, 1497), False, 'from pathlib import Path\n'), ((568, 581), 'numpy.log', 'np.log', (['depth'], {}), '(depth)\n', (574, 581), True, 'import numpy as np\n'), ((800, 814), 'numpy.fliplr', 'np.fliplr', (['img'], {}), '(img)\n', (809, 814), True, 'import numpy as np\n'), ((1095, 1111), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (1109, 1111), True, 'import numpy as np\n'), ((1135, 1153), 'cv2.flip', 'cv2.flip', (['image', '(1)'], {}), '(image, 1)\n', (1143, 1153), False, 'import cv2\n'), ((1663, 1692), 'cv2.imshow', 'cv2.imshow', (['"""depth image"""', 'im'], {}), "('depth image', im)\n", (1673, 1692), False, 'import cv2\n'), ((1758, 1772), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (1769, 1772), False, 'import cv2\n'), ((306, 359), 'argparse.ArgumentTypeError', 'argparse.ArgumentTypeError', (['"""Boolean value expected."""'], {}), "('Boolean value expected.')\n", (332, 359), False, 'import argparse\n'), ((1323, 1337), 'numpy.min', 'np.min', (['output'], {}), '(output)\n', (1329, 1337), True, 'import numpy as np\n'), ((603, 616), 'numpy.max', 'np.max', (['depth'], {}), '(depth)\n', (609, 616), True, 'import numpy as np\n')]
#!/usr/bin/python3 import random import math import numpy as np def softmax(z): return np.exp(z) / np.sum(np.exp(z)) ######################################################################################################################## # Input & Data Normalization class Input(object): def __init__(self, input): self.input = input def normalize(self): pass # return self.input / self.maximum def denormalize(self): pass # return self.input * self.maximum @property def input(self): return self.input @input.setter def input(self, input): self.input = input class CategoricalInput(Input): def __init__(self, input): super().__init__(input) class NumericalInput(Input): def __init__(self, input): super().__init__(input) @property def maximum(self): raise NotImplementedError("Input class requires a maximum property to be defined!") class PriceInput(NumericalInput): def __init__(self, input): super().__init__(input) @property def maximum(self): return 100 class CategoryInput(CategoricalInput): pass class DiscountInput(NumericalInput): def __init__(self, input): super().__init__(input) # log normalization: z = x * y => ln(z) = ln(x) + ln(y) # min-max normalization ######################################################################################################################## # Neural Network class Connection(object): def __init__(self): self.weight = random.random() self.delta = 0.0 class Neuron(object): def __init__(self, nid, lid=0): self.nid = nid self.lid = lid self.output = 0.0 self.connections = [] self.gradient = 0.0 self.activate = None self.derivate = None def weights(self, weights=None): if weights is None: output = [0.0] * len(self.connections) for c in range(len(self.connections)): output[c] = self.connections[c].weight return output else: assert len(weights) == len(self.connections) for c in range(len(self.connections)): self.connections[c].weight = weights[c] class Network(object): eta = 0.9 # learning rate - too low and it will take forever, too big and it will oscillate forever alpha = 0.9 # momentum - how much of the previous value should be taken in account scale = 1.0 # weight scale def __init__(self): self.layers = [] self.error = 0.0 self.average = 0.0 self.smoothing = 100.0 self.outputs = [] def setup(self): if Network.scale is not None: for l in range(1, len(self.layers)): # 1: skip input for n in range(len(self.layers[l])): # w/o bias for c in range(len(self.layers[l][n].connections)): self.layers[l][n].connections[c].weight *= Network.scale Network.scale = None def train(self, inputs, targets, batch_size=1): self.setup() assert batch_size > 0 if batch_size > 1: # batch_size = 2, 3, 4, ... # inputs=((1,2,3),(2,3,4)) targets=((1,2),(2,3)) pass print('TODO: implement logic for training in batches') else: # batch_size = 1 # inputs=(1,2,3) targets=(1,2) assert len(inputs) == len(self.layers[0])-1 # input values == input neurons(-1 bias) assert len(targets) == len(self.layers[-1])-1 # target values == output neurons(-1 bias) # set input values to input neurons for i in range(len(inputs)): self.layers[0][i].output = inputs[i] # feed forward to hidden for l in range(1, len(self.layers)): # 1: skip input for n in range(len(self.layers[l])-1): # w/o bias Network.forward(self.layers[l-1], self.layers[l][n]) # outputs after feed forward self.outputs.clear() for n in range(len(self.layers[-1]) - 1): # w/o bias(-1) self.outputs.append(self.layers[-1][n].output) # calculate overall error(RMS) self.error = 0.0 for n in range(len(self.layers[-1])-1): delta = targets[n] - self.layers[-1][n].output self.error += delta*delta self.error /= len(self.layers[-1])-1 self.error = math.sqrt(self.error) # RMS self.average = (self.average * self.smoothing + self.error) / (self.smoothing + 1.0) # back propagate from output to 1st hidden # calculate output layer gradients for n in range(len(self.layers[-1])-1): # w/o bias(-1) Network.gradient(self.layers[-1][n], targets[n]) # output gradients # calculate hidden layer gradients for l in range(len(self.layers)-2,0,-1): # from last hidden layer -> the first hidden layer [hn...h0] for n in range(len(self.layers[l])): # loop each neuron...calc gradinet using next layer neurons Network.gradient(self.layers[l][n], self.layers[l+1]) # update hidden layer outputs for l in range(len(self.layers)-1,0,-1): # from output layer -> first hidden layer [o...h0] for n in range(len(self.layers[l])-1): # w/o bias(-1) Network.update(self.layers[l-1], self.layers[l][n]) # should it be Layer.udpate(const neuron) ? # return output layer outputs return self.outputs def predict(self, inputs, batch_size=1): assert batch_size > 0 if batch_size > 1: pass else: assert len(inputs) == len(self.layers[0]) - 1 # input values == input neurons(-1 bias) # set input values to input neurons for n in range(len(inputs)): # 0 # set input values self.layers[0][n].output = inputs[n] # feed forward to hidden for l in range(1, len(self.layers)): # [1..output] # input layer already done for n in range(len(self.layers[l]) - 1): # w/o bias Network.forward(self.layers[l-1], self.layers[l][n]) # read outputs from the last layer self.outputs.clear() for n in range(len(self.layers[-1]) - 1): # w/o bias(-1) self.outputs.append(self.layers[-1][n].output) return self.outputs @staticmethod def forward(layer, neuron): # forward input from prev layer to neuron assert type(neuron) is Neuron # move these 2 asserts assert type(layer) is list total = 0.0 for n in range(len(layer)): # including bias total += layer[n].output * layer[n].connections[neuron.nid].weight neuron.output = neuron.activate(total) @staticmethod def gradient(neuron, target): # target or next layer if type(target) is list: total = 0.0 for n in range(len(target)-1): # w/o bias(-1) total += neuron.connections[n].weight * target[n].gradient neuron.gradient = total * neuron.derivate(neuron.output) # output neuron gradient else: delta = target - neuron.output neuron.gradient = delta * neuron.derivate(neuron.output) # hidden neuron gradient @staticmethod def update(layer, neuron): # update layer using a neuron(from next layer) for n in range(len(layer)): # prev layer olddelta = layer[n].connections[neuron.nid].delta newdelta = Network.eta * layer[n].output * neuron.gradient + Network.alpha * olddelta layer[n].connections[neuron.nid].delta = newdelta layer[n].connections[neuron.nid].weight += newdelta @staticmethod def cost(targets, outputs): assert len(targets) == len(outputs) cost = 0.0 for i in range(len(targets)): cost += 0.5*(targets[i]-outputs[i])**2 return cost ######################################################################################################################## # Builder class Activation(object): @staticmethod def activate(x): raise NotImplementedError("Activation class requires .activate() method to be defined to be defined!") @staticmethod def derivate(x): raise NotImplementedError("Activation class requires .derivate() method to be defined to be defined!") class TanhActivation(Activation): @staticmethod def activate(x): return math.tanh(x) @staticmethod def derivate(x): return 1 - x*x # approx for tanh derivative class SigmoidActivation(Activation): @staticmethod def activate(x): return 1 / (1 + np.exp(-x)) @staticmethod def derivate(x): a = SigmoidActivation.activate(x) return (1 - a) * a class SoftplusActivation(Activation): @staticmethod def activate(x): return math.log1p(1 + math.exp(x)) @staticmethod def derivate(x): return 1 / (1 + math.exp(-x)) class BinaryActivation(Activation): @staticmethod def activate(x): return 0 if x < 0 else 1 @staticmethod def derivate(x): return 0 if x != 0 else math.nan class ReluActivation(Activation): @staticmethod def activate(x): return 0 if x < 0 else x @staticmethod def derivate(x): return 0 if x < 0 else 1 class LinearActivation(Activation): @staticmethod def activate(x): return x @staticmethod def derivate(x): return 1 class Distribution(object): @staticmethod def apply(neuron): raise NotImplementedError('Distribution type class requires .apply method to be implemented!') class UniformDistribution(Distribution): @staticmethod def apply(neuron): left = 1.0 for c in range(len(neuron.connections)): if c == len(neuron.connections)-1: neuron.connections[c].weight = left break neuron.connections[c].weight = random.uniform(0.00001, left) left -= neuron.connections[c].weight return neuron class LacunDristribution(Distribution): # @todo LaCun 98 pass class Layer(object): def __init__(self, neurons=1, activation=None, distribution=None): self.neurons = neurons self.distribution = activation if issubclass(activation, Distribution) else distribution self.activation = activation if issubclass(activation, Activation) else None def __getitem__(self, item): pass class Builder(object): builder = None # activations TANH = TanhActivation LINEAR = LinearActivation RELU = ReluActivation SIGMOID = SigmoidActivation SOFTPLUS = SoftplusActivation #distributions UNIFORM = UniformDistribution def __init__(self): self.layers = [] def __getitem__(self, item): return self.layers[item] @staticmethod def instance(): if Builder.builder is None: Builder.builder = Builder() return Builder.builder def set(self, item, layer): self.layers[item] = layer return Builder.builder def add(self, layer): self.layers.append(layer) return Builder.builder def compile(self): # init empty network _nn = Network() # 1 input, n hidden, 1 output _num_layers = len(self.layers) # assert num of layers, MUST be >= 3 assert _num_layers >= 3 # add layers for l in range(_num_layers): assert type(self.layers[l]) is Layer # IF last => 0 conn ELSE next layer neuron count (w/o bias) _num_connections = 0 if l == _num_layers-1 else self.layers[l+1].neurons _num_neurons = self.layers[l].neurons # current layer + layer id for reference _layer = [] # neurons for the current layer for n in range(_num_neurons+1): # +1 bias # create neuron _neuron = Neuron(n,l) # add connnections for _ in range(_num_connections): _connection = Connection() _neuron.connections.append(_connection) # apply distribution on neuron weights if l < _num_layers-1 and self.layers[l].distribution is not None: _neuron = self.layers[l].distribution.apply(_neuron) # setup neuron activation functions if l > 0: _neuron.activate = self.layers[l].activation.activate _neuron.derivate = self.layers[l].activation.derivate # if bias: output = 1 else: 0 _neuron.output = 1.0 if n == _num_neurons else _neuron.output _layer.append(_neuron) # add layer to network's layers _nn.layers.append(_layer) return _nn ######################################################################################################################## # Testing nn = Builder.instance().add(Layer(2, Builder.UNIFORM)).add(Layer(1, Builder.SIGMOID, Builder.UNIFORM)).add(Layer(1, Builder.SIGMOID)).compile() m = 1 for i in range(100): # + a = random.randint(0, m) b = random.randint(0, m) t = (a or b) o, = nn.train((a, b), (t,)) print('train ', (a, b), (a or b), [o], ' error ', nn.error) for _ in range(4): a = random.randint(0, m) b = random.randint(0, m) o, = nn.predict((a, b)) print('predict', (a, b), (a or b), [o]) ######################################################################################################################## # Notes # @note # hidden layer activation: tanh # output layer activation: linear(no constraints), logistic(for [0,1]) or exp(strictly positive) # @note # bias neurons allow network output to be translated to the desired output range # @note # normalization: match inputs to the range to that of the activation function # denormalize outputs to their original desired state # @notes # gpgpu w/ opencl neural network # meta reinforced learning: use nn to learn the best nn structure # framework for input normalization/standardization/denormalization # @notes @relu # [0,n] float inputs: relu + linear NOT good; the weights, gradients and outputs become too large(+ or -) # [0,n] float inputs: relu=max(0,x) in the hidden layer prevents weights from blancing out(cause of the 0) # @notes @sigmoid # addition: w/ enough layers, iterations and w/ input normalization to [0,1] output will converge to the correct result
[ "math.exp", "random.randint", "math.sqrt", "math.tanh", "random.uniform", "random.random", "numpy.exp" ]
[((13660, 13680), 'random.randint', 'random.randint', (['(0)', 'm'], {}), '(0, m)\n', (13674, 13680), False, 'import random\n'), ((13690, 13710), 'random.randint', 'random.randint', (['(0)', 'm'], {}), '(0, m)\n', (13704, 13710), False, 'import random\n'), ((13854, 13874), 'random.randint', 'random.randint', (['(0)', 'm'], {}), '(0, m)\n', (13868, 13874), False, 'import random\n'), ((13884, 13904), 'random.randint', 'random.randint', (['(0)', 'm'], {}), '(0, m)\n', (13898, 13904), False, 'import random\n'), ((94, 103), 'numpy.exp', 'np.exp', (['z'], {}), '(z)\n', (100, 103), True, 'import numpy as np\n'), ((1583, 1598), 'random.random', 'random.random', ([], {}), '()\n', (1596, 1598), False, 'import random\n'), ((8839, 8851), 'math.tanh', 'math.tanh', (['x'], {}), '(x)\n', (8848, 8851), False, 'import math\n'), ((113, 122), 'numpy.exp', 'np.exp', (['z'], {}), '(z)\n', (119, 122), True, 'import numpy as np\n'), ((4631, 4652), 'math.sqrt', 'math.sqrt', (['self.error'], {}), '(self.error)\n', (4640, 4652), False, 'import math\n'), ((10385, 10412), 'random.uniform', 'random.uniform', (['(1e-05)', 'left'], {}), '(1e-05, left)\n', (10399, 10412), False, 'import random\n'), ((9051, 9061), 'numpy.exp', 'np.exp', (['(-x)'], {}), '(-x)\n', (9057, 9061), True, 'import numpy as np\n'), ((9281, 9292), 'math.exp', 'math.exp', (['x'], {}), '(x)\n', (9289, 9292), False, 'import math\n'), ((9358, 9370), 'math.exp', 'math.exp', (['(-x)'], {}), '(-x)\n', (9366, 9370), False, 'import math\n')]
import os import numpy as np import h5py import tensorflow as tf import keras import keras.backend as K ############################################ ### Function to load data in h5py format ### ############################################ def load_data(path_to_data): data = h5py.File(path_to_data,'r') X_test_seq = np.transpose(np.array(data['test_in_seq']),axes=(0,2,1)) X_test_region = np.transpose(np.array(data['test_in_region']),axes=(0, 2, 1)) y_test_RBP = np.array(data['test_out']) y_test_name= np.array(data['test_name']) y_train= np.array(data['train_out']) data.close() return X_test_seq, X_test_region, y_test_RBP, y_test_name, y_train ######################## ### custume metrics #### ######################## def precision(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) #TPs=K.sum(K.round(K.clip(y_true * y_pred , 0, 1))) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) precision = true_positives / (predicted_positives + K.epsilon()) return precision def recall(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) #TPs=K.sum(K.round(K.clip(y_ture * y_pred , 0, 1))) possible_positives = K.sum(K.round(K.clip(y_true, 0, 1))) recall = true_positives / (possible_positives + K.epsilon()) return recall ########################################################## ### Function to convert the sequence to one-hot encode ### ########################################################## def seq_to_mat(seq): seq_len = len(seq) seq = seq.replace('A','0') seq = seq.replace('a','0') seq = seq.replace('C','1') seq = seq.replace('c','1') seq = seq.replace('G','2') seq = seq.replace('g','2') seq = seq.replace('T','3') seq = seq.replace('t','3') seq = seq.replace('U','3') seq = seq.replace('u','3') seq = seq.replace('N','4') #some cases have N in sequence seq = seq.replace('n','4') seq_code = np.zeros((4,seq_len), dtype='float16') for i in range(seq_len): if int(seq[i]) != 4: seq_code[int(seq[i]),i] = 1 else: seq_code[0:4,i] = np.tile(0.25,4) return np.transpose(seq_code) def seq_to_1hot(seq,randomsel=True): 'converts the sequence to one-hot encoding' import random seq_len = len(seq) seq= seq.upper() seq_code = np.zeros((4,seq_len), dtype='int') for i in range(seq_len): nt = seq[i] if nt == 'A': seq_code[0,i] = 1 elif nt == 'C': seq_code[1,i] = 1 elif nt == 'G': seq_code[2,i] = 1 elif nt == 'T': seq_code[3,i] = 1 elif randomsel: rn = random.randint(0,3) seq_code[rn,i] = 1 return seq_code ########################################################## ### Function to convert the region to one-hot encode ### ########################################################## def region_to_mat(region): region_len = len(region) region= region.replace('i','0') region= region.replace('c','1') region= region.replace('3','2') region= region.replace('5','3') region= region.replace('N','4') region_code = np.zeros((4,region_len), dtype='float16') for i in range(region_len): if int(region[i]) != 4: region_code[int(region[i]),i] = 1 else: region_code[0:4,i] = np.tile(0.25,4) return np.transpose(region_code) ###################################################################################### ######### function to find the top k and bottom K frequent 6MERs functions############ ###################################################################################### def getkmer(X,y,pred,RBP_index,k): import rpy2 from rpy2.robjects.packages import importr base = importr('base') Biostrings= importr("Biostrings") multi_ind_high=[i[0] for i in sorted(enumerate(pred[:,RBP_index]), key=lambda x:x[1],reverse=True) if y[i[0],RBP_index]==1][0:k] multi_ind_low=[i[0] for i in sorted(enumerate(pred[:,RBP_index]), key=lambda x:x[1]) if y[i[0],RBP_index]==1][0:k] multi_fastaseq_low=vecs2dna(np.transpose(X[multi_ind_low],axes=(0,2,1))) multi_fastaseq_high=vecs2dna(np.transpose(X[multi_ind_high],axes=(0,2,1))) multi_fastaseq_high=base.unlist(multi_fastaseq_high) multi_fastaseq_low=base.unlist(multi_fastaseq_low) kmer_freqs_low = base.rowSums(base.sapply(Biostrings.DNAStringSet(multi_fastaseq_low),Biostrings.oligonucleotideFrequency,width = 6, step = 1)) kmer_freqs_high = base.rowSums(base.sapply(Biostrings.DNAStringSet(multi_fastaseq_high),Biostrings.oligonucleotideFrequency,width = 6, step = 1)) return kmer_freqs_low, kmer_freqs_high ############################################################################### ######### function to convert one hot encoded sequence to sequence ############ ############################################################################### def vecs2dna(seq_vecs): if len(seq_vecs.shape) == 2: seq_vecs = np.reshape(seq_vecs, (seq_vecs.shape[0], 4, -1)) elif len(seq_vecs.shape) == 4: seq_vecs = np.reshape(seq_vecs, (seq_vecs.shape[0], 4, -1)) seqs = [] for i in range(seq_vecs.shape[0]): seq_list = ['']*seq_vecs.shape[2] for j in range(seq_vecs.shape[2]): if seq_vecs[i,0,j] == 1: seq_list[j] = 'A' elif seq_vecs[i,1,j] == 1: seq_list[j] = 'C' elif seq_vecs[i,2,j] == 1: seq_list[j] = 'G' elif seq_vecs[i,3,j] == 1: seq_list[j] = 'T' elif seq_vecs[i,:,j].sum() == 1: seq_list[j] = 'N' else: print('Malformed position vector: ', seq_vecs[i,:,j], 'for sequence %d position %d' % (i,j), file=sys.stderr) seqs.append(''.join(seq_list)) return seqs
[ "h5py.File", "rpy2.robjects.packages.importr", "random.randint", "keras.backend.epsilon", "numpy.zeros", "numpy.transpose", "numpy.array", "numpy.reshape", "numpy.tile", "keras.backend.clip" ]
[((282, 310), 'h5py.File', 'h5py.File', (['path_to_data', '"""r"""'], {}), "(path_to_data, 'r')\n", (291, 310), False, 'import h5py\n'), ((483, 509), 'numpy.array', 'np.array', (["data['test_out']"], {}), "(data['test_out'])\n", (491, 509), True, 'import numpy as np\n'), ((527, 554), 'numpy.array', 'np.array', (["data['test_name']"], {}), "(data['test_name'])\n", (535, 554), True, 'import numpy as np\n'), ((568, 595), 'numpy.array', 'np.array', (["data['train_out']"], {}), "(data['train_out'])\n", (576, 595), True, 'import numpy as np\n'), ((1977, 2016), 'numpy.zeros', 'np.zeros', (['(4, seq_len)'], {'dtype': '"""float16"""'}), "((4, seq_len), dtype='float16')\n", (1985, 2016), True, 'import numpy as np\n'), ((2185, 2207), 'numpy.transpose', 'np.transpose', (['seq_code'], {}), '(seq_code)\n', (2197, 2207), True, 'import numpy as np\n'), ((2356, 2391), 'numpy.zeros', 'np.zeros', (['(4, seq_len)'], {'dtype': '"""int"""'}), "((4, seq_len), dtype='int')\n", (2364, 2391), True, 'import numpy as np\n'), ((3118, 3160), 'numpy.zeros', 'np.zeros', (['(4, region_len)'], {'dtype': '"""float16"""'}), "((4, region_len), dtype='float16')\n", (3126, 3160), True, 'import numpy as np\n'), ((3344, 3369), 'numpy.transpose', 'np.transpose', (['region_code'], {}), '(region_code)\n', (3356, 3369), True, 'import numpy as np\n'), ((3742, 3757), 'rpy2.robjects.packages.importr', 'importr', (['"""base"""'], {}), "('base')\n", (3749, 3757), False, 'from rpy2.robjects.packages import importr\n'), ((3774, 3795), 'rpy2.robjects.packages.importr', 'importr', (['"""Biostrings"""'], {}), "('Biostrings')\n", (3781, 3795), False, 'from rpy2.robjects.packages import importr\n'), ((340, 369), 'numpy.array', 'np.array', (["data['test_in_seq']"], {}), "(data['test_in_seq'])\n", (348, 369), True, 'import numpy as np\n'), ((417, 449), 'numpy.array', 'np.array', (["data['test_in_region']"], {}), "(data['test_in_region'])\n", (425, 449), True, 'import numpy as np\n'), ((4082, 4128), 'numpy.transpose', 'np.transpose', (['X[multi_ind_low]'], {'axes': '(0, 2, 1)'}), '(X[multi_ind_low], axes=(0, 2, 1))\n', (4094, 4128), True, 'import numpy as np\n'), ((4160, 4207), 'numpy.transpose', 'np.transpose', (['X[multi_ind_high]'], {'axes': '(0, 2, 1)'}), '(X[multi_ind_high], axes=(0, 2, 1))\n', (4172, 4207), True, 'import numpy as np\n'), ((4980, 5028), 'numpy.reshape', 'np.reshape', (['seq_vecs', '(seq_vecs.shape[0], 4, -1)'], {}), '(seq_vecs, (seq_vecs.shape[0], 4, -1))\n', (4990, 5028), True, 'import numpy as np\n'), ((825, 854), 'keras.backend.clip', 'K.clip', (['(y_true * y_pred)', '(0)', '(1)'], {}), '(y_true * y_pred, 0, 1)\n', (831, 854), True, 'import keras.backend as K\n'), ((947, 967), 'keras.backend.clip', 'K.clip', (['y_pred', '(0)', '(1)'], {}), '(y_pred, 0, 1)\n', (953, 967), True, 'import keras.backend as K\n'), ((1023, 1034), 'keras.backend.epsilon', 'K.epsilon', ([], {}), '()\n', (1032, 1034), True, 'import keras.backend as K\n'), ((1115, 1144), 'keras.backend.clip', 'K.clip', (['(y_true * y_pred)', '(0)', '(1)'], {}), '(y_true * y_pred, 0, 1)\n', (1121, 1144), True, 'import keras.backend as K\n'), ((1236, 1256), 'keras.backend.clip', 'K.clip', (['y_true', '(0)', '(1)'], {}), '(y_true, 0, 1)\n', (1242, 1256), True, 'import keras.backend as K\n'), ((1308, 1319), 'keras.backend.epsilon', 'K.epsilon', ([], {}), '()\n', (1317, 1319), True, 'import keras.backend as K\n'), ((2158, 2174), 'numpy.tile', 'np.tile', (['(0.25)', '(4)'], {}), '(0.25, 4)\n', (2165, 2174), True, 'import numpy as np\n'), ((3317, 3333), 'numpy.tile', 'np.tile', (['(0.25)', '(4)'], {}), '(0.25, 4)\n', (3324, 3333), True, 'import numpy as np\n'), ((5083, 5131), 'numpy.reshape', 'np.reshape', (['seq_vecs', '(seq_vecs.shape[0], 4, -1)'], {}), '(seq_vecs, (seq_vecs.shape[0], 4, -1))\n', (5093, 5131), True, 'import numpy as np\n'), ((2626, 2646), 'random.randint', 'random.randint', (['(0)', '(3)'], {}), '(0, 3)\n', (2640, 2646), False, 'import random\n')]
#!/usr/bin/env python """ main.py """ import sys import json import argparse import numpy as np from helpers import compute_scores P_AT_01_THRESHOLD = 0.475 def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--cache-path', type=str, default='data/cache') return parser.parse_args() if __name__ == "__main__": args = parse_args() # -- # Check correctness X_valid = np.load('%s_valid.npy' % args.cache_path, allow_pickle=True) topk = np.loadtxt('results/topk') scores = compute_scores(topk, X_valid) # -- # Log print(json.dumps({ "status" : "PASS" if scores[1] >= P_AT_01_THRESHOLD else "FAIL", "p_at_01" : scores[1], "p_at_05" : scores[5], "p_at_10" : scores[10], })) does_pass = "PASS" if scores[1] >= P_AT_01_THRESHOLD else "FAIL" open('results/.pass', 'w').write(str(does_pass))
[ "numpy.load", "argparse.ArgumentParser", "helpers.compute_scores", "json.dumps", "numpy.loadtxt" ]
[((196, 221), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (219, 221), False, 'import argparse\n'), ((434, 494), 'numpy.load', 'np.load', (["('%s_valid.npy' % args.cache_path)"], {'allow_pickle': '(True)'}), "('%s_valid.npy' % args.cache_path, allow_pickle=True)\n", (441, 494), True, 'import numpy as np\n'), ((509, 535), 'numpy.loadtxt', 'np.loadtxt', (['"""results/topk"""'], {}), "('results/topk')\n", (519, 535), True, 'import numpy as np\n'), ((554, 583), 'helpers.compute_scores', 'compute_scores', (['topk', 'X_valid'], {}), '(topk, X_valid)\n', (568, 583), False, 'from helpers import compute_scores\n'), ((623, 770), 'json.dumps', 'json.dumps', (["{'status': 'PASS' if scores[1] >= P_AT_01_THRESHOLD else 'FAIL', 'p_at_01':\n scores[1], 'p_at_05': scores[5], 'p_at_10': scores[10]}"], {}), "({'status': 'PASS' if scores[1] >= P_AT_01_THRESHOLD else 'FAIL',\n 'p_at_01': scores[1], 'p_at_05': scores[5], 'p_at_10': scores[10]})\n", (633, 770), False, 'import json\n')]
import torch import numpy as np from smplx import SMPL as _SMPL from smplx.body_models import ModelOutput from smplx.lbs import vertices2joints import config class SMPL(_SMPL): """ Extension of the official SMPL (from the smplx python package) implementation to support more joints. """ def __init__(self, *args, **kwargs): super(SMPL, self).__init__(*args, **kwargs) J_regressor_extra = np.load(config.J_REGRESSOR_EXTRA_PATH) J_regressor_cocoplus = np.load(config.COCOPLUS_REGRESSOR_PATH) J_regressor_h36m = np.load(config.H36M_REGRESSOR_PATH) self.register_buffer('J_regressor_extra', torch.tensor(J_regressor_extra, dtype=torch.float32)) self.register_buffer('J_regressor_cocoplus', torch.tensor(J_regressor_cocoplus, dtype=torch.float32)) self.register_buffer('J_regressor_h36m', torch.tensor(J_regressor_h36m, dtype=torch.float32)) def forward(self, *args, **kwargs): kwargs['get_skin'] = True smpl_output = super(SMPL, self).forward(*args, **kwargs) extra_joints = vertices2joints(self.J_regressor_extra, smpl_output.vertices) cocoplus_joints = vertices2joints(self.J_regressor_cocoplus, smpl_output.vertices) h36m_joints = vertices2joints(self.J_regressor_h36m, smpl_output.vertices) all_joints = torch.cat([smpl_output.joints, extra_joints, cocoplus_joints, h36m_joints], dim=1) output = ModelOutput(vertices=smpl_output.vertices, global_orient=smpl_output.global_orient, body_pose=smpl_output.body_pose, joints=all_joints, betas=smpl_output.betas, full_pose=smpl_output.full_pose) return output
[ "numpy.load", "smplx.body_models.ModelOutput", "torch.cat", "smplx.lbs.vertices2joints", "torch.tensor" ]
[((427, 465), 'numpy.load', 'np.load', (['config.J_REGRESSOR_EXTRA_PATH'], {}), '(config.J_REGRESSOR_EXTRA_PATH)\n', (434, 465), True, 'import numpy as np\n'), ((497, 536), 'numpy.load', 'np.load', (['config.COCOPLUS_REGRESSOR_PATH'], {}), '(config.COCOPLUS_REGRESSOR_PATH)\n', (504, 536), True, 'import numpy as np\n'), ((564, 599), 'numpy.load', 'np.load', (['config.H36M_REGRESSOR_PATH'], {}), '(config.H36M_REGRESSOR_PATH)\n', (571, 599), True, 'import numpy as np\n'), ((1270, 1331), 'smplx.lbs.vertices2joints', 'vertices2joints', (['self.J_regressor_extra', 'smpl_output.vertices'], {}), '(self.J_regressor_extra, smpl_output.vertices)\n', (1285, 1331), False, 'from smplx.lbs import vertices2joints\n'), ((1358, 1422), 'smplx.lbs.vertices2joints', 'vertices2joints', (['self.J_regressor_cocoplus', 'smpl_output.vertices'], {}), '(self.J_regressor_cocoplus, smpl_output.vertices)\n', (1373, 1422), False, 'from smplx.lbs import vertices2joints\n'), ((1445, 1505), 'smplx.lbs.vertices2joints', 'vertices2joints', (['self.J_regressor_h36m', 'smpl_output.vertices'], {}), '(self.J_regressor_h36m, smpl_output.vertices)\n', (1460, 1505), False, 'from smplx.lbs import vertices2joints\n'), ((1527, 1613), 'torch.cat', 'torch.cat', (['[smpl_output.joints, extra_joints, cocoplus_joints, h36m_joints]'], {'dim': '(1)'}), '([smpl_output.joints, extra_joints, cocoplus_joints, h36m_joints],\n dim=1)\n', (1536, 1613), False, 'import torch\n'), ((1659, 1861), 'smplx.body_models.ModelOutput', 'ModelOutput', ([], {'vertices': 'smpl_output.vertices', 'global_orient': 'smpl_output.global_orient', 'body_pose': 'smpl_output.body_pose', 'joints': 'all_joints', 'betas': 'smpl_output.betas', 'full_pose': 'smpl_output.full_pose'}), '(vertices=smpl_output.vertices, global_orient=smpl_output.\n global_orient, body_pose=smpl_output.body_pose, joints=all_joints,\n betas=smpl_output.betas, full_pose=smpl_output.full_pose)\n', (1670, 1861), False, 'from smplx.body_models import ModelOutput\n'), ((650, 702), 'torch.tensor', 'torch.tensor', (['J_regressor_extra'], {'dtype': 'torch.float32'}), '(J_regressor_extra, dtype=torch.float32)\n', (662, 702), False, 'import torch\n'), ((820, 875), 'torch.tensor', 'torch.tensor', (['J_regressor_cocoplus'], {'dtype': 'torch.float32'}), '(J_regressor_cocoplus, dtype=torch.float32)\n', (832, 875), False, 'import torch\n'), ((992, 1043), 'torch.tensor', 'torch.tensor', (['J_regressor_h36m'], {'dtype': 'torch.float32'}), '(J_regressor_h36m, dtype=torch.float32)\n', (1004, 1043), False, 'import torch\n')]
from __future__ import print_function import argparse import json import logging import os import pandas as pd import numpy as np import pickle as pkl from sagemaker_containers import entry_point from sagemaker_xgboost_container.data_utils import get_dmatrix import xgboost as xgb from xgboost.sklearn import XGBClassifier # how do we make sure we are using this from sklearn import metrics #Additional scklearn functions def CreateBalancedSampleWeights(y_train, largest_class_weight_coef): classes = y_train.unique() classes.sort() class_samples = np.bincount(y_train) total_samples = class_samples.sum() n_classes = len(class_samples) weights = total_samples / (n_classes * class_samples * 1.0) class_weight_dict = {key : value for (key, value) in zip(classes, weights)} class_weight_dict[classes[1]] = class_weight_dict[classes[1]] * largest_class_weight_coef sample_weights = [class_weight_dict[y] for y in y_train] return sample_weights def input_fn(request_body, request_content_type): """An input_fn that loads a numpy array""" if request_content_type == "text/csv": input_features =[] for i in request_body.split('\n'): # the first element is the id, the rest is payload if len(i) == 0: continue input_features.append([float(j) for j in i.split(",")]) return np.array(input_features) else: pass if __name__ == '__main__': parser = argparse.ArgumentParser() # Hyperparameters are described here parser.add_argument('--n_estimators', type=int, default=1000) parser.add_argument('--n_jobs', type=int, default=4) parser.add_argument('--max_depth', type=int, default=5) parser.add_argument('--learning_rate', type=float, default=0.01) parser.add_argument('--objective', type=str, default='multi:softmax') parser.add_argument('--subsample', type=float, default=1) parser.add_argument('--reg_lambda', type=float, default=0.1) parser.add_argument('--eval_metric', type=str, default='merror') #- looks like we don't include this in fact, worth checking later parser.add_argument('--colsample_bytree', type=float, default=1) parser.add_argument('--gamma', type=float, default=1) # SageMaker specific arguments. Defaults are set in the environment variables. parser.add_argument('--output_data_dir', type=str, default=os.environ.get('SM_OUTPUT_DATA_DIR')) parser.add_argument('--model_dir', type=str, default=os.environ.get('SM_MODEL_DIR')) parser.add_argument('--train', type=str, default=os.environ['SM_CHANNEL_TRAIN']) parser.add_argument('--validation', type=str, default=os.environ['SM_CHANNEL_VALIDATION']) args = parser.parse_args() # Take the set of files and read them all into a single pandas dataframe input_files1 = [ os.path.join(args.train, file1) for file1 in os.listdir(args.train) ] if len(input_files1) == 0: raise ValueError(('There are no files in {}.\n' + 'This usually indicates that the channel was incorrectly specified,\n' + 'the data specification in S3 was incorrectly specified or the role specified\n' + 'does not have permission to access the data.').format(args.train)) raw_data1 = [pd.read_csv(file1, header=None, engine='python') for file1 in input_files1] training_data = pd.concat(raw_data1) input_files2 = [ os.path.join(args.validation, file2) for file2 in os.listdir(args.validation) ] if len(input_files2) == 0: raise ValueError(('There are no files in {}.\n' + 'This usually indicates that the channel was incorrectly specified,\n' + 'the data specification in S3 was incorrectly specified or the role specified\n' + 'does not have permission to access the data.').format(args.validation)) raw_data2 = [pd.read_csv(file2, header=None, engine='python') for file2 in input_files2] validing_data = pd.concat(raw_data2) y_train = training_data.iloc[:,0].values X_train = training_data.iloc[:,1:].values y_test = validing_data.iloc[:,0].values X_test = validing_data.iloc[:,1:].values largest_class_weight_coef = max(training_data.iloc[:,0].value_counts().values)/training_data.shape[0] w_train = CreateBalancedSampleWeights(training_data.iloc[:,0], largest_class_weight_coef=largest_class_weight_coef) clf = xgb.XGBClassifier(n_estimators=args.n_estimators, n_jobs=args.n_jobs, max_depth=args.max_depth, learning_rate=args.learning_rate, subsample=args.subsample, objective=args.objective) clf = clf.fit(X_train, y_train, sample_weight=w_train, eval_set=[(X_train, y_train), (X_test, y_test)], eval_metric='merror', verbose=True) evals_result = clf.evals_result() # save the model model_location = args.model_dir + '/xgboost-model' pkl.dump(clf, open(model_location, 'wb')) logging.info("Stored trained model at {}".format(model_location)) def model_fn(model_dir): """Deserialize and return fitted model. Note that this should have the same name as the serialized model in the _xgb_train method """ model_file = 'xgboost-model' clf = pkl.load(open(os.path.join(model_dir, model_file), 'rb')) return clf
[ "os.listdir", "argparse.ArgumentParser", "pandas.read_csv", "os.environ.get", "numpy.array", "xgboost.XGBClassifier", "numpy.bincount", "os.path.join", "pandas.concat" ]
[((568, 588), 'numpy.bincount', 'np.bincount', (['y_train'], {}), '(y_train)\n', (579, 588), True, 'import numpy as np\n'), ((1479, 1504), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1502, 1504), False, 'import argparse\n'), ((3426, 3446), 'pandas.concat', 'pd.concat', (['raw_data1'], {}), '(raw_data1)\n', (3435, 3446), True, 'import pandas as pd\n'), ((4058, 4078), 'pandas.concat', 'pd.concat', (['raw_data2'], {}), '(raw_data2)\n', (4067, 4078), True, 'import pandas as pd\n'), ((4504, 4694), 'xgboost.XGBClassifier', 'xgb.XGBClassifier', ([], {'n_estimators': 'args.n_estimators', 'n_jobs': 'args.n_jobs', 'max_depth': 'args.max_depth', 'learning_rate': 'args.learning_rate', 'subsample': 'args.subsample', 'objective': 'args.objective'}), '(n_estimators=args.n_estimators, n_jobs=args.n_jobs,\n max_depth=args.max_depth, learning_rate=args.learning_rate, subsample=\n args.subsample, objective=args.objective)\n', (4521, 4694), True, 'import xgboost as xgb\n'), ((1386, 1410), 'numpy.array', 'np.array', (['input_features'], {}), '(input_features)\n', (1394, 1410), True, 'import numpy as np\n'), ((2852, 2883), 'os.path.join', 'os.path.join', (['args.train', 'file1'], {}), '(args.train, file1)\n', (2864, 2883), False, 'import os\n'), ((3330, 3378), 'pandas.read_csv', 'pd.read_csv', (['file1'], {'header': 'None', 'engine': '"""python"""'}), "(file1, header=None, engine='python')\n", (3341, 3378), True, 'import pandas as pd\n'), ((3469, 3505), 'os.path.join', 'os.path.join', (['args.validation', 'file2'], {}), '(args.validation, file2)\n', (3481, 3505), False, 'import os\n'), ((3962, 4010), 'pandas.read_csv', 'pd.read_csv', (['file2'], {'header': 'None', 'engine': '"""python"""'}), "(file2, header=None, engine='python')\n", (3973, 4010), True, 'import pandas as pd\n'), ((2414, 2450), 'os.environ.get', 'os.environ.get', (['"""SM_OUTPUT_DATA_DIR"""'], {}), "('SM_OUTPUT_DATA_DIR')\n", (2428, 2450), False, 'import os\n'), ((2509, 2539), 'os.environ.get', 'os.environ.get', (['"""SM_MODEL_DIR"""'], {}), "('SM_MODEL_DIR')\n", (2523, 2539), False, 'import os\n'), ((2897, 2919), 'os.listdir', 'os.listdir', (['args.train'], {}), '(args.train)\n', (2907, 2919), False, 'import os\n'), ((3519, 3546), 'os.listdir', 'os.listdir', (['args.validation'], {}), '(args.validation)\n', (3529, 3546), False, 'import os\n'), ((5333, 5368), 'os.path.join', 'os.path.join', (['model_dir', 'model_file'], {}), '(model_dir, model_file)\n', (5345, 5368), False, 'import os\n')]
import os from subprocess import PIPE, Popen import numpy as np import pytest import vtk import vtki from vtki import examples from vtki.plotting import running_xserver TEST_DOWNLOADS = False try: if os.environ['TEST_DOWNLOADS'] == 'True': TEST_DOWNLOADS = True except KeyError: pass @pytest.mark.skipif(not running_xserver(), reason="Requires X11") def test_docexample_advancedplottingwithnumpy(): import vtki import numpy as np # Make a grid x, y, z = np.meshgrid(np.linspace(-5, 5, 20), np.linspace(-5, 5, 20), np.linspace(-5, 5, 5)) points = np.empty((x.size, 3)) points[:, 0] = x.ravel('F') points[:, 1] = y.ravel('F') points[:, 2] = z.ravel('F') # Compute a direction for the vector field direction = np.sin(points)**3 # plot using the plotting class plotter = vtki.Plotter(off_screen=True) plotter.add_arrows(points, direction, 0.5) plotter.set_background([0, 0, 0]) # RGB set to black plotter.plot(auto_close=False) np.any(plotter.screenshot()) plotter.close() @pytest.mark.skipif(not running_xserver(), reason="Requires X11") def test_creatingagifmovie(tmpdir, off_screen=True): if tmpdir: filename = str(tmpdir.mkdir("tmpdir").join('wave.gif')) else: filename = '/tmp/wave.gif' x = np.arange(-10, 10, 0.25) y = np.arange(-10, 10, 0.25) x, y = np.meshgrid(x, y) r = np.sqrt(x**2 + y**2) z = np.sin(r) # Create and structured surface grid = vtki.StructuredGrid(x, y, z) # Make copy of points pts = grid.points.copy() # Start a plotter object and set the scalars to the Z height plotter = vtki.Plotter(off_screen=off_screen) plotter.add_mesh(grid, scalars=z.ravel()) plotter.plot(auto_close=False) # Open a gif plotter.open_gif(filename) # Update Z and write a frame for each updated position nframe = 5 for phase in np.linspace(0, 2*np.pi, nframe + 1)[:nframe]: z = np.sin(r + phase) pts[:, -1] = z.ravel() plotter.update_coordinates(pts) plotter.update_scalars(z.ravel()) plotter.write_frame() # Close movie and delete object plotter.close() @pytest.mark.skipif(not running_xserver(), reason="Requires X11") def test_plot_wave(): points = examples.plot_wave(wavetime=0.1, off_screen=True) assert isinstance(points, np.ndarray) @pytest.mark.skipif(not running_xserver(), reason="Requires X11") def test_beam_example(): examples.beam_example(off_screen=True) @pytest.mark.skipif(not running_xserver(), reason="Requires X11") def test_plot_ants_plane(): examples.plot_ants_plane(off_screen=True) def test_load_ant(): """ Load ply ant mesh """ mesh = examples.load_ant() assert mesh.n_points def test_load_airplane(): """ Load ply airplane mesh """ mesh = examples.load_airplane() assert mesh.n_points def test_load_sphere(): """ Loads sphere ply mesh """ mesh = examples.load_sphere() assert mesh.n_points def test_load_channels(): """ Loads geostat training image """ mesh = examples.load_channels() assert mesh.n_points if TEST_DOWNLOADS: def test_download_masonry_texture(): data = examples.download_masonry_texture() assert isinstance(data, vtk.vtkTexture) def test_download_usa_texture(): data = examples.download_usa_texture() assert isinstance(data, vtk.vtkTexture) def test_download_usa(): data = examples.download_usa() assert np.any(data.points) def test_download_st_helens(): data = examples.download_st_helens() assert data.n_points def test_download_bunny(): data = examples.download_bunny() assert data.n_points def test_download_cow(): data = examples.download_cow() assert data.n_points def test_download_faults(): data = examples.download_faults() assert data.n_points def test_download_tensors(): data = examples.download_tensors() assert data.n_points def test_download_head(): data = examples.download_head() assert data.n_points def test_download_bolt_nut(): data = examples.download_bolt_nut() assert isinstance(data, vtki.MultiBlock) def test_download_clown(): data = examples.download_clown() assert data.n_points def test_download_exodus(): data = examples.download_exodus() assert data.n_blocks def test_download_nefertiti(): data = examples.download_nefertiti() assert data.n_cells # End of download tests
[ "vtki.examples.load_sphere", "numpy.empty", "vtki.examples.download_faults", "vtki.examples.download_bolt_nut", "numpy.sin", "numpy.arange", "vtki.examples.plot_wave", "vtki.StructuredGrid", "vtki.Plotter", "numpy.meshgrid", "vtki.examples.download_masonry_texture", "numpy.linspace", "vtki.examples.load_ant", "vtki.examples.download_usa", "vtki.examples.download_clown", "vtki.plotting.running_xserver", "vtki.examples.download_nefertiti", "vtki.examples.download_exodus", "vtki.examples.download_st_helens", "vtki.examples.load_channels", "vtki.examples.download_cow", "vtki.examples.download_head", "vtki.examples.load_airplane", "vtki.examples.download_tensors", "vtki.examples.download_usa_texture", "numpy.any", "vtki.examples.beam_example", "vtki.examples.download_bunny", "vtki.examples.plot_ants_plane", "numpy.sqrt" ]
[((641, 662), 'numpy.empty', 'np.empty', (['(x.size, 3)'], {}), '((x.size, 3))\n', (649, 662), True, 'import numpy as np\n'), ((892, 921), 'vtki.Plotter', 'vtki.Plotter', ([], {'off_screen': '(True)'}), '(off_screen=True)\n', (904, 921), False, 'import vtki\n'), ((1368, 1392), 'numpy.arange', 'np.arange', (['(-10)', '(10)', '(0.25)'], {}), '(-10, 10, 0.25)\n', (1377, 1392), True, 'import numpy as np\n'), ((1401, 1425), 'numpy.arange', 'np.arange', (['(-10)', '(10)', '(0.25)'], {}), '(-10, 10, 0.25)\n', (1410, 1425), True, 'import numpy as np\n'), ((1437, 1454), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {}), '(x, y)\n', (1448, 1454), True, 'import numpy as np\n'), ((1463, 1487), 'numpy.sqrt', 'np.sqrt', (['(x ** 2 + y ** 2)'], {}), '(x ** 2 + y ** 2)\n', (1470, 1487), True, 'import numpy as np\n'), ((1492, 1501), 'numpy.sin', 'np.sin', (['r'], {}), '(r)\n', (1498, 1501), True, 'import numpy as np\n'), ((1550, 1578), 'vtki.StructuredGrid', 'vtki.StructuredGrid', (['x', 'y', 'z'], {}), '(x, y, z)\n', (1569, 1578), False, 'import vtki\n'), ((1715, 1750), 'vtki.Plotter', 'vtki.Plotter', ([], {'off_screen': 'off_screen'}), '(off_screen=off_screen)\n', (1727, 1750), False, 'import vtki\n'), ((2352, 2401), 'vtki.examples.plot_wave', 'examples.plot_wave', ([], {'wavetime': '(0.1)', 'off_screen': '(True)'}), '(wavetime=0.1, off_screen=True)\n', (2370, 2401), False, 'from vtki import examples\n'), ((2541, 2579), 'vtki.examples.beam_example', 'examples.beam_example', ([], {'off_screen': '(True)'}), '(off_screen=True)\n', (2562, 2579), False, 'from vtki import examples\n'), ((2680, 2721), 'vtki.examples.plot_ants_plane', 'examples.plot_ants_plane', ([], {'off_screen': '(True)'}), '(off_screen=True)\n', (2704, 2721), False, 'from vtki import examples\n'), ((2786, 2805), 'vtki.examples.load_ant', 'examples.load_ant', ([], {}), '()\n', (2803, 2805), False, 'from vtki import examples\n'), ((2905, 2929), 'vtki.examples.load_airplane', 'examples.load_airplane', ([], {}), '()\n', (2927, 2929), False, 'from vtki import examples\n'), ((3026, 3048), 'vtki.examples.load_sphere', 'examples.load_sphere', ([], {}), '()\n', (3046, 3048), False, 'from vtki import examples\n'), ((3154, 3178), 'vtki.examples.load_channels', 'examples.load_channels', ([], {}), '()\n', (3176, 3178), False, 'from vtki import examples\n'), ((504, 526), 'numpy.linspace', 'np.linspace', (['(-5)', '(5)', '(20)'], {}), '(-5, 5, 20)\n', (515, 526), True, 'import numpy as np\n'), ((554, 576), 'numpy.linspace', 'np.linspace', (['(-5)', '(5)', '(20)'], {}), '(-5, 5, 20)\n', (565, 576), True, 'import numpy as np\n'), ((604, 625), 'numpy.linspace', 'np.linspace', (['(-5)', '(5)', '(5)'], {}), '(-5, 5, 5)\n', (615, 625), True, 'import numpy as np\n'), ((823, 837), 'numpy.sin', 'np.sin', (['points'], {}), '(points)\n', (829, 837), True, 'import numpy as np\n'), ((329, 346), 'vtki.plotting.running_xserver', 'running_xserver', ([], {}), '()\n', (344, 346), False, 'from vtki.plotting import running_xserver\n'), ((1973, 2010), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', '(nframe + 1)'], {}), '(0, 2 * np.pi, nframe + 1)\n', (1984, 2010), True, 'import numpy as np\n'), ((2031, 2048), 'numpy.sin', 'np.sin', (['(r + phase)'], {}), '(r + phase)\n', (2037, 2048), True, 'import numpy as np\n'), ((1140, 1157), 'vtki.plotting.running_xserver', 'running_xserver', ([], {}), '()\n', (1155, 1157), False, 'from vtki.plotting import running_xserver\n'), ((2275, 2292), 'vtki.plotting.running_xserver', 'running_xserver', ([], {}), '()\n', (2290, 2292), False, 'from vtki.plotting import running_xserver\n'), ((2470, 2487), 'vtki.plotting.running_xserver', 'running_xserver', ([], {}), '()\n', (2485, 2487), False, 'from vtki.plotting import running_xserver\n'), ((2606, 2623), 'vtki.plotting.running_xserver', 'running_xserver', ([], {}), '()\n', (2621, 2623), False, 'from vtki.plotting import running_xserver\n'), ((3281, 3316), 'vtki.examples.download_masonry_texture', 'examples.download_masonry_texture', ([], {}), '()\n', (3314, 3316), False, 'from vtki import examples\n'), ((3418, 3449), 'vtki.examples.download_usa_texture', 'examples.download_usa_texture', ([], {}), '()\n', (3447, 3449), False, 'from vtki import examples\n'), ((3543, 3566), 'vtki.examples.download_usa', 'examples.download_usa', ([], {}), '()\n', (3564, 3566), False, 'from vtki import examples\n'), ((3582, 3601), 'numpy.any', 'np.any', (['data.points'], {}), '(data.points)\n', (3588, 3601), True, 'import numpy as np\n'), ((3653, 3682), 'vtki.examples.download_st_helens', 'examples.download_st_helens', ([], {}), '()\n', (3680, 3682), False, 'from vtki import examples\n'), ((3759, 3784), 'vtki.examples.download_bunny', 'examples.download_bunny', ([], {}), '()\n', (3782, 3784), False, 'from vtki import examples\n'), ((3859, 3882), 'vtki.examples.download_cow', 'examples.download_cow', ([], {}), '()\n', (3880, 3882), False, 'from vtki import examples\n'), ((3960, 3986), 'vtki.examples.download_faults', 'examples.download_faults', ([], {}), '()\n', (3984, 3986), False, 'from vtki import examples\n'), ((4065, 4092), 'vtki.examples.download_tensors', 'examples.download_tensors', ([], {}), '()\n', (4090, 4092), False, 'from vtki import examples\n'), ((4168, 4192), 'vtki.examples.download_head', 'examples.download_head', ([], {}), '()\n', (4190, 4192), False, 'from vtki import examples\n'), ((4272, 4300), 'vtki.examples.download_bolt_nut', 'examples.download_bolt_nut', ([], {}), '()\n', (4298, 4300), False, 'from vtki import examples\n'), ((4397, 4422), 'vtki.examples.download_clown', 'examples.download_clown', ([], {}), '()\n', (4420, 4422), False, 'from vtki import examples\n'), ((4500, 4526), 'vtki.examples.download_exodus', 'examples.download_exodus', ([], {}), '()\n', (4524, 4526), False, 'from vtki import examples\n'), ((4607, 4636), 'vtki.examples.download_nefertiti', 'examples.download_nefertiti', ([], {}), '()\n', (4634, 4636), False, 'from vtki import examples\n')]
import numpy as np import matplotlib.pyplot as plt from convolution_matrices.convmat2D import * #generate a picture array with a circle Nx = 2*256 Ny = 2*256; A = 9*np.ones((Nx,Ny)); ci = Nx/2-1; cj= Ny/2-1; cr = np.round(0.35*Nx); I,J=np.meshgrid(np.arange(A.shape[0]),np.arange(A.shape[1])); dist = np.sqrt((I-ci)**2 + (J-cj)**2); A[np.where(dist<cr)] = 1; plt.imshow(A); plt.show() ##fft P = 1; Q = 1; C1 = convmat2D(A, P, Q); C2 = convmat2D_o(A, 3,3); print(np.linalg.norm(C1-C2)) #make sure the two ways of writing convmat are the same... print(C1.shape) np.set_printoptions(precision=2) print(C1) plt.imshow(np.abs(C1)); plt.show() ## test 2d convmat on a homogeneous medium, should return a scaled identity matrix eps_grid = np.ones((Nx,Ny)); C_uniform = convmat2D(eps_grid,3,3) print(C_uniform)
[ "numpy.set_printoptions", "matplotlib.pyplot.show", "numpy.abs", "matplotlib.pyplot.imshow", "numpy.ones", "numpy.where", "numpy.arange", "numpy.linalg.norm", "numpy.round", "numpy.sqrt" ]
[((214, 233), 'numpy.round', 'np.round', (['(0.35 * Nx)'], {}), '(0.35 * Nx)\n', (222, 233), True, 'import numpy as np\n'), ((303, 341), 'numpy.sqrt', 'np.sqrt', (['((I - ci) ** 2 + (J - cj) ** 2)'], {}), '((I - ci) ** 2 + (J - cj) ** 2)\n', (310, 341), True, 'import numpy as np\n'), ((362, 375), 'matplotlib.pyplot.imshow', 'plt.imshow', (['A'], {}), '(A)\n', (372, 375), True, 'import matplotlib.pyplot as plt\n'), ((377, 387), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (385, 387), True, 'import matplotlib.pyplot as plt\n'), ((564, 596), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(2)'}), '(precision=2)\n', (583, 596), True, 'import numpy as np\n'), ((631, 641), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (639, 641), True, 'import matplotlib.pyplot as plt\n'), ((738, 755), 'numpy.ones', 'np.ones', (['(Nx, Ny)'], {}), '((Nx, Ny))\n', (745, 755), True, 'import numpy as np\n'), ((166, 183), 'numpy.ones', 'np.ones', (['(Nx, Ny)'], {}), '((Nx, Ny))\n', (173, 183), True, 'import numpy as np\n'), ((249, 270), 'numpy.arange', 'np.arange', (['A.shape[0]'], {}), '(A.shape[0])\n', (258, 270), True, 'import numpy as np\n'), ((271, 292), 'numpy.arange', 'np.arange', (['A.shape[1]'], {}), '(A.shape[1])\n', (280, 292), True, 'import numpy as np\n'), ((337, 356), 'numpy.where', 'np.where', (['(dist < cr)'], {}), '(dist < cr)\n', (345, 356), True, 'import numpy as np\n'), ((466, 489), 'numpy.linalg.norm', 'np.linalg.norm', (['(C1 - C2)'], {}), '(C1 - C2)\n', (480, 489), True, 'import numpy as np\n'), ((618, 628), 'numpy.abs', 'np.abs', (['C1'], {}), '(C1)\n', (624, 628), True, 'import numpy as np\n')]
# coding: utf-8 # In[1]: import torch import torch.nn as nn import torchvision import torch.nn.functional as F from torchvision import datasets, transforms, models import numpy as np import matplotlib.pyplot as plt from datetime import datetime import sys, os from glob import glob import imageio import argparse import torch.distributed as dist from tqdm import tqdm from torch.utils.data.distributed import DistributedSampler from torch.nn.parallel import DistributedDataParallel # In[2]: arch_train_dir = '../../Arch_train/' arch_test_dir = '../../Arch_test/' # print("Dataset dir: %s %s" % (arch_train_dir, arch_test_dir)) weight_save_root = "logs" if not os.path.exists(weight_save_root): os.mkdir(weight_save_root) # In[6]: # conv_1_dim = int(sys.argv[1]) if len(sys.argv) > 1 else 64 ### 384 # conv_m_dim = int(sys.argv[2]) if len(sys.argv) > 2 else 64 ### 512 # conv_h_dim = int(sys.argv[3]) if len(sys.argv) > 2 else 64 ### 256 def init_dist_pytorch(args, backend="nccl"): args.rank = int(os.environ['LOCAL_RANK']) args.ngpus_per_node = torch.cuda.device_count() args.gpu = args.rank args.world_size = args.ngpus_per_node torch.cuda.set_device(args.gpu) dist.init_process_group(backend=backend) def synchronize(): """ Helper function to synchronize (barrier) among all processes when using distributed training """ if not dist.is_available(): return if not dist.is_initialized(): return world_size = dist.get_world_size() if world_size == 1: return dist.barrier() class HAF(nn.Module): def __init__(self,lower_branch,middle_branch,higher_branch,args): super(HAF,self).__init__() ### add batch norm # self.conv_1=nn.Sequential( # lower_branch, # nn.UpsamplingNearest2d(scale_factor=2), # nn.Conv2d(256, args.branch_1_dim, kernel_size=1), ### 384 # 64 # nn.BatchNorm2d(args.branch_1_dim) # ) # self.conv_m=nn.Sequential( # middle_branch, # nn.UpsamplingNearest2d(scale_factor=4), # nn.Conv2d(512, args.branch_m_dim, kernel_size=1), ### 512 # 64 # nn.BatchNorm2d(args.branch_m_dim) # ) # self.conv_h=nn.Sequential( # higher_branch, # nn.UpsamplingNearest2d(scale_factor=8), # nn.Conv2d(512, args.branch_h_dim, kernel_size=1), ### 256 # 64 # nn.BatchNorm2d(args.branch_h_dim) # ) self.conv_1=nn.Sequential( lower_branch, nn.UpsamplingNearest2d(scale_factor=2), nn.Conv2d(256, args.branch_1_dim, kernel_size=1) ### 384 # 64 ) self.conv_m=nn.Sequential( middle_branch, nn.UpsamplingNearest2d(scale_factor=4), nn.Conv2d(512, args.branch_m_dim, kernel_size=1) ### 512 # 64 ) self.conv_h=nn.Sequential( higher_branch, nn.UpsamplingNearest2d(scale_factor=8), nn.Conv2d(512, args.branch_h_dim, kernel_size=1) ### 256 # 64 ) # self.fc=nn.Sequential( # nn.Linear(in_features=1024*(args.branch_1_dim+args.branch_m_dim+args.branch_h_dim), out_features=4096, bias=True), ### 196608 # nn.ReLU(inplace=True), # nn.Dropout(p=0.5, inplace=False), # nn.Linear(in_features=4096, out_features=4096, bias=True), # nn.ReLU(inplace=True), # nn.Dropout(p=0.5, inplace=False), # nn.Linear(in_features=4096, out_features=1000, bias=True) ### 1000 # ) self.gap = nn.AdaptiveMaxPool2d(1) self.fc=nn.Sequential( nn.Linear(in_features=args.branch_1_dim+args.branch_m_dim+args.branch_h_dim, out_features=2048, bias=True), nn.ReLU(inplace=True), nn.Dropout(p=0.5, inplace=False), nn.Linear(in_features=2048, out_features=1000, bias=True) ### 1000 ) def forward(self, x): # print(x.shape) h_x = self.conv_1(x) m_x = self.conv_m(x) l_x = self.conv_h(x) # ## concat features out = torch.cat((l_x,m_x,h_x), 1) # out=F.relu(out) # out = out.view(out.size(0), -1)# flatten out = self.gap(out) out = out.view(out.size(0), -1) out=self.fc(out) return out def batch_gd(model, criterion, optimizer, train_loader, test_loader, epochs, device, args): train_losses = np.zeros(epochs) test_losses = np.zeros(epochs) best_test_acc = 0 for it in range(epochs): t0 = datetime.now() train_loss = [] model.train() for inputs, targets in tqdm(train_loader, desc="%d/%d (GPU-%d)" % (it+1, epochs, args.gpu)): # move data to GPU inputs, targets = inputs.to(device), targets.to(device) # zero the parameter gradients optimizer.zero_grad() # Forward pass outputs = model(inputs) loss = criterion(outputs, targets) # Backward and optimize loss.backward() optimizer.step() train_loss.append(loss.item()) model.eval() test_loss = [] n_test_correct = 0. n_test_total = 0. n_train_correct = 0. n_train_total = 0. for inputs, targets in test_loader: inputs, targets = inputs.to(device), targets.to(device) outputs = model(inputs) _, predictions = torch.max(outputs, 1) loss = criterion(outputs, targets) test_loss.append(loss.item()) n_test_correct += (predictions == targets).sum().item() n_test_total+= targets.shape[0] test_acc = n_test_correct / n_test_total test_loss = np.mean(test_loss) synchronize() # torch.save(model.state_dict(), os.path.join(weight_save_path, "model_%d.pth" % (it+1))) if test_acc > best_test_acc: if (args.rank==0): torch.save(model.module.conv_1.state_dict(), os.path.join(weight_save_root, "haf_vgg16_conv_1_dim-%d.pth" % args.branch_1_dim)) torch.save(model.module.conv_m.state_dict(), os.path.join(weight_save_root, "haf_vgg16_conv_m_dim-%d.pth" % args.branch_m_dim)) torch.save(model.module.conv_h.state_dict(), os.path.join(weight_save_root, "haf_vgg16_conv_h_dim-%d.pth" % args.branch_h_dim)) print("model weights are saved to haf_vgg16_conv_1_dim-%d.pth, haf_vgg16_conv_m_dim-%d.pth, haf_vgg16_conv_h_dim-%d.pth" % (args.branch_1_dim, args.branch_m_dim, args.branch_h_dim) ) best_test_acc = test_acc # Get train loss and test loss train_loss = np.mean(train_loss) # a little misleading if it % args.test_epoch != 0: continue for inputs, targets in train_loader: inputs, targets = inputs.to(device), targets.to(device) outputs = model(inputs) _, predictions = torch.max(outputs, 1) n_train_correct += (predictions == targets).sum().item() n_train_total+= targets.shape[0] # Save losses synchronize() train_acc = n_train_correct / n_train_total train_losses[it] = train_loss test_losses[it] = test_loss dt = datetime.now() - t0 # print(f'Epoch {it+1}/{epochs}, Train Loss: {train_loss:.4f}, Train Acc:{train_acc:.4f},\ # Test Loss: {test_loss:.4f}, Test Acc:{test_acc:.4f}') print('Epoch %d/%d, Train Loss: %f, Train Acc:%f, Test Loss: %f, Test Acc:%f' % (it+1, epochs, train_loss, train_acc, test_loss, test_acc)) return train_losses, test_losses def main_worker(args): global start_epoch, best_recall5 init_dist_pytorch(args) synchronize() print("Use GPU: {} for training, rank no.{} of world_size {}" .format(args.gpu, args.rank, args.world_size)) if (args.rank==0): # sys.stdout = Logger(osp.join(args.logs_dir, 'log_feature_branch.txt')) print("==========\nArgs:{}\n==========".format(args)) # In[3]: # Note: normalize mean and std are standardized for ImageNet # https://github.com/pytorch/examples/blob/97304e232807082c2e7b54c597615dc0ad8f6173/imagenet/main.py#L197-L198 train_transform = transforms.Compose([ transforms.Resize(size=(128,128)), transforms.ToTensor() ]) test_transform = transforms.Compose([ transforms.Resize(size=(128,128)), transforms.ToTensor() ]) # print("Loading dataset") train_dataset = datasets.ImageFolder( arch_train_dir, transform=train_transform ) test_dataset = datasets.ImageFolder( arch_test_dir, transform=train_transform ) if (args.rank==0): print("train dataset size:", len(train_dataset.imgs)) train_data_sampler = DistributedSampler(train_dataset, num_replicas=args.world_size, rank=dist.get_rank()) test_data_sampler = DistributedSampler(test_dataset, num_replicas=args.world_size, rank=dist.get_rank()) batch_size = 16 # train_loader = torch.utils.data.DataLoader( # train_dataset, # batch_size=batch_size, # sampler=train_data_sampler, # shuffle=True # ) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=batch_size, sampler=train_data_sampler ) test_loader = torch.utils.data.DataLoader( test_dataset, batch_size=batch_size, sampler=test_data_sampler ) # In[4]: # for inputs,tars in train_loader: # print(inputs[0].shape) # plt.imshow(inputs[0].permute(1,2,0)) # print(tars[0]) # break # K=0 # # print(os.getcwd()) # for i in os.listdir(arch_test_dir): # K+=1 # print(K) # In[5]: # Define the model pre_model = models.vgg16(pretrained=True) features=pre_model.classifier[0].in_features # pre_model lower_branch=pre_model.features[:17] ### 16,16-- 2 middle_branch=pre_model.features[:24] ### 8,8-- 4 higher_branch=pre_model.features ### 4,4-- 8 for param in lower_branch.parameters(): param.requires_grad = False for param in middle_branch.parameters(): param.requires_grad = False for param in higher_branch.parameters(): param.requires_grad = False haf = HAF(lower_branch,middle_branch,higher_branch,args) device = torch.device("cuda:%d" % args.gpu if torch.cuda.is_available() else "cpu") # print(device) # haf.to(device) haf.cuda(args.gpu) haf = DistributedDataParallel(haf, device_ids=[args.gpu], output_device=args.gpu, find_unused_parameters=True) # In[9]: criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, haf.parameters()), lr=0.0001, betas=(0.9, 0.999), eps=1e-08, weight_decay=1e-5) train_losses, test_losses = batch_gd( haf, criterion, optimizer, train_loader, test_loader, epochs=100, device=device, args=args ) # c=0 # for i,t in train_loader: # plt.imshow(i[3].permute(1,2,0)) # outs=cnn_model(i[3].unsqueeze(0).to(device)) # _,pred=torch.max(outs,1) # print(pred == t[3]) # plt.title(f'Pred:{pred.cpu().numpy()}---Label:{t[3]}') # break # # In[ ]: # plt.plot(train_losses, label='train loss') # plt.plot(test_losses, label='test loss') # plt.legend() # plt.show() # # In[ ]: # torch.save(cnn_model.state_dict(),"trained_arc.pt") def main(): args = parser.parse_args() main_worker(args) if __name__ == '__main__': parser = argparse.ArgumentParser(description="NetVLAD/SARE training") parser.add_argument('--launcher', type=str, choices=['none', 'pytorch', 'slurm'], default='none', help='job launcher') parser.add_argument('--tcp-port', type=str, default='5017') parser.add_argument('--branch-1-dim', type=int, default=64) parser.add_argument('--branch-m-dim', type=int, default=64) parser.add_argument('--branch-h-dim', type=int, default=64) parser.add_argument('--test-epoch', type=int, default=5) main()
[ "torch.distributed.is_initialized", "os.mkdir", "torch.nn.Dropout", "argparse.ArgumentParser", "torch.nn.AdaptiveMaxPool2d", "torch.cat", "torch.cuda.device_count", "numpy.mean", "torch.distributed.get_world_size", "os.path.join", "torch.utils.data.DataLoader", "torch.distributed.get_rank", "torch.nn.parallel.DistributedDataParallel", "os.path.exists", "torch.nn.Linear", "torch.cuda.set_device", "torch.distributed.is_available", "torchvision.models.vgg16", "datetime.datetime.now", "tqdm.tqdm", "torch.nn.Conv2d", "torchvision.datasets.ImageFolder", "torch.max", "torch.cuda.is_available", "torchvision.transforms.Resize", "torch.distributed.init_process_group", "torch.nn.UpsamplingNearest2d", "torch.nn.ReLU", "torch.distributed.barrier", "numpy.zeros", "torch.nn.CrossEntropyLoss", "torchvision.transforms.ToTensor" ]
[((670, 702), 'os.path.exists', 'os.path.exists', (['weight_save_root'], {}), '(weight_save_root)\n', (684, 702), False, 'import sys, os\n'), ((708, 734), 'os.mkdir', 'os.mkdir', (['weight_save_root'], {}), '(weight_save_root)\n', (716, 734), False, 'import sys, os\n'), ((1076, 1101), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (1099, 1101), False, 'import torch\n'), ((1173, 1204), 'torch.cuda.set_device', 'torch.cuda.set_device', (['args.gpu'], {}), '(args.gpu)\n', (1194, 1204), False, 'import torch\n'), ((1209, 1249), 'torch.distributed.init_process_group', 'dist.init_process_group', ([], {'backend': 'backend'}), '(backend=backend)\n', (1232, 1249), True, 'import torch.distributed as dist\n'), ((1501, 1522), 'torch.distributed.get_world_size', 'dist.get_world_size', ([], {}), '()\n', (1520, 1522), True, 'import torch.distributed as dist\n'), ((1566, 1580), 'torch.distributed.barrier', 'dist.barrier', ([], {}), '()\n', (1578, 1580), True, 'import torch.distributed as dist\n'), ((4266, 4282), 'numpy.zeros', 'np.zeros', (['epochs'], {}), '(epochs)\n', (4274, 4282), True, 'import numpy as np\n'), ((4299, 4315), 'numpy.zeros', 'np.zeros', (['epochs'], {}), '(epochs)\n', (4307, 4315), True, 'import numpy as np\n'), ((8152, 8215), 'torchvision.datasets.ImageFolder', 'datasets.ImageFolder', (['arch_train_dir'], {'transform': 'train_transform'}), '(arch_train_dir, transform=train_transform)\n', (8172, 8215), False, 'from torchvision import datasets, transforms, models\n'), ((8257, 8319), 'torchvision.datasets.ImageFolder', 'datasets.ImageFolder', (['arch_test_dir'], {'transform': 'train_transform'}), '(arch_test_dir, transform=train_transform)\n', (8277, 8319), False, 'from torchvision import datasets, transforms, models\n'), ((8866, 8964), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['train_dataset'], {'batch_size': 'batch_size', 'sampler': 'train_data_sampler'}), '(train_dataset, batch_size=batch_size, sampler=\n train_data_sampler)\n', (8893, 8964), False, 'import torch\n'), ((9008, 9104), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['test_dataset'], {'batch_size': 'batch_size', 'sampler': 'test_data_sampler'}), '(test_dataset, batch_size=batch_size, sampler=\n test_data_sampler)\n', (9035, 9104), False, 'import torch\n'), ((9472, 9501), 'torchvision.models.vgg16', 'models.vgg16', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (9484, 9501), False, 'from torchvision import datasets, transforms, models\n'), ((10193, 10301), 'torch.nn.parallel.DistributedDataParallel', 'DistributedDataParallel', (['haf'], {'device_ids': '[args.gpu]', 'output_device': 'args.gpu', 'find_unused_parameters': '(True)'}), '(haf, device_ids=[args.gpu], output_device=args.gpu,\n find_unused_parameters=True)\n', (10216, 10301), False, 'from torch.nn.parallel import DistributedDataParallel\n'), ((10330, 10351), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (10349, 10351), True, 'import torch.nn as nn\n'), ((11336, 11396), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""NetVLAD/SARE training"""'}), "(description='NetVLAD/SARE training')\n", (11359, 11396), False, 'import argparse\n'), ((1399, 1418), 'torch.distributed.is_available', 'dist.is_available', ([], {}), '()\n', (1416, 1418), True, 'import torch.distributed as dist\n'), ((1446, 1467), 'torch.distributed.is_initialized', 'dist.is_initialized', ([], {}), '()\n', (1465, 1467), True, 'import torch.distributed as dist\n'), ((3471, 3494), 'torch.nn.AdaptiveMaxPool2d', 'nn.AdaptiveMaxPool2d', (['(1)'], {}), '(1)\n', (3491, 3494), True, 'import torch.nn as nn\n'), ((3962, 3991), 'torch.cat', 'torch.cat', (['(l_x, m_x, h_x)', '(1)'], {}), '((l_x, m_x, h_x), 1)\n', (3971, 3991), False, 'import torch\n'), ((4378, 4392), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4390, 4392), False, 'from datetime import datetime\n'), ((4458, 4528), 'tqdm.tqdm', 'tqdm', (['train_loader'], {'desc': "('%d/%d (GPU-%d)' % (it + 1, epochs, args.gpu))"}), "(train_loader, desc='%d/%d (GPU-%d)' % (it + 1, epochs, args.gpu))\n", (4462, 4528), False, 'from tqdm import tqdm\n'), ((5447, 5465), 'numpy.mean', 'np.mean', (['test_loss'], {}), '(test_loss)\n', (5454, 5465), True, 'import numpy as np\n'), ((6321, 6340), 'numpy.mean', 'np.mean', (['train_loss'], {}), '(train_loss)\n', (6328, 6340), True, 'import numpy as np\n'), ((2490, 2528), 'torch.nn.UpsamplingNearest2d', 'nn.UpsamplingNearest2d', ([], {'scale_factor': '(2)'}), '(scale_factor=2)\n', (2512, 2528), True, 'import torch.nn as nn\n'), ((2538, 2586), 'torch.nn.Conv2d', 'nn.Conv2d', (['(256)', 'args.branch_1_dim'], {'kernel_size': '(1)'}), '(256, args.branch_1_dim, kernel_size=1)\n', (2547, 2586), True, 'import torch.nn as nn\n'), ((2669, 2707), 'torch.nn.UpsamplingNearest2d', 'nn.UpsamplingNearest2d', ([], {'scale_factor': '(4)'}), '(scale_factor=4)\n', (2691, 2707), True, 'import torch.nn as nn\n'), ((2717, 2765), 'torch.nn.Conv2d', 'nn.Conv2d', (['(512)', 'args.branch_m_dim'], {'kernel_size': '(1)'}), '(512, args.branch_m_dim, kernel_size=1)\n', (2726, 2765), True, 'import torch.nn as nn\n'), ((2848, 2886), 'torch.nn.UpsamplingNearest2d', 'nn.UpsamplingNearest2d', ([], {'scale_factor': '(8)'}), '(scale_factor=8)\n', (2870, 2886), True, 'import torch.nn as nn\n'), ((2896, 2944), 'torch.nn.Conv2d', 'nn.Conv2d', (['(512)', 'args.branch_h_dim'], {'kernel_size': '(1)'}), '(512, args.branch_h_dim, kernel_size=1)\n', (2905, 2944), True, 'import torch.nn as nn\n'), ((3532, 3647), 'torch.nn.Linear', 'nn.Linear', ([], {'in_features': '(args.branch_1_dim + args.branch_m_dim + args.branch_h_dim)', 'out_features': '(2048)', 'bias': '(True)'}), '(in_features=args.branch_1_dim + args.branch_m_dim + args.\n branch_h_dim, out_features=2048, bias=True)\n', (3541, 3647), True, 'import torch.nn as nn\n'), ((3650, 3671), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (3657, 3671), True, 'import torch.nn as nn\n'), ((3683, 3715), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': '(0.5)', 'inplace': '(False)'}), '(p=0.5, inplace=False)\n', (3693, 3715), True, 'import torch.nn as nn\n'), ((3727, 3784), 'torch.nn.Linear', 'nn.Linear', ([], {'in_features': '(2048)', 'out_features': '(1000)', 'bias': '(True)'}), '(in_features=2048, out_features=1000, bias=True)\n', (3736, 3784), True, 'import torch.nn as nn\n'), ((5182, 5203), 'torch.max', 'torch.max', (['outputs', '(1)'], {}), '(outputs, 1)\n', (5191, 5203), False, 'import torch\n'), ((6579, 6600), 'torch.max', 'torch.max', (['outputs', '(1)'], {}), '(outputs, 1)\n', (6588, 6600), False, 'import torch\n'), ((6878, 6892), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (6890, 6892), False, 'from datetime import datetime\n'), ((7893, 7927), 'torchvision.transforms.Resize', 'transforms.Resize', ([], {'size': '(128, 128)'}), '(size=(128, 128))\n', (7910, 7927), False, 'from torchvision import datasets, transforms, models\n'), ((7940, 7961), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (7959, 7961), False, 'from torchvision import datasets, transforms, models\n'), ((8024, 8058), 'torchvision.transforms.Resize', 'transforms.Resize', ([], {'size': '(128, 128)'}), '(size=(128, 128))\n', (8041, 8058), False, 'from torchvision import datasets, transforms, models\n'), ((8071, 8092), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (8090, 8092), False, 'from torchvision import datasets, transforms, models\n'), ((8523, 8538), 'torch.distributed.get_rank', 'dist.get_rank', ([], {}), '()\n', (8536, 8538), True, 'import torch.distributed as dist\n'), ((8632, 8647), 'torch.distributed.get_rank', 'dist.get_rank', ([], {}), '()\n', (8645, 8647), True, 'import torch.distributed as dist\n'), ((10081, 10106), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (10104, 10106), False, 'import torch\n'), ((5691, 5777), 'os.path.join', 'os.path.join', (['weight_save_root', "('haf_vgg16_conv_1_dim-%d.pth' % args.branch_1_dim)"], {}), "(weight_save_root, 'haf_vgg16_conv_1_dim-%d.pth' % args.\n branch_1_dim)\n", (5703, 5777), False, 'import sys, os\n'), ((5827, 5913), 'os.path.join', 'os.path.join', (['weight_save_root', "('haf_vgg16_conv_m_dim-%d.pth' % args.branch_m_dim)"], {}), "(weight_save_root, 'haf_vgg16_conv_m_dim-%d.pth' % args.\n branch_m_dim)\n", (5839, 5913), False, 'import sys, os\n'), ((5963, 6049), 'os.path.join', 'os.path.join', (['weight_save_root', "('haf_vgg16_conv_h_dim-%d.pth' % args.branch_h_dim)"], {}), "(weight_save_root, 'haf_vgg16_conv_h_dim-%d.pth' % args.\n branch_h_dim)\n", (5975, 6049), False, 'import sys, os\n')]
import numpy as np from termcolor import colored from pyfiglet import * print(colored("Advent of Code - Day 25", "yellow").center(80, "-")) print(colored(figlet_format("Sea Cucumber",font="small",justify="center"), 'green')) print(colored("Output","yellow").center(80, "-")) g = np.array([[{".": 0, ">": 2, "v": 1}[a] for a in a.strip()] for a in open("../Input/day25.txt")]) i = 0 while True: i += 1 a = (g == 2) & (np.roll(g, -1, 1) == 0) g[a], g[np.roll(a, 1, 1)] = 0, 2 b = (g == 1) & (np.roll(g, -1, 0) == 0) g[b], g[np.roll(b, 1, 0)] = 0, 1 if not (a|b).any(): break print("\nPuzzle 1: ",i) print("Puzzle 1: Completed :))",end = "\n\n") print(colored("=".center(71, "="), "yellow"))
[ "termcolor.colored", "numpy.roll" ]
[((78, 122), 'termcolor.colored', 'colored', (['"""Advent of Code - Day 25"""', '"""yellow"""'], {}), "('Advent of Code - Day 25', 'yellow')\n", (85, 122), False, 'from termcolor import colored\n'), ((231, 258), 'termcolor.colored', 'colored', (['"""Output"""', '"""yellow"""'], {}), "('Output', 'yellow')\n", (238, 258), False, 'from termcolor import colored\n'), ((421, 438), 'numpy.roll', 'np.roll', (['g', '(-1)', '(1)'], {}), '(g, -1, 1)\n', (428, 438), True, 'import numpy as np\n'), ((454, 470), 'numpy.roll', 'np.roll', (['a', '(1)', '(1)'], {}), '(a, 1, 1)\n', (461, 470), True, 'import numpy as np\n'), ((496, 513), 'numpy.roll', 'np.roll', (['g', '(-1)', '(0)'], {}), '(g, -1, 0)\n', (503, 513), True, 'import numpy as np\n'), ((529, 545), 'numpy.roll', 'np.roll', (['b', '(1)', '(0)'], {}), '(b, 1, 0)\n', (536, 545), True, 'import numpy as np\n')]
import numpy as np import os import json import quantities as pq from mpi4py import MPI import elephant.spade as spade import argparse import yaml from utils import mkdirp, split_path with open("configfile.yaml", 'r') as stream: config = yaml.load(stream) # max. time window width in number of bins winlen = config['winlen'] # resolution in ms binsize = config['binsize'] * pq.ms # Multiple of the binsize to dither data dither = config['dither'] * binsize # number of surrogates for psf n_surr = config['n_surr'] # Spectrum ('#' for 2d-spectrum '3d#' for 3d-spectrum spectrum = config['spectrum'] # Minimum size of pattern to analyze min_spikes = config['min_xi'] # Minimum num occ pattern to analyze min_occ = config['min_occ'] param = {'winlen':winlen, 'n_surr':n_surr, 'binsize':binsize, 'spectrum':spectrum, 'min_spikes':min_spikes, 'min_occ':min_occ, 'dither':dither} # Parsing data parameter parser = argparse.ArgumentParser(description='Compute spade on artificial data ' 'for the given winlen and spectrum parameters') parser.add_argument('data_idx', metavar='data_idx', type=int, help='idx of the data to analyze (integer between 0 and 3)') parser.add_argument('xi', metavar='xi', type=int, help='size of injected pattern (integer between 3 and 10') parser.add_argument('occ', metavar='occ', type=int, help='number of occurrences of injected pattern (integer between 3 and 10') args = parser.parse_args() data_idx = args.data_idx xi = args.xi occ = args.occ results = {} # Loading data data_path = '../data/stp_data%i.npy' % data_idx if not os.path.exists(data_path): raise ValueError('Data path not existing') datafile = np.load(data_path, encoding='latin1').item() # MPI parameters comm = MPI.COMM_WORLD # create MPI communicator rank = comm.Get_rank() # get rank of current MPI task size = comm.Get_size() # get tot number of MPI tasks print(size) # Analyzing the 100 realization of data for rep in range(100): print(("Doing rep", rep)) # Selecting data spikedata = datafile['sts_%iocc_%ixi' % (occ, xi)][rep] # SPADE analysis if xi==0 and occ ==0 and rep == 0: output = spade.spade(spikedata, binsize, winlen, dither=dither, n_surr=n_surr, min_spikes=min_spikes, min_occ=min_occ, spectrum=spectrum) else: output = spade.spade(spikedata, binsize, winlen, dither=dither, n_surr=0, min_spikes=min_spikes, min_occ=min_occ, spectrum=spectrum) # Storing data if rank == 0: results[rep] = output if rank == 0: # Storing results path = '../results/results_data{}'.format(data_idx) path_temp = './' for folder in split_path(path): path_temp = path_temp + '/' + folder mkdirp(path_temp) if xi == 0 and occ ==0: np.save( path + '/result_ind'.format(xi, occ), [results, param]) else: np.save( path+'/result_xi{}_occ{}'.format(xi,occ), [results, param])
[ "utils.mkdirp", "yaml.load", "numpy.load", "argparse.ArgumentParser", "os.path.exists", "elephant.spade.spade", "utils.split_path" ]
[((926, 1052), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Compute spade on artificial data for the given winlen and spectrum parameters"""'}), "(description=\n 'Compute spade on artificial data for the given winlen and spectrum parameters'\n )\n", (949, 1052), False, 'import argparse\n'), ((244, 261), 'yaml.load', 'yaml.load', (['stream'], {}), '(stream)\n', (253, 261), False, 'import yaml\n'), ((1673, 1698), 'os.path.exists', 'os.path.exists', (['data_path'], {}), '(data_path)\n', (1687, 1698), False, 'import os\n'), ((2796, 2812), 'utils.split_path', 'split_path', (['path'], {}), '(path)\n', (2806, 2812), False, 'from utils import mkdirp, split_path\n'), ((1758, 1795), 'numpy.load', 'np.load', (['data_path'], {'encoding': '"""latin1"""'}), "(data_path, encoding='latin1')\n", (1765, 1795), True, 'import numpy as np\n'), ((2244, 2376), 'elephant.spade.spade', 'spade.spade', (['spikedata', 'binsize', 'winlen'], {'dither': 'dither', 'n_surr': 'n_surr', 'min_spikes': 'min_spikes', 'min_occ': 'min_occ', 'spectrum': 'spectrum'}), '(spikedata, binsize, winlen, dither=dither, n_surr=n_surr,\n min_spikes=min_spikes, min_occ=min_occ, spectrum=spectrum)\n', (2255, 2376), True, 'import elephant.spade as spade\n'), ((2416, 2544), 'elephant.spade.spade', 'spade.spade', (['spikedata', 'binsize', 'winlen'], {'dither': 'dither', 'n_surr': '(0)', 'min_spikes': 'min_spikes', 'min_occ': 'min_occ', 'spectrum': 'spectrum'}), '(spikedata, binsize, winlen, dither=dither, n_surr=0, min_spikes\n =min_spikes, min_occ=min_occ, spectrum=spectrum)\n', (2427, 2544), True, 'import elephant.spade as spade\n'), ((2867, 2884), 'utils.mkdirp', 'mkdirp', (['path_temp'], {}), '(path_temp)\n', (2873, 2884), False, 'from utils import mkdirp, split_path\n')]
# **************************************************************************** # # # # ::: :::::::: # # config.py :+: :+: :+: # # +:+ +:+ +:+ # # By: winshare <<EMAIL>> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2020/02/28 11:45:40 by winshare #+# #+# # # Updated: 2020/05/28 15:01:24 by winshare ### ########.fr # # # # **************************************************************************** # # Copyright 2020 winshare # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import os import json import numpy as np import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import torch import torchvision.datasets as dataset # ---------------------------- Official Reference ---------------------------- # from Data.DataSets.NPY.segmentation_dataset import Costum_NPY_DataSet from Data.DataSets.CitysCapes.cityscapes import CityscapesSegmentation from Data.DataSets.COCO.coco import CocoDataset from Data.DataSets.PascalVoc.pascal import VOCSegmentation # ------------------------------ Local Reference ----------------------------- # class CFG(): def __init__(self): # ---------------------------------------------------------------------------- # # init process # # ---------------------------------------------------------------------------- # for i in range(5): print("#####------------------------------------------------------------------#####") print("#####-------------------------<===== WSNET =====>----------------------#####") for i in range(5): print("#####------------------------------------------------------------------#####") print("\n\n# -----Decode Config File :",self.configfile,"-----#") # ---------------------------------------------------------------------------- # # init process # # ---------------------------------------------------------------------------- # # ---------------------------------------------------------------------------- # # Pytorch Function Dictionary # # ---------------------------------------------------------------------------- # self.datasets_function_dict={ "Classification":{ "MINST":dataset.MNIST, "FashionMINST":dataset.FashionMNIST, "KMINST":dataset.KMNIST, "EMINST":dataset.EMNIST, "CIFAR10":dataset.CIFAR10, "CIFAR100":dataset.CIFAR100, "ImageNet":dataset.ImageNet }, "Detection":{ "CocoDetection":CocoDataset, "VOC_Detection":dataset.VOCDetection }, "Segmentation":{ "VOC_Segmentation":dataset.VOCSegmentation, "Cityscapes":dataset.Cityscapes, "Costum_NPY_DataSet":Costum_NPY_DataSet, "CocoSegmentation":CocoDataset }, "Caption":{ "CocoCaptions":dataset.CocoCaptions }, "InstenceSegmentation":{ "CocoDetection":CocoDataset } } self.dataset_support_list=self.datasets_function_dict.keys() # ---------------------------------------------------------------------------- # self.OptimDict={ "SGD":optim.SGD, "ASGD":optim.ASGD, "Adam":optim.Adam, "Adadelta":optim.Adadelta, "Adagrad":optim.Adagrad, "AdamW":optim.AdamW, "LBFGS":optim.LBFGS, "RMSprop":optim.RMSprop, "SparseAdam":optim.SparseAdam, "Adamax":optim.Adamax } # ---------------------------------------------------------------------------- # self.Loss_Function_Dict={ "AdaptiveLogSoftmaxWithLoss":nn.AdaptiveLogSoftmaxWithLoss ,"BCELoss":nn.BCELoss ,"BCEWithLogitsLoss":nn.BCEWithLogitsLoss ,"CosineEmbeddingLoss":nn.CosineEmbeddingLoss ,"CrossEntropyLoss":nn.CrossEntropyLoss ,"CTCLoss":nn.CTCLoss ,"cosine_embedding_loss":F.cosine_embedding_loss ,"ctc_loss":F.ctc_loss ,"hinge_embedding_loss":F.hinge_embedding_loss ,"l1_loss":F.l1_loss ,"margin_ranking_loss":F.margin_ranking_loss ,"mse_loss":F.mse_loss ,"multi_margin_loss":F.mse_loss ,"multilabel_margin_loss":F.multilabel_margin_loss ,"multilabel_soft_margin_loss":F.multilabel_margin_loss ,"nll_loss":F.nll_loss ,"poisson_nll_loss":F.poisson_nll_loss ,"smooth_l1_loss":F.smooth_l1_loss ,"soft_margin_loss":F.soft_margin_loss ,"triplet_margin_loss":F.triplet_margin_loss ,"HingeEmbeddingLoss":nn.HingeEmbeddingLoss ,"KLDivLoss":nn.KLDivLoss ,"L1Loss":nn.L1Loss ,"MarginRankingLoss":nn.MarginRankingLoss ,"MSELoss":nn.MSELoss ,"MultiLabelMarginLoss":nn.MultiLabelMarginLoss ,"MultiLabelSoftMarginLoss":nn.MultiLabelSoftMarginLoss ,"MultiMarginLoss":nn.MultiMarginLoss ,"NLLLoss":nn.MultiMarginLoss ,"PoissonNLLLoss":nn.PoissonNLLLoss ,"SmoothL1Loss":nn.SmoothL1Loss ,"SoftMarginLoss":nn.SoftMarginLoss ,"TripletMarginLoss":nn.TripletMarginLoss } # ---------------------------------------------------------------------------- # self.Lr_Dict={ "StepLR":optim.lr_scheduler.StepLR, "MultiStepLR":optim.lr_scheduler.MultiStepLR, "ExponentialLR":optim.lr_scheduler.ExponentialLR, "CosineAnnealingLR":optim.lr_scheduler.CosineAnnealingLR, "ReduceLROnPlateau":optim.lr_scheduler.ReduceLROnPlateau, "CyclicLR":optim.lr_scheduler.CyclicLR, "OneCycleLR":optim.lr_scheduler.OneCycleLR, "CosineAnnealingWarmRestarts":optim.lr_scheduler.CosineAnnealingWarmRestarts } # ---------------------------------------------------------------------------- # # Config in 3 Level # # ---------------------------------------------------------------------------- # # -------------------------------- File Level -------------------------------- # self.__configfile=self.configfile self.__json=json.load(open(self.__configfile,'r')) self.usegpu=False self.MissionType=self.__json['MissionType'] self.InstanceID=self.__json['instance_id'] self.Content=self.__json['content'] # ------------------------------- Second Level ------------------------------- # self.Net=self.Content['Net'] self.DataSetConfig=self.Content['Dataset'] self.Config=self.Content['Config'] print('\n\n# ---------------------------------- config ---------------------------------- #') print("# ------------------------------ NETWORK CONFIG ------------------------------ #") self.print_dict(self.Net) print("# ------------------------------ NETWORK CONFIG ------------------------------ #") print("# ------------------------------ DATASET CONFIG ------------------------------ #") self.print_dict(self.DataSetConfig) print("# ------------------------------ DATASET CONFIG ------------------------------ #") print("# ------------------------------ GENERAL CONFIG ------------------------------ #") self.print_dict(self.Config) print("# ------------------------------ GENERAL CONFIG ------------------------------ #") print('# ---------------------------------- config ---------------------------------- #') # -------------------------------- Third Level ------------------------------- # # ---------------------------------------------------------------------------- # # NET # # ---------------------------------------------------------------------------- # # self.NetType=self.Net['NetType'] self.DefaultNetwork=self.Net["DefaultNetwork"] self.BatchSize=self.Net['BatchSize'] if self.Net['BackBone']=='None': self.BackBone=None else: self.BackBone=self.Net['BackBone'] self.NetType=self.Net["NetType"] # --------------------------------- Optimizer -------------------------------- # self.optimizer=self.OptimDict[self.Net['Optimizer']] self.learning_rate=self.Net['learning_rate'] self.momentum=self.Net['momentum'] self.weight_decay=self.Net['weight_decay'] # ------------------------------- lr_scheduler ------------------------------- # self.lr_scheduler=self.Net['lr_scheduler'] self.lr_steps=self.Net['lr_steps'] self.lr_gamma=self.Net['lr_gamma'] self.lr_scheduler=self.Lr_Dict[self.lr_scheduler] self.class_num=self.Net['class_num'] # ------------------------------- Loss Function ------------------------------ # self.Loss_Function=self.Loss_Function_Dict[self.Net['Loss_Function']]() # ---------------------------------------------------------------------------- # # Dataset # # ---------------------------------------------------------------------------- # self.DataSetType=self.DataSetConfig['Type'] self.DataSet_Root=self.DataSetConfig['root'] self.Dataset_Train_file=os.path.join(self.DataSet_Root,self.DataSetConfig['train_index_file']) self.Dataset_Val_file=os.path.join(self.DataSet_Root,self.DataSetConfig['val_index_file']) self.DefaultDataset=self.DataSetConfig['DefaultDataset'] self.NPY=self.DataSetConfig["NPY"] if os.path.exists(self.NPY): self.NPY_Data=np.load(self.NPY,allow_pickle=True) self.SFT_Enable=self.DataSetConfig["SFT_Enable"] # --------------------------------- Transform (Aborted)------------------------# # ---------------------------------------------------------------------------- # """ Because the defalut detection network has transform flow so the image list should include 3d tensors [ [C, H, W], [C, H, W]..... ] Target should be list of dict : { boxes: list of box tensor[n,4] (float32) masks: list of segmentation mask points [n,n] (float32) keypoints: list of key pointss[n,n] (float32) labels: list of index of label[n] (int64) } For Default Detection: The transformations it perform are: - input normalization (mean subtraction and std division) - input / target resizing to match min_size / max_size It returns a ImageList for the inputs, and a List[Dict[Tensor]] for the targets """ # print('\n\n--------------------------------- Transform --------------------------------') # self.TransformDict=self.DataSetConfig['Transform'] # functionlist=[list(i.keys())[0] for i in self.TransformDict] # paralist=[list(i.values())[0] for i in self.TransformDict] # self.transforms=GeneralTransform(self.TransformDict) # ---------------------------------------------------------------------------- # # Config # # ---------------------------------------------------------------------------- # self.DistributedDataParallel=self.Config['DistributedDataParallel'] self.resume=self.Config['Resume'] self.checkpoint=self.Config['checkpoint_path'] self.MultiScale_Training=self.Config['multiscale_training'] self.logdir=self.Config['logdir'] self.devices=self.Config['devices'] self.pre_estimation=self.Config['pre_estimation'] if not os.path.exists(self.checkpoint): os.makedirs(self.checkpoint) if self.devices=='GPU': self.usegpu=True self.gpu_id=self.Config['gpu_id'] # os.environ['CUDA_VISIBLE_DEVICES']=str(self.gpu_id) self.device = torch.device("cuda:"+str(self.gpu_id) if torch.cuda.is_available() else "cpu") print('#-----Device:\n',self.device) if self.devices=='CPU': self.device=torch.device("cpu") self.download_pretrain_model=self.Config['down_pretrain_model'] self.visualization=self.Config['visualization'] self.worker_num=self.Config['worker_num'] self.epochs=self.Config['epochs'] self.aspect_ratio_factor=self.Config['group_factor'] print("# ---------------------------------------------------------------------------- #") print("# Configure Class Init Successful #") print("# ---------------------------------------------------------------------------- #") self.Enviroment_Info() # ---------------------------------------------------------------------------- # # Config Class Function # # ---------------------------------------------------------------------------- # def GenerateDefaultConfig(self,mode='detection'): print('Generate Default Config with mode :',mode) def configinfo(self): print('***** Already read Config file ,'+self.__configfile,'*****') print('***** Instance ID : ',self.InstanceID,'*****') print('***** Mission Type : ',self.MissionType,'*****') def Enviroment_Info(self): print("\n\n# --------------------------------- NVCC INFO -------------------------------- #\n\n") os.system('nvcc -V') print("\n\n# --------------------------------- NVCC INFO -------------------------------- #\n\n") print("\n\n# --------------------------------- GPU INFO --------------------------------- #") os.system('nvidia-smi') print("# --------------------------------- GPU INFO --------------------------------- #\n\n") def print_dict(self,d,n=0): length=74 for k,v in d.items(): # print ('\t'*n) if type(v)==type({}): print("%s : {" % k) self.print_dict(v,n+1) else: strl=len(str(k))+len(str(v)) space=length-strl print("# %s : %s" % (k,v)+" "*space+"#") if n!=0: print('\t'*(n-1)+ '}')
[ "numpy.load", "os.makedirs", "os.path.exists", "os.system", "torch.cuda.is_available", "torch.device", "os.path.join" ]
[((11130, 11201), 'os.path.join', 'os.path.join', (['self.DataSet_Root', "self.DataSetConfig['train_index_file']"], {}), "(self.DataSet_Root, self.DataSetConfig['train_index_file'])\n", (11142, 11201), False, 'import os\n'), ((11231, 11300), 'os.path.join', 'os.path.join', (['self.DataSet_Root', "self.DataSetConfig['val_index_file']"], {}), "(self.DataSet_Root, self.DataSetConfig['val_index_file'])\n", (11243, 11300), False, 'import os\n'), ((11419, 11443), 'os.path.exists', 'os.path.exists', (['self.NPY'], {}), '(self.NPY)\n', (11433, 11443), False, 'import os\n'), ((15609, 15629), 'os.system', 'os.system', (['"""nvcc -V"""'], {}), "('nvcc -V')\n", (15618, 15629), False, 'import os\n'), ((15855, 15878), 'os.system', 'os.system', (['"""nvidia-smi"""'], {}), "('nvidia-smi')\n", (15864, 15878), False, 'import os\n'), ((11471, 11507), 'numpy.load', 'np.load', (['self.NPY'], {'allow_pickle': '(True)'}), '(self.NPY, allow_pickle=True)\n', (11478, 11507), True, 'import numpy as np\n'), ((13743, 13774), 'os.path.exists', 'os.path.exists', (['self.checkpoint'], {}), '(self.checkpoint)\n', (13757, 13774), False, 'import os\n'), ((13788, 13816), 'os.makedirs', 'os.makedirs', (['self.checkpoint'], {}), '(self.checkpoint)\n', (13799, 13816), False, 'import os\n'), ((14220, 14239), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (14232, 14239), False, 'import torch\n'), ((14068, 14093), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (14091, 14093), False, 'import torch\n')]
""" measurement.py MeasurementModel wraps up a halo.HaloDensityProfile instance with both a set of observables (e.g., {r, DeltaSigma, DeltaSigma_err}) and a prior on the model parameters of interest. """ from collections import OrderedDict import numpy as np from scipy import optimize from colossus.halo.profile_base import HaloDensityProfile from modds.parameter import Parameter __all__ = ['MeasurementModel'] def lnlike_gauss(q_model, q, q_err): """ Log of Gaussian likelihood. Parameters ---------- q_model : array_like predicted value q : array_like observed value q_err : array_like observational uncertainty Returns ------- lnl : array_like log likehood array, same size as input observations """ var = q_err**2 return -0.5 * (np.log(2 * np.pi * var) + (q - q_model)**2 / var) class MeasurementModel(): """ A wrapped up halo density profile with data constraints and priors. Parameters ---------- profile : halo.profile_bass.HaloDensityProfile observables : dict or iterable Should have keys of 'r', 'q', 'q_err', else it is assumed to be an iterable containing three arrays in the order r, q, q_err. quantity : str One of {'rho', 'M', 'Sigma', 'DeltaSigma'}, with standard colossus units. Denotes volume mass density, enclosed mass, surface density, and surface density deviation (i.e., the weak lensing observable) respectively. parameters : list of colossus.modeling.Parameter instances constants : dict Map from constant name (str) to fixed physical value (float). Should contain redshift (named "z") if not defined as a parameter lnlike : callable, optional Map from (q_model, q, q_err) to log likelihood at each point. Defaults to a Gaussian likelihood, i.e., q ~ N(q_model, q_err**2) priors : iterable, optional List of functions, f(profile, **kwargs) -> log prior. Additional priors to consider (e.g., halo mass concentration relation, See examples in joint_priors.py. Keywords should be either constants or parameters of the model. """ # mapping of inputtable quantities to colossus halo profile function name _quantities = dict(rho='density', density='density', m='enclosedMass', mass='enclosedMass', enclosedmass='enclosedMass', sigma='surfaceDensity', surfacedensity='surfaceDensity', deltasigma='deltaSigma') _obskeys = ['r', 'q', 'q_err'] def __init__(self, profile, observables, quantity, parameters, constants=None, lnlike=lnlike_gauss, priors=None): # check this is an actual halo density profile assert isinstance(profile, HaloDensityProfile) self.profile = profile # check this is an allowed quantity quantity = quantity.replace(' ', '').lower() assert quantity in self._quantities self.quantity = self._quantities[quantity] # construct ordered dict of observables if isinstance(observables, OrderedDict): assert all([key in observables for key in self._obskeys]) self.observables = observables elif isinstance(observables, dict): assert all([key in observables for key in self._obskeys]) self.observables = OrderedDict([(key, observables[key]) for key in self._obskeys]) else: self.observables = OrderedDict(zip(self._obskeys, observables)) # check that everything is a proper parameter assert all([isinstance(p, Parameter) for p in parameters]) self.parameters = OrderedDict([(p.name, p) for p in parameters]) self.ndim = len(parameters) # set default constants to empty dictionary if constants is None: constants = {} self.constants = constants self.lnlike = lnlike self.priors = priors assert ("z" in self.constants) or ("z" in self.parameters) def _get_required_parameters(self, sample): """The parameters the sampler sees are different than what colossus needs. This glues the two together. `sample` is what the sampler sees. """ # construct array for profile prediction new_pars = np.zeros(len(self.profile.par)) for i, required_param in enumerate(self.profile.par_names): try: new_pars[i] = self.constants[required_param] except KeyError: # must be a free parameter, transform if need be p = self.parameters[required_param] # index into values for free parameters idx = list(self.parameters.keys()).index(required_param) if p.transform is None: new_pars[i] = sample[idx] else: # need to do the inverse transform to physical values new_pars[i] = p.inverse_transform(sample[idx]) return new_pars def _get_kwargs(self, sample): """Construct a dictionary of keyword arguments from a point in sample space. Includes constant values. """ kwargs = {} for i, (name, p) in enumerate(self.parameters.items()): if p.transform is not None: kwargs[name] = p.inverse_transform(sample[i]) else: kwargs[name] = sample[i] kwargs = {**kwargs, **self.constants} return kwargs def update(self, sample): """Update the profile with the passed values. Parameters ---------- sample : array_like Size of ndim, values as the sampler would see them (i.e., transformed) Returns ------- bool True if successful """ # set new profile parameters and update new_pars = self._get_required_parameters(sample) if 'z' in self.parameters: # update redshift with new value p = self.parameters['z'] idx = list(self.parameters.keys()).index('z') if p.transform is not None: z = p.inverse_transform(sample[idx]) else: z = sample[idx] self.profile.opt['z'] = z else: assert self.profile.opt['z'] == self.constants['z'] self.profile.setParameterArray(new_pars) try: self.profile.update() return True except: # TODO: catch the specific exception # handle case where the halo density is too small return False def __call__(self, sample, return_lnlike=False, return_profile=False, return_vir=False, return_sp=False, r_grid=None, mdef="vir", log_rsp_search_min=2.5, log_rsp_search_max=3.5): """ Calculate the log posterior probability for the model. Parameters ---------- sample : array_like length ndim array of transformed parameters return_lnlike : bool, optional if True, also return the log likelihood return_profile : bool, optional if True, also return the model interpolated on the specified grid return_vir : bool, optional if True, also return the halo virial mass and concentration return_sp : bool, optional if True, also return the halo splashback radius and steepest slope r_grid : array_like, optional Radial interpolation grid for when caching the posterior prediction mdef : str, optional halo virial mass definition log_rsp_search_min : float, optional log of kpc, minimum radius to search for rsp log_rsp_search_max : float, optional log of kpc, maximum radius to search for rsp Returns ------- lnpost : float log of posterior probability blobs : tuple tuple of optional returns, ordered as (lnlike, profile, Mvir, cvir, rsp, gamma_min) """ return_blobs = np.any([return_lnlike, return_profile, return_vir, return_sp]) # update profile with new values successful_update = self.update(sample) # calculate log prior, returning early on bad values lnp = 0 for i, p in enumerate(self.parameters.values()): lnp += p(sample[i]) if self.priors is not None: for prior in self.priors: lnp += prior(self.profile, **self._get_kwargs(sample)) if not np.isfinite(lnp) or not successful_update: if return_blobs: # construct rejected blobs blobs = [] if return_lnlike: blobs.append(np.nan) if return_profile: blobs.append(np.nan * np.ones(r_grid.shape)) if return_vir: blobs.append(np.nan) blobs.append(np.nan) if return_sp: blobs.append(np.nan) blobs.append(np.nan) return -np.inf, tuple(blobs) # calculate log likelihood r = self.observables['r'] q = self.observables['q'] q_err = self.observables['q_err'] try: q_model = getattr(self.profile, self.quantity)(r) except: # TODO: selectively catch interpolation failure # try with interpolation off try: kwargs = dict(interpolate=False, interpolate_surface_density=False) q_model = getattr(self.profile, self.quantity)(r, **kwargs) except: # and fail somewhat gracefully if that doesn't work q_model = np.nan * r lnl = np.sum(self.lnlike(q_model, q, q_err)) if return_blobs: kwargs = self._get_kwargs(sample) blobs = [] if return_lnlike: blobs.append(lnl) if return_profile: q_grid = np.interp(r_grid, r, q_model) blobs.append(q_grid) if return_vir: z = kwargs['z'] rvir, Mvir = self.profile.RMDelta(z=z, mdef=mdef) rs = kwargs['rs'] cvir = rvir / rs blobs.append(Mvir) blobs.append(cvir) if return_sp: rsp = optimize.fminbound(self.profile.densityDerivativeLog, 10**log_rsp_search_min, 10**log_rsp_search_max) gamma_min = self.profile.densityDerivativeLog(rsp) blobs.append(rsp) blobs.append(gamma_min) return lnp + lnl, tuple(blobs) else: return lnp + lnl
[ "numpy.log", "numpy.interp", "numpy.isfinite", "numpy.ones", "numpy.any", "scipy.optimize.fminbound", "collections.OrderedDict" ]
[((3773, 3819), 'collections.OrderedDict', 'OrderedDict', (['[(p.name, p) for p in parameters]'], {}), '([(p.name, p) for p in parameters])\n', (3784, 3819), False, 'from collections import OrderedDict\n'), ((8424, 8486), 'numpy.any', 'np.any', (['[return_lnlike, return_profile, return_vir, return_sp]'], {}), '([return_lnlike, return_profile, return_vir, return_sp])\n', (8430, 8486), True, 'import numpy as np\n'), ((830, 853), 'numpy.log', 'np.log', (['(2 * np.pi * var)'], {}), '(2 * np.pi * var)\n', (836, 853), True, 'import numpy as np\n'), ((3428, 3491), 'collections.OrderedDict', 'OrderedDict', (['[(key, observables[key]) for key in self._obskeys]'], {}), '([(key, observables[key]) for key in self._obskeys])\n', (3439, 3491), False, 'from collections import OrderedDict\n'), ((8951, 8967), 'numpy.isfinite', 'np.isfinite', (['lnp'], {}), '(lnp)\n', (8962, 8967), True, 'import numpy as np\n'), ((10477, 10506), 'numpy.interp', 'np.interp', (['r_grid', 'r', 'q_model'], {}), '(r_grid, r, q_model)\n', (10486, 10506), True, 'import numpy as np\n'), ((10870, 10979), 'scipy.optimize.fminbound', 'optimize.fminbound', (['self.profile.densityDerivativeLog', '(10 ** log_rsp_search_min)', '(10 ** log_rsp_search_max)'], {}), '(self.profile.densityDerivativeLog, 10 **\n log_rsp_search_min, 10 ** log_rsp_search_max)\n', (10888, 10979), False, 'from scipy import optimize\n'), ((9245, 9266), 'numpy.ones', 'np.ones', (['r_grid.shape'], {}), '(r_grid.shape)\n', (9252, 9266), True, 'import numpy as np\n')]
""" Solver D1Q2Q2 for the shallow water system on [0, 1] d_t(h) + d_x(q) = 0, t > 0, 0 < x < 1, d_t(q) + d_x(q^2/h+gh^2/2) = 0, t > 0, 0 < x < 1, h(t=0,x) = h0(x), q(t=0,x) = q0(x), d_t(h)(t,x=0) = d_t(h)(t,x=1) = 0 d_t(q)(t,x=0) = d_t(q)(t,x=1) = 0 the initial condition is a picewise constant function in order to visualize the simulation of elementary waves test: True """ import sympy as sp import numpy as np import pylbm h, q, X, LA, g = sp.symbols('h, q, X, LA, g') def Riemann_pb(x, xmin, xmax, uL, uR): xm = 0.5*(xmin+xmax) u = np.empty(x.shape) u[x < xm] = uL u[x == xm] = .5*(uL+uR) u[x > xm] = uR return u def run(dx, Tf, generator="numpy", sorder=None, withPlot=True): """ Parameters ---------- dx: double spatial step Tf: double final time generator: pylbm generator sorder: list storage order withPlot: boolean if True plot the solution otherwise just compute the solution """ # parameters xmin, xmax = 0., 1. # bounds of the domain la = 2. # velocity of the scheme s = 1.5 # relaxation parameter hL, hR, qL, qR = 1., .25, 0.10, 0.10 ymina, ymaxa, yminb, ymaxb = 0., 1., 0., .5 dico = { 'box': { 'x': [xmin, xmax], 'label': 0 }, 'space_step': dx, 'scheme_velocity': la, 'schemes': [ { 'velocities': [1, 2], 'conserved_moments': h, 'polynomials': [1, LA*X], 'relaxation_parameters': [0, s], 'equilibrium': [h, q], }, { 'velocities': [1, 2], 'conserved_moments': q, 'polynomials': [1, LA*X], 'relaxation_parameters': [0, s], 'equilibrium': [q, q**2/h+.5*g*h**2], }, ], 'init': {h: (Riemann_pb, (xmin, xmax, hL, hR)), q: (Riemann_pb, (xmin, xmax, qL, qR))}, 'boundary_conditions': { 0: { 'method': { 0: pylbm.bc.Neumann, 1: pylbm.bc.Neumann } }, }, 'generator': generator, 'parameters': {LA: la, g: 1.}, } sol = pylbm.Simulation(dico, sorder=sorder) if withPlot: # create the viewer to plot the solution viewer = pylbm.viewer.matplotlib_viewer fig = viewer.Fig(2, 1) ax1 = fig[0] ax1.axis(xmin, xmax, .9*ymina, 1.1*ymaxa) ax2 = fig[1] ax2.axis(xmin, xmax, .9*yminb, 1.1*ymaxb) x = sol.domain.x l1 = ax1.plot(x, sol.m[h], color='b')[0] l2 = ax2.plot(x, sol.m[q], color='r')[0] def update(iframe): if sol.t<Tf: sol.one_time_step() l1.set_data(x, sol.m[h]) l2.set_data(x, sol.m[q]) ax1.title = r'$h$ at $t = {0:f}$'.format(sol.t) ax2.title = r'$q$ at $t = {0:f}$'.format(sol.t) fig.animate(update) fig.show() else: while sol.t < Tf: sol.one_time_step() return sol if __name__ == '__main__': dx = 1./256 Tf = .25 run(dx, Tf)
[ "sympy.symbols", "pylbm.Simulation", "numpy.empty" ]
[((460, 488), 'sympy.symbols', 'sp.symbols', (['"""h, q, X, LA, g"""'], {}), "('h, q, X, LA, g')\n", (470, 488), True, 'import sympy as sp\n'), ((562, 579), 'numpy.empty', 'np.empty', (['x.shape'], {}), '(x.shape)\n', (570, 579), True, 'import numpy as np\n'), ((2339, 2376), 'pylbm.Simulation', 'pylbm.Simulation', (['dico'], {'sorder': 'sorder'}), '(dico, sorder=sorder)\n', (2355, 2376), False, 'import pylbm\n')]
# Copyright 2019 Xilinx Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS # PART OF THIS FILE AT ALL TIMES. from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from dataset import dataset_common def parse_rec(image_boxes_info): objects = [] xmin = image_boxes_info[3][0] ymin = image_boxes_info[3][1] xmax = image_boxes_info[3][2] ymax = image_boxes_info[3][3] label = image_boxes_info[3][4] difficult = image_boxes_info[3][5] for i in range(len(xmin)): obj_struct = {} obj_struct['name'] = label[i] obj_struct['difficult'] = difficult[i] obj_struct['bbox'] = [int(xmin[i]) - 1, int(ymin[i]) - 1, int(xmax[i]) - 1, int(ymax[i]) - 1] objects.append(obj_struct) return objects def do_python_eval(det_bboxes_by_class, gt_bboxes_by_imagename, use_07=True): aps = [] use_07_metric = use_07 print('VOC07 metric? ' + ('Yes' if use_07_metric else 'No')) for cls_name, cls_pair in dataset_common.EDD_LABELS.items(): if 'none' in cls_name: continue cls_id = cls_pair[0] rec, prec, ap = voc_eval(det_bboxes_by_class, gt_bboxes_by_imagename, cls_id, ovthresh=0.5, use_07_metric=use_07_metric) aps += [ap] print('AP for {} = {:.4f}'.format(cls_name, ap)) print ('MAP = {:.4f}'.format(np.mean(aps))) return np.mean(aps) def voc_ap(rec, prec, use_07_metric=True): if use_07_metric: ap = 0. for t in np.arange(0., 1.1, 0.1): if np.sum(rec >= t) == 0: p = 0 else: p = np.max(prec[rec >= t]) ap = ap + p / 11. else: mrec = np.concatenate(([0.], rec, [1.])) mpre = np.concatenate(([0.], prec, [0.])) for i in range(mpre.size - 1, 0, -1): mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) i = np.where(mrec[1:] != mrec[:-1])[0] ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) return ap def voc_eval(det_bboxes_by_class, gt_bboxes_dict_by_imagename, class_id, ovthresh=0.5, use_07_metric=True): imagenames = gt_bboxes_dict_by_imagename.keys() recs = {} for i, imagename in enumerate(imagenames): recs[imagename] = parse_rec(gt_bboxes_dict_by_imagename[imagename]) class_recs = {} npos = 0 for imagename in imagenames: R = [obj for obj in recs[imagename] if obj['name'] == class_id] bbox = np.array([x['bbox'] for x in R]) difficult = np.array([x['difficult'] for x in R]).astype(np.bool) det = [False] * len(R) npos = npos + sum(~difficult) class_recs[imagename] = {'bbox': bbox, 'difficult': difficult, 'det': det} if class_id not in det_bboxes_by_class.keys(): rec = -1. prec = -1. ap = -1. else: det_bboxes = det_bboxes_by_class[class_id] if any(det_bboxes) == 1: image_ids = [x[0] for x in det_bboxes] confidence = np.array([float(x[1]) for x in det_bboxes]) BB = np.array([[float(z) for z in x[2:]] for x in det_bboxes]) sorted_ind = np.argsort(-confidence) sorted_scores = np.sort(-confidence) BB = BB[sorted_ind, :] image_ids = [image_ids[x] for x in sorted_ind] nd = len(image_ids) tp = np.zeros(nd) fp = np.zeros(nd) for d in range(nd): R = class_recs[image_ids[d]] bb = BB[d, :].astype(float) ovmax = -np.inf BBGT = R['bbox'].astype(float) if BBGT.size > 0: ixmin = np.maximum(BBGT[:, 0], bb[0]) iymin = np.maximum(BBGT[:, 1], bb[1]) ixmax = np.minimum(BBGT[:, 2], bb[2]) iymax = np.minimum(BBGT[:, 3], bb[3]) iw = np.maximum(ixmax - ixmin, 0.) ih = np.maximum(iymax - iymin, 0.) inters = iw * ih uni = ((bb[2] - bb[0]) * (bb[3] - bb[1]) + (BBGT[:, 2] - BBGT[:, 0]) * (BBGT[:, 3] - BBGT[:, 1]) - inters) overlaps = inters / uni ovmax = np.max(overlaps) jmax = np.argmax(overlaps) if ovmax > ovthresh: if not R['difficult'][jmax]: if not R['det'][jmax]: tp[d] = 1. R['det'][jmax] = 1 else: fp[d] = 1. else: fp[d] = 1. fp = np.cumsum(fp) tp = np.cumsum(tp) rec = tp / float(npos) prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps) ap = voc_ap(rec, prec, use_07_metric) else: rec = -1. prec = -1. ap = -1. return rec, prec, ap if __name__ == '__main__': do_python_eval()
[ "numpy.minimum", "numpy.sum", "numpy.maximum", "numpy.argmax", "numpy.zeros", "numpy.argsort", "numpy.sort", "numpy.cumsum", "numpy.mean", "numpy.arange", "numpy.array", "numpy.where", "dataset.dataset_common.EDD_LABELS.items", "numpy.max", "numpy.finfo", "numpy.concatenate" ]
[((1699, 1732), 'dataset.dataset_common.EDD_LABELS.items', 'dataset_common.EDD_LABELS.items', ([], {}), '()\n', (1730, 1732), False, 'from dataset import dataset_common\n'), ((2096, 2108), 'numpy.mean', 'np.mean', (['aps'], {}), '(aps)\n', (2103, 2108), True, 'import numpy as np\n'), ((2208, 2232), 'numpy.arange', 'np.arange', (['(0.0)', '(1.1)', '(0.1)'], {}), '(0.0, 1.1, 0.1)\n', (2217, 2232), True, 'import numpy as np\n'), ((2409, 2444), 'numpy.concatenate', 'np.concatenate', (['([0.0], rec, [1.0])'], {}), '(([0.0], rec, [1.0]))\n', (2423, 2444), True, 'import numpy as np\n'), ((2458, 2494), 'numpy.concatenate', 'np.concatenate', (['([0.0], prec, [0.0])'], {}), '(([0.0], prec, [0.0]))\n', (2472, 2494), True, 'import numpy as np\n'), ((2658, 2703), 'numpy.sum', 'np.sum', (['((mrec[i + 1] - mrec[i]) * mpre[i + 1])'], {}), '((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n', (2664, 2703), True, 'import numpy as np\n'), ((3170, 3202), 'numpy.array', 'np.array', (["[x['bbox'] for x in R]"], {}), "([x['bbox'] for x in R])\n", (3178, 3202), True, 'import numpy as np\n'), ((2070, 2082), 'numpy.mean', 'np.mean', (['aps'], {}), '(aps)\n', (2077, 2082), True, 'import numpy as np\n'), ((2565, 2597), 'numpy.maximum', 'np.maximum', (['mpre[i - 1]', 'mpre[i]'], {}), '(mpre[i - 1], mpre[i])\n', (2575, 2597), True, 'import numpy as np\n'), ((2610, 2641), 'numpy.where', 'np.where', (['(mrec[1:] != mrec[:-1])'], {}), '(mrec[1:] != mrec[:-1])\n', (2618, 2641), True, 'import numpy as np\n'), ((3924, 3947), 'numpy.argsort', 'np.argsort', (['(-confidence)'], {}), '(-confidence)\n', (3934, 3947), True, 'import numpy as np\n'), ((3976, 3996), 'numpy.sort', 'np.sort', (['(-confidence)'], {}), '(-confidence)\n', (3983, 3996), True, 'import numpy as np\n'), ((4140, 4152), 'numpy.zeros', 'np.zeros', (['nd'], {}), '(nd)\n', (4148, 4152), True, 'import numpy as np\n'), ((4170, 4182), 'numpy.zeros', 'np.zeros', (['nd'], {}), '(nd)\n', (4178, 4182), True, 'import numpy as np\n'), ((5471, 5484), 'numpy.cumsum', 'np.cumsum', (['fp'], {}), '(fp)\n', (5480, 5484), True, 'import numpy as np\n'), ((5502, 5515), 'numpy.cumsum', 'np.cumsum', (['tp'], {}), '(tp)\n', (5511, 5515), True, 'import numpy as np\n'), ((2248, 2264), 'numpy.sum', 'np.sum', (['(rec >= t)'], {}), '(rec >= t)\n', (2254, 2264), True, 'import numpy as np\n'), ((2331, 2353), 'numpy.max', 'np.max', (['prec[rec >= t]'], {}), '(prec[rec >= t])\n', (2337, 2353), True, 'import numpy as np\n'), ((3223, 3260), 'numpy.array', 'np.array', (["[x['difficult'] for x in R]"], {}), "([x['difficult'] for x in R])\n", (3231, 3260), True, 'import numpy as np\n'), ((4445, 4474), 'numpy.maximum', 'np.maximum', (['BBGT[:, 0]', 'bb[0]'], {}), '(BBGT[:, 0], bb[0])\n', (4455, 4474), True, 'import numpy as np\n'), ((4503, 4532), 'numpy.maximum', 'np.maximum', (['BBGT[:, 1]', 'bb[1]'], {}), '(BBGT[:, 1], bb[1])\n', (4513, 4532), True, 'import numpy as np\n'), ((4561, 4590), 'numpy.minimum', 'np.minimum', (['BBGT[:, 2]', 'bb[2]'], {}), '(BBGT[:, 2], bb[2])\n', (4571, 4590), True, 'import numpy as np\n'), ((4619, 4648), 'numpy.minimum', 'np.minimum', (['BBGT[:, 3]', 'bb[3]'], {}), '(BBGT[:, 3], bb[3])\n', (4629, 4648), True, 'import numpy as np\n'), ((4674, 4704), 'numpy.maximum', 'np.maximum', (['(ixmax - ixmin)', '(0.0)'], {}), '(ixmax - ixmin, 0.0)\n', (4684, 4704), True, 'import numpy as np\n'), ((4729, 4759), 'numpy.maximum', 'np.maximum', (['(iymax - iymin)', '(0.0)'], {}), '(iymax - iymin, 0.0)\n', (4739, 4759), True, 'import numpy as np\n'), ((5049, 5065), 'numpy.max', 'np.max', (['overlaps'], {}), '(overlaps)\n', (5055, 5065), True, 'import numpy as np\n'), ((5093, 5112), 'numpy.argmax', 'np.argmax', (['overlaps'], {}), '(overlaps)\n', (5102, 5112), True, 'import numpy as np\n'), ((5595, 5615), 'numpy.finfo', 'np.finfo', (['np.float64'], {}), '(np.float64)\n', (5603, 5615), True, 'import numpy as np\n')]
""" This module recognizes shapes in pictures """ import numpy as np import sys np.set_printoptions(threshold=sys.maxsize) import matplotlib.image as img import matplotlib.pyplot as plt # sample user interaction idea # img = library.image('pic1.png') # img_contour = img.draw_contours() class Picture: """ Runs through ``orbitize`` methods in a standardized way. Args: input_data: Either a relative path to data file or astropy.table.Table object in the orbitize format. See ``orbitize.read_input`` sampler_str (str): algorithm to use for orbit computation. "MCMC" for Markov Chain Monte Carlo, "OFTI" for Orbits for the Impatient num_secondary_bodies (int): number of secondary bodies in the system. Should be at least 1. system_mass (float): mean total mass of the system [M_sol] plx (float): mean parallax of the system [mas] mass_err (float, optional): uncertainty on ``system_mass`` [M_sol] plx_err (float, optional): uncertainty on ``plx`` [mas] lnlike (str, optional): name of function in ``orbitize.lnlike`` that will be used to compute likelihood. (default="chi2_lnlike") system_kwargs (dict, optional): ``restrict_angle_ranges``, ``ref_tau_epoch``, ``results`` for ``orbitize.system.System``. mcmc_kwargs (dict, optional): ``num_temps``, ``num_walkers``, and ``num_threads`` kwargs for ``orbitize.sampler.MCMC`` Written: <NAME>, 2018 """ def __init__(self, file_name, threshold = 0.1): """class __init__ method Note: Do not include the `self` parameter in the ``Args`` section. Args: file_name (str): The name of the image file to be loaded as a Picture object. threshold (float): Threshold value to determine whether or not an edge is present. This is passed as an attribute and then called in by the highlight_edges_grad method. Default value is 0.1 . Attributes: file_name (str): file name of the loaded image image (np.array): [R G B] values of each pixel in the image contours (np.array): copy of the [R G B] values of each pixel in the image, will be used to draw the detected edge over the original image height (int): height of the image in px width (int): width of the image in px edges (np.array): array of zeros with same dimensions as the image. whenever an edge is found, the "color difference" value is stored in the corresponding pixel threshold (float): threshold to the "color difference" to determine the presence of an edge alpha (bool): True if the loaded image has an alpha channel, False otherwise """ self.file_name = file_name self.image = img.imread(file_name) # numpy array of r-g-b values self.contours = img.imread(file_name) # image copy for including highligthed edges self.height= len(self.image) self.width = len(self.image[0]) self.edges = np.zeros((self.height, self.width)) # numpy array with 1s as edges self.threshold = threshold if len(self.image[0][0]) == 4: self.alpha = True else: self.alpha = False def __len__(self): """ Special len method Returns: int: total number of pixels """ return self.height * self.width def __str__(self): """ Special str method Returns: str: string with info on filename and image size """ return f'File name: {self.file_name}; width: {self.width}px, height: {self.height}px' def __del__(self): """ Special del method It deletes a picture object and prints a report of the deletion """ print(f'I just deleted {self.file_name}') def assess_difference(self, pixel_a, pixel_b): """ This function checks if two adjacent pixels have the exact same RGB value Args: pixel_a (float, list): [r,g,b] values for pixel A pixel_b (float, list): [r,g,b] values for pixel B Returns: bool: True if the two pixel have the same RGB values """ return np.array_equal(pixel_a, pixel_b) def horizontal_scan(self, row_index): """ This function performs a linear scan over a given row Args: row_index (int): index of row to scan in self.image """ for i in range(1, self.width): # compare each pixel to the previous one if not self.assess_difference(self.image[row_index][i-1], self.image[row_index][i]): self.edges[row_index][i] = 1 def vertical_scan(self, col_index): ''' This function performs a linear scan over a given column Args: col_index - index of column in self.image to scan ''' for i in range(1, self.height): # compare each pixel to the previous one if not self.assess_difference(self.image[i-1][col_index], self.image[i][col_index]): self.edges[i][col_index] = 1 def find_edges(self): ''' ... ''' for i in range(self.width): self.vertical_scan(i) for i in range(self.height): self.horizontal_scan(i) def highlight_edges(self): ''' ''' if self.alpha: for i in range(self.height): for j in range(self.width): if self.edges[i][j] == 0: # print(self.contours[i][j]) self.contours[i][j] = [0, 0, 0, 1] else: # print(self.contours[i][j]) self.contours[i][j] = [1, 1, 1, 1] else: for i in range(self.height): for j in range(self.width): if self.edges[i][j] == 0: # print(self.contours[i][j]) self.contours[i][j] = [0, 0, 0] else: # print(self.contours[i][j]) self.contours[i][j] = [1, 1, 1] def assess_gradient(self, pixel_a, pixel_b): ''' This function checks if two adjacent pixels have the exact same RGB value Args: pixel_a - list: [r,g,b] values for pixel A pixel_b - list: [r,g,b] values for pixel B ''' diff = np.abs(pixel_a - pixel_b).sum() # grad = diff / self.scale return diff def horizontal_scan_grad(self, row_index): ''' This function performs a linear scan over a given row Args: row_index - index of row in self.image to scan ''' for i in range(1, self.width): # compare each pixel to the previous one hor_grad = self.assess_gradient(self.image[row_index][i-1], self.image[row_index][i]) self.edges[row_index][i] = max(self.edges[row_index][i], hor_grad) def vertical_scan_grad(self, col_index): ''' This function performs a linear scan over a given column Args: col_index - index of column in self.image to scan ''' for i in range(1, self.height): # compare each pixel to the previous one vert_grad = self.assess_gradient(self.image[i-1][col_index], self.image[i][col_index]) self.edges[i][col_index] = max(self.edges[i][col_index], vert_grad) def find_edges_grad(self): ''' ... ''' for i in range(self.width): self.vertical_scan_grad(i) for i in range(self.height): self.horizontal_scan_grad(i) def highlight_edges_grad(self): ''' ''' if self.alpha: for i in range(self.height): for j in range(self.width): if self.edges[i][j] < self.threshold: # print(self.contours[i][j]) self.contours[i][j] = [0, 0, 0, 1] #drawing black else: # print(self.contours[i][j]) # if self.contours[i][j] self.contours[i][j] = [1, 1, 1, 1] #drawing the edge else: for i in range(self.height): for j in range(self.width): if self.edges[i][j] < self.threshold: # print(self.contours[i][j]) self.contours[i][j] = [0, 0, 0] else: # print(self.contours[i][j]) self.contours[i][j] = [1, 1, 1] def check_num_edges(self): ''' ''' tot_edges = 0 for row in self.edges: tot_edges += sum(row) return tot_edges def paint_contours(self, grad = False): print('Working on the following image:') print(self) if grad: self.find_edges_grad() print(f'I found {self.check_num_edges()} edges.') self.highlight_edges_grad() else: self.find_edges() print(f'I found {self.check_num_edges()} edges.') self.highlight_edges() plt.imshow(self.contours) # for th in np.linspace(0.1, 1., 10, endpoint=True): # print(f'Threshold is {th}') # image_to_process = Picture('pic6.png', threshold = th) image_to_process = Picture('pic6.png') image_to_process.paint_contours(grad=True) plt.show()
[ "matplotlib.image.imread", "numpy.set_printoptions", "matplotlib.pyplot.show", "numpy.abs", "matplotlib.pyplot.imshow", "numpy.zeros", "numpy.array_equal" ]
[((80, 122), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': 'sys.maxsize'}), '(threshold=sys.maxsize)\n', (99, 122), True, 'import numpy as np\n'), ((9988, 9998), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9996, 9998), True, 'import matplotlib.pyplot as plt\n'), ((2870, 2891), 'matplotlib.image.imread', 'img.imread', (['file_name'], {}), '(file_name)\n', (2880, 2891), True, 'import matplotlib.image as img\n'), ((2946, 2967), 'matplotlib.image.imread', 'img.imread', (['file_name'], {}), '(file_name)\n', (2956, 2967), True, 'import matplotlib.image as img\n'), ((3111, 3146), 'numpy.zeros', 'np.zeros', (['(self.height, self.width)'], {}), '((self.height, self.width))\n', (3119, 3146), True, 'import numpy as np\n'), ((4427, 4459), 'numpy.array_equal', 'np.array_equal', (['pixel_a', 'pixel_b'], {}), '(pixel_a, pixel_b)\n', (4441, 4459), True, 'import numpy as np\n'), ((9690, 9715), 'matplotlib.pyplot.imshow', 'plt.imshow', (['self.contours'], {}), '(self.contours)\n', (9700, 9715), True, 'import matplotlib.pyplot as plt\n'), ((6773, 6798), 'numpy.abs', 'np.abs', (['(pixel_a - pixel_b)'], {}), '(pixel_a - pixel_b)\n', (6779, 6798), True, 'import numpy as np\n')]
import torch from itertools import accumulate from fairseq.data import ( data_utils, FairseqDataset, Dictionary, IdDataset, NestedDictionaryDataset, NumelDataset, NumSamplesDataset, ) from functools import lru_cache import numpy as np from seqp.hdf5 import Hdf5RecordReader from typing import List from morphodropout.binarize import ( SRC_SUBWORD_KEY, SRC_SUBWORD_LENGTHS_KEY, SRC_MORPH_KEY, SRC_MORPH_LENGTHS_KEY, SRC_LEMMA_KEY, ) class MorphoDataset(FairseqDataset): """A dataset that provides helpers for batching.""" def __init__(self, dictionary: Dictionary, data_files: List[str], morpho_dropout: float = 0.5): self.dictionary = dictionary self.pad_idx = dictionary.pad_index self.data_files = data_files self.reader = Hdf5RecordReader(data_files) self.morpho_dropout = morpho_dropout def __getstate__(self): state = self.__dict__.copy() # Don't pickle the reader (see https://github.com/h5py/h5py/issues/1092) del state["reader"] return state def __setstate__(self, state): self.__dict__.update(state) # Add reader back since it doesn't exist in the pickle self.reader = Hdf5RecordReader(self.data_files) @lru_cache(maxsize=8) def __getitem__(self, index): record = self.reader.retrieve(index) lemmas = record[SRC_LEMMA_KEY] subwords = record[SRC_SUBWORD_KEY] morphos = record[SRC_MORPH_KEY] morpho_lengths = record[SRC_MORPH_LENGTHS_KEY].tolist() sw_lengths = record[SRC_SUBWORD_LENGTHS_KEY].tolist() use_subwords = np.random.binomial(size=len(lemmas), n=1, p=self.morpho_dropout).astype(bool) EOS_POS = -1 sw_pos = list(accumulate(sw_lengths)) morpho_pos = list(accumulate(morpho_lengths)) start_end = zip([0] + sw_pos[:EOS_POS - 1], sw_pos[:EOS_POS], [0] + morpho_pos[:-1], morpho_pos) pad = [self.dictionary.pad_index] eos = [self.dictionary.eos_index] result: List[np.ndarray] = list() max_depth = 0 for k, (sw_start, sw_end, morpho_start, morpho_end) in enumerate(start_end): if use_subwords[k] or lemmas[k] in [self.dictionary.unk_index, self.dictionary.pad_index]: word_subwords = subwords[sw_start:sw_end] result.extend([np.array([sw], dtype=np.int64) for sw in word_subwords]) max_depth = max(max_depth, 1) else: clean_morphos = [m if m != self.dictionary.unk_index else self.dictionary.pad_index for m in morphos[morpho_start:morpho_end]] word_linguistic_info = [lemmas[k]] + clean_morphos result.append(np.array(word_linguistic_info, dtype=np.int64)) max_depth = max(max_depth, len(word_linguistic_info)) result.append(np.array(eos, dtype=np.int64)) # Add padding and convert to tensors result = [torch.LongTensor(np.concatenate((r, pad * (max_depth - len(r))))) for r in result] # Combine padded tensors into a single 2d tensor result = torch.stack(result) return result def __len__(self): return self.reader.num_records() def num_tokens(self, index): return self.reader.length(index) def size(self, index): return self.reader.length(index) def ordered_indices(self): return [idx for idx, length in self.reader.indexes_and_lengths()] @property def sizes(self): return [length for idx, length in self.reader.indexes_and_lengths()] def get_dummy_batch(self, num_tokens, max_positions): return self.dictionary.dummy_sentence(num_tokens).unsqueeze(dim=2) @property def supports_prefetch(self): return False def prefetch(self, indices): raise NotImplementedError def collater(self, samples): size = max(v.size(0) for v in samples) depth = max(v.size(1) for v in samples) res = samples[0].new(len(samples), size, depth).fill_(self.pad_idx) def copy_tensor(src, dst): assert dst.numel() == src.numel() dst.copy_(src) for i, v in enumerate(samples): copy_tensor(v, res[i, :v.size(0), :v.size(1)]) return res class MonolingualDataset(FairseqDataset): """A dataset that provides helpers for batching.""" def __init__(self, dictionary: Dictionary, data_files: List[str], left_pad=False, move_eos_to_beginning=False): self.dictionary = dictionary self.data_files = data_files self.reader = Hdf5RecordReader(data_files) self.left_pad = left_pad self.move_eos_to_beginning = move_eos_to_beginning def __getstate__(self): state = self.__dict__.copy() # Don't pickle the reader (see https://github.com/h5py/h5py/issues/1092) del state["reader"] return state def __setstate__(self, state): self.__dict__.update(state) # Add reader back since it doesn't exist in the pickle self.reader = Hdf5RecordReader(self.data_files) def __getitem__(self, index): elem = self.reader.retrieve(index) elem = torch.LongTensor(elem.astype(np.int64)) return elem def __len__(self): return self.reader.num_records() def collater(self, samples): tokens = data_utils.collate_tokens( [s for s in samples], self.dictionary.pad_index, self.dictionary.eos_index, self.left_pad, move_eos_to_beginning=self.move_eos_to_beginning) return tokens def get_dummy_batch(self, num_tokens, max_positions): return self.dictionary.dummy_sentence(num_tokens) def num_tokens(self, index): return self.reader.length(index) def size(self, index): return self.reader.length(index) def ordered_indices(self): return [idx for idx, length in self.reader.indexes_and_lengths()] @property def sizes(self): return [length for idx, length in self.reader.indexes_and_lengths()] @property def supports_prefetch(self): return False def prefetch(self, indices): raise NotImplementedError def build_combined_dataset( src_dictionary: Dictionary, src_data_files: List[str], src_morpho_dropout: float, tgt_dictionary: Dictionary, tgt_hdf5_files: List[str], seed: int, epoch: int, ) -> FairseqDataset: src = MorphoDataset(src_dictionary, src_data_files, src_morpho_dropout) target = MonolingualDataset(tgt_dictionary, tgt_hdf5_files, move_eos_to_beginning=False) prev_output_tokens = MonolingualDataset(tgt_dictionary, tgt_hdf5_files, move_eos_to_beginning=True) return NestedDictionaryDataset( { 'id': IdDataset(), 'net_input': { 'src_tokens': src, 'src_lengths': NumelDataset(src, reduce=False), 'prev_output_tokens': prev_output_tokens, }, 'target': target, 'nsentences': NumSamplesDataset(), 'ntokens': NumelDataset(src, reduce=True), }, sizes=[src.sizes], )
[ "fairseq.data.data_utils.collate_tokens", "fairseq.data.NumelDataset", "torch.stack", "seqp.hdf5.Hdf5RecordReader", "itertools.accumulate", "fairseq.data.NumSamplesDataset", "numpy.array", "fairseq.data.IdDataset", "functools.lru_cache" ]
[((1335, 1355), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': '(8)'}), '(maxsize=8)\n', (1344, 1355), False, 'from functools import lru_cache\n'), ((868, 896), 'seqp.hdf5.Hdf5RecordReader', 'Hdf5RecordReader', (['data_files'], {}), '(data_files)\n', (884, 896), False, 'from seqp.hdf5 import Hdf5RecordReader\n'), ((1295, 1328), 'seqp.hdf5.Hdf5RecordReader', 'Hdf5RecordReader', (['self.data_files'], {}), '(self.data_files)\n', (1311, 1328), False, 'from seqp.hdf5 import Hdf5RecordReader\n'), ((3297, 3316), 'torch.stack', 'torch.stack', (['result'], {}), '(result)\n', (3308, 3316), False, 'import torch\n'), ((4853, 4881), 'seqp.hdf5.Hdf5RecordReader', 'Hdf5RecordReader', (['data_files'], {}), '(data_files)\n', (4869, 4881), False, 'from seqp.hdf5 import Hdf5RecordReader\n'), ((5327, 5360), 'seqp.hdf5.Hdf5RecordReader', 'Hdf5RecordReader', (['self.data_files'], {}), '(self.data_files)\n', (5343, 5360), False, 'from seqp.hdf5 import Hdf5RecordReader\n'), ((5630, 5805), 'fairseq.data.data_utils.collate_tokens', 'data_utils.collate_tokens', (['[s for s in samples]', 'self.dictionary.pad_index', 'self.dictionary.eos_index', 'self.left_pad'], {'move_eos_to_beginning': 'self.move_eos_to_beginning'}), '([s for s in samples], self.dictionary.pad_index,\n self.dictionary.eos_index, self.left_pad, move_eos_to_beginning=self.\n move_eos_to_beginning)\n', (5655, 5805), False, 'from fairseq.data import data_utils, FairseqDataset, Dictionary, IdDataset, NestedDictionaryDataset, NumelDataset, NumSamplesDataset\n'), ((1828, 1850), 'itertools.accumulate', 'accumulate', (['sw_lengths'], {}), '(sw_lengths)\n', (1838, 1850), False, 'from itertools import accumulate\n'), ((1878, 1904), 'itertools.accumulate', 'accumulate', (['morpho_lengths'], {}), '(morpho_lengths)\n', (1888, 1904), False, 'from itertools import accumulate\n'), ((3044, 3073), 'numpy.array', 'np.array', (['eos'], {'dtype': 'np.int64'}), '(eos, dtype=np.int64)\n', (3052, 3073), True, 'import numpy as np\n'), ((7389, 7400), 'fairseq.data.IdDataset', 'IdDataset', ([], {}), '()\n', (7398, 7400), False, 'from fairseq.data import data_utils, FairseqDataset, Dictionary, IdDataset, NestedDictionaryDataset, NumelDataset, NumSamplesDataset\n'), ((7713, 7732), 'fairseq.data.NumSamplesDataset', 'NumSamplesDataset', ([], {}), '()\n', (7730, 7732), False, 'from fairseq.data import data_utils, FairseqDataset, Dictionary, IdDataset, NestedDictionaryDataset, NumelDataset, NumSamplesDataset\n'), ((7765, 7795), 'fairseq.data.NumelDataset', 'NumelDataset', (['src'], {'reduce': '(True)'}), '(src, reduce=True)\n', (7777, 7795), False, 'from fairseq.data import data_utils, FairseqDataset, Dictionary, IdDataset, NestedDictionaryDataset, NumelDataset, NumSamplesDataset\n'), ((7519, 7550), 'fairseq.data.NumelDataset', 'NumelDataset', (['src'], {'reduce': '(False)'}), '(src, reduce=False)\n', (7531, 7550), False, 'from fairseq.data import data_utils, FairseqDataset, Dictionary, IdDataset, NestedDictionaryDataset, NumelDataset, NumSamplesDataset\n'), ((2904, 2950), 'numpy.array', 'np.array', (['word_linguistic_info'], {'dtype': 'np.int64'}), '(word_linguistic_info, dtype=np.int64)\n', (2912, 2950), True, 'import numpy as np\n'), ((2510, 2540), 'numpy.array', 'np.array', (['[sw]'], {'dtype': 'np.int64'}), '([sw], dtype=np.int64)\n', (2518, 2540), True, 'import numpy as np\n')]
from tqdm.auto import tqdm import click import numpy as np from transformers import GPT2LMHeadModel, GPT2TokenizerFast from sklearn.metrics.pairwise import cosine_similarity import torch import math import json def load_vectors(path, max_n=200_000): with open(path) as f: ids = {} dim = int(f.readline().strip().split()[1]) vectors = np.zeros((max_n, dim)) i = 0 for line in tqdm(f, total=max_n): if i == max_n: break parts = line.split() name = parts[0] if name in ids: continue try: values = np.array([float(x) for x in parts[1:]]) vectors[i] = values ids[name] = i i += 1 except ValueError: pass return vectors, ids def get_tokenizer_embeddings(tokenizer, vectors, ids, freqs): embs = {value: ([], [], set()) for value in tokenizer.get_vocab().values()} for lower_key, value in tqdm(ids.items()): for key in [lower_key, lower_key.title()]: tokenized = tokenizer.encode( key, add_special_tokens=False ) + tokenizer.encode(" " + key, add_special_tokens=False) for token_id in tokenized: if key not in embs[token_id][2] and key in freqs: embs[token_id][0].append(vectors[value]) embs[token_id][1].append(freqs[key]) embs[token_id][2].add(key) embs_matrix = np.zeros((len(embs), vectors.shape[1])) for i in range(len(embs_matrix)): if len(embs[i][2]) == 0: continue freqs = np.array(embs[i][1], dtype=np.float32) freqs /= freqs.sum() embs_matrix[i] = (np.stack(embs[i][0]) * freqs[:, np.newaxis]).sum(axis=0) return embs_matrix @click.command() @click.option("--german_tokenizer", help="Name or path of trained German tokenizer.") @click.option("--english_tokenizer", help="Name or path of trained English tokenizer.") @click.option( "--gpt2_model", help="Name or path of trained English GPT2 model to use WTE from." ) @click.option( "--german_freqs", help="Path to a .json file with frequencies of german words." ) @click.option( "--english_freqs", help="Path to a .json file with frequencies of english words." ) @click.option( "--german_vecs", help="German aligned word vectors from https://fasttext.cc/docs/en/aligned-vectors.html.", ) @click.option( "--english_vecs", help="English aligned word vectors from https://fasttext.cc/docs/en/aligned-vectors.html.", ) @click.option( "--out_path", help="Path to store the German WTE matrix at as .pt file.", ) def main( german_tokenizer, english_tokenizer, gpt2_model, german_freqs, english_freqs, german_vecs, english_vecs, out_path, ): german_freqs = json.load(open(german_freqs)) english_freqs = json.load(open(english_freqs)) de_vectors, de_ids = load_vectors(german_vecs) en_vectors, en_ids = load_vectors(english_vecs) german_tokenizer = GPT2TokenizerFast.from_pretrained(german_tokenizer) english_tokenizer = GPT2TokenizerFast.from_pretrained(english_tokenizer) model = GPT2LMHeadModel.from_pretrained(gpt2_model) en_tok_embs = get_tokenizer_embeddings( english_tokenizer, en_vectors, en_ids, english_freqs ) de_tok_embs = get_tokenizer_embeddings( german_tokenizer, de_vectors, de_ids, german_freqs ) def get_closest(token_id, similarities=None): if (de_tok_embs[token_id] == 0).all(): return None, None if similarities is None: similarities = cosine_similarity( de_tok_embs[token_id][np.newaxis, :], en_tok_embs )[0] best = np.argsort(similarities)[::-1] best = english_tokenizer.convert_ids_to_tokens(best) de_token = german_tokenizer.convert_ids_to_tokens([token_id])[0] space_before = de_token.startswith("Ġ") best = [x for x in best if x.startswith("Ġ") == space_before] en_token = best[0] return en_token, de_token print("Some sample mappings:") for token_id in np.random.choice(list(german_tokenizer.get_vocab().values()), 30): en_token, de_token = get_closest(token_id) print(f"{de_token} -> {en_token}") german_wte_weight = torch.zeros_like(model.transformer.wte.weight) mean, std = ( model.transformer.wte.weight.mean().item(), model.transformer.wte.weight.std().item(), ) en_vocab = english_tokenizer.get_vocab() n_matched = 0 batch_size = 1024 for i in tqdm(range(int(math.ceil(len(german_wte_weight) / batch_size)))): start, end = i * batch_size, min((i + 1) * batch_size, len(german_wte_weight)) similarities = cosine_similarity(de_tok_embs[start:end], en_tok_embs) for token_id in range(start, end): en_token, _ = get_closest( token_id, similarities=similarities[token_id - start] ) if en_token is None: german_wte_weight[token_id] = torch.normal( mean, std, size=(german_wte_weight.shape[1],) ) else: en_token_id = en_vocab[en_token] german_wte_weight[token_id] = model.transformer.wte.weight[en_token_id] n_matched += 1 print(f"Matching token found for {n_matched} of {len(en_vocab)} tokens.") torch.save(german_wte_weight, out_path) if __name__ == "__main__": main()
[ "numpy.stack", "sklearn.metrics.pairwise.cosine_similarity", "torch.zeros_like", "transformers.GPT2TokenizerFast.from_pretrained", "transformers.GPT2LMHeadModel.from_pretrained", "click.option", "numpy.zeros", "click.command", "torch.save", "tqdm.auto.tqdm", "numpy.argsort", "torch.normal", "numpy.array" ]
[((1882, 1897), 'click.command', 'click.command', ([], {}), '()\n', (1895, 1897), False, 'import click\n'), ((1899, 1988), 'click.option', 'click.option', (['"""--german_tokenizer"""'], {'help': '"""Name or path of trained German tokenizer."""'}), "('--german_tokenizer', help=\n 'Name or path of trained German tokenizer.')\n", (1911, 1988), False, 'import click\n'), ((1985, 2076), 'click.option', 'click.option', (['"""--english_tokenizer"""'], {'help': '"""Name or path of trained English tokenizer."""'}), "('--english_tokenizer', help=\n 'Name or path of trained English tokenizer.')\n", (1997, 2076), False, 'import click\n'), ((2073, 2174), 'click.option', 'click.option', (['"""--gpt2_model"""'], {'help': '"""Name or path of trained English GPT2 model to use WTE from."""'}), "('--gpt2_model', help=\n 'Name or path of trained English GPT2 model to use WTE from.')\n", (2085, 2174), False, 'import click\n'), ((2177, 2275), 'click.option', 'click.option', (['"""--german_freqs"""'], {'help': '"""Path to a .json file with frequencies of german words."""'}), "('--german_freqs', help=\n 'Path to a .json file with frequencies of german words.')\n", (2189, 2275), False, 'import click\n'), ((2278, 2378), 'click.option', 'click.option', (['"""--english_freqs"""'], {'help': '"""Path to a .json file with frequencies of english words."""'}), "('--english_freqs', help=\n 'Path to a .json file with frequencies of english words.')\n", (2290, 2378), False, 'import click\n'), ((2381, 2511), 'click.option', 'click.option', (['"""--german_vecs"""'], {'help': '"""German aligned word vectors from https://fasttext.cc/docs/en/aligned-vectors.html."""'}), "('--german_vecs', help=\n 'German aligned word vectors from https://fasttext.cc/docs/en/aligned-vectors.html.'\n )\n", (2393, 2511), False, 'import click\n'), ((2514, 2646), 'click.option', 'click.option', (['"""--english_vecs"""'], {'help': '"""English aligned word vectors from https://fasttext.cc/docs/en/aligned-vectors.html."""'}), "('--english_vecs', help=\n 'English aligned word vectors from https://fasttext.cc/docs/en/aligned-vectors.html.'\n )\n", (2526, 2646), False, 'import click\n'), ((2649, 2740), 'click.option', 'click.option', (['"""--out_path"""'], {'help': '"""Path to store the German WTE matrix at as .pt file."""'}), "('--out_path', help=\n 'Path to store the German WTE matrix at as .pt file.')\n", (2661, 2740), False, 'import click\n'), ((3131, 3182), 'transformers.GPT2TokenizerFast.from_pretrained', 'GPT2TokenizerFast.from_pretrained', (['german_tokenizer'], {}), '(german_tokenizer)\n', (3164, 3182), False, 'from transformers import GPT2LMHeadModel, GPT2TokenizerFast\n'), ((3207, 3259), 'transformers.GPT2TokenizerFast.from_pretrained', 'GPT2TokenizerFast.from_pretrained', (['english_tokenizer'], {}), '(english_tokenizer)\n', (3240, 3259), False, 'from transformers import GPT2LMHeadModel, GPT2TokenizerFast\n'), ((3273, 3316), 'transformers.GPT2LMHeadModel.from_pretrained', 'GPT2LMHeadModel.from_pretrained', (['gpt2_model'], {}), '(gpt2_model)\n', (3304, 3316), False, 'from transformers import GPT2LMHeadModel, GPT2TokenizerFast\n'), ((4436, 4482), 'torch.zeros_like', 'torch.zeros_like', (['model.transformer.wte.weight'], {}), '(model.transformer.wte.weight)\n', (4452, 4482), False, 'import torch\n'), ((5556, 5595), 'torch.save', 'torch.save', (['german_wte_weight', 'out_path'], {}), '(german_wte_weight, out_path)\n', (5566, 5595), False, 'import torch\n'), ((364, 386), 'numpy.zeros', 'np.zeros', (['(max_n, dim)'], {}), '((max_n, dim))\n', (372, 386), True, 'import numpy as np\n'), ((422, 442), 'tqdm.auto.tqdm', 'tqdm', (['f'], {'total': 'max_n'}), '(f, total=max_n)\n', (426, 442), False, 'from tqdm.auto import tqdm\n'), ((1703, 1741), 'numpy.array', 'np.array', (['embs[i][1]'], {'dtype': 'np.float32'}), '(embs[i][1], dtype=np.float32)\n', (1711, 1741), True, 'import numpy as np\n'), ((4887, 4941), 'sklearn.metrics.pairwise.cosine_similarity', 'cosine_similarity', (['de_tok_embs[start:end]', 'en_tok_embs'], {}), '(de_tok_embs[start:end], en_tok_embs)\n', (4904, 4941), False, 'from sklearn.metrics.pairwise import cosine_similarity\n'), ((3845, 3869), 'numpy.argsort', 'np.argsort', (['similarities'], {}), '(similarities)\n', (3855, 3869), True, 'import numpy as np\n'), ((3727, 3795), 'sklearn.metrics.pairwise.cosine_similarity', 'cosine_similarity', (['de_tok_embs[token_id][np.newaxis, :]', 'en_tok_embs'], {}), '(de_tok_embs[token_id][np.newaxis, :], en_tok_embs)\n', (3744, 3795), False, 'from sklearn.metrics.pairwise import cosine_similarity\n'), ((5188, 5247), 'torch.normal', 'torch.normal', (['mean', 'std'], {'size': '(german_wte_weight.shape[1],)'}), '(mean, std, size=(german_wte_weight.shape[1],))\n', (5200, 5247), False, 'import torch\n'), ((1798, 1818), 'numpy.stack', 'np.stack', (['embs[i][0]'], {}), '(embs[i][0])\n', (1806, 1818), True, 'import numpy as np\n')]
#!/usr/bin/env python3 from itertools import product from pathlib import Path import numpy as np import pygame import os # основные используемые цвета background_color = (100, 100, 100) layout_color = (120, 120, 120) lighter_color = (150, 150, 150) text_color = (200, 200, 200) colors = { # игровое поле и шрифт 0: (170, 170, 170), # фигуры 1: (230, 100, 100), 2: (230, 210, 100), 3: (210, 230, 100), 4: (100, 230, 100), 5: (100, 230, 210), 6: (100, 210, 230), 7: (100, 100, 230), 8: (210, 100, 230), 9: (230, 100, 200) } figures = [ # коробки всех размеров np.array([[True] * 3, [True] * 3, [True] * 3]).T, np.array([[True, True], [True, True]]).T, np.array([[True]]).T, # # прямые линии np.array([[True] * 5]), np.array([[True] * 4]), np.array([[True] * 3]), np.array([[True] * 2]), # остальные фигуры np.array([[True, False, False], [True, False, False], [True, True, True]]), np.array([[True, False, False], [True, False, False], [True, True, False]]), np.array([[True, False], [True, True]]), ] # сдвига начала координат shift_pos = (10, 10) # размер одного тайла TILE_SIZE = 32 # сдвиги и пробелы между тайлами для отрисовки TILE_SHIFT = 8 TILE_SKIP = 28 # размер корзины для фигур MAX_BASKET_TILES = 5 # количество ячеек в корзине для фигур MAX_BASKET_SIZE = 3 # размер игровой доски BOARD_SIZE = 10 # идентификаторы кнопок мыши в pygame LEFT_MOUSE = 1 RIGHT_MOUSE = 3 # координаты с корзинам с фигурами basket_pos = [[x + shift_pos[0], TILE_SIZE * 11 + shift_pos[1]] for x in np.arange(0, 3 * MAX_BASKET_TILES * TILE_SIZE, TILE_SIZE * 6)] # автоматический размер окна game_width = basket_pos[2][0] + (basket_pos[1][0] - basket_pos[0][0]) - shift_pos[0] game_height = TILE_SIZE * (BOARD_SIZE + MAX_BASKET_TILES + 2) + shift_pos[1] - shift_pos[1] # gameover params game_over_text = 'КОНЕЦ ИГРЫ' gmx, gmy = len(game_over_text) * 30, 48 gmx_pos = ((game_width - gmx) // 2, (game_height - gmy) // 2) rect1 = (gmx_pos[0] - 10, gmx_pos[1], gmx + 15, gmy + 13) rect2 = (gmx_pos[0] - 5, gmx_pos[1] + 5, gmx + 5, gmy + 3) def remove_zeros(arr): # находим строки и столбцы полностью пустые empty_cols, empty_rows = arr.sum(axis=0), arr.sum(axis=1) # и убираем их из текущей фигуры return arr[empty_rows != False, :][:, empty_cols != False] def rotate(figure): # помещаем фигуру в квадрат side_size x side_size side_size = max(figure.shape) zeros = np.zeros((side_size, side_size), dtype=bool) zeros[:figure.shape[0], :figure.shape[1]] = figure figure = zeros # создаём новый массив повёрнутый на 90 градусов nf = np.empty(figure.shape, dtype=bool) for i in range(side_size): for j in range(side_size): nf[side_size - i - 1][j] = figure[j][i] return remove_zeros(nf) def prepare_figures(figures): result = figures[:3] # генерируем все положения для линейных фигур (2 варианта) for figure in figures[3:][:4]: r_figure = rotate(figure) # INFO: не убирать .T (нужно для корректного отображения фигур) result += [remove_zeros(figure.T), r_figure.T] # генерируем угловые фигуры (4 варианта) for figure in figures[-3:]: # INFO: не убирать .T (нужно для корректного отображения фигур) result.append(remove_zeros(figure.T)) for _ in range(3): figure = rotate(figure) result.append(figure.T) return result def AAfilledRoundedRect(surface, rect, color, radius=0.2): """ surface : destination rect : rectangle color : rgb or rgba radius : 0 <= radius <= 1 """ rect, color = pygame.Rect(rect), pygame.Color(*color) alpha = color.a color.a = 0 pos = rect.topleft rect.topleft = 0, 0 rectangle = pygame.Surface(rect.size, pygame.SRCALPHA) circle = pygame.Surface([min(rect.size) * 3] * 2, pygame.SRCALPHA) pygame.draw.ellipse(circle, (0, 0, 0), circle.get_rect(), 0) circle = pygame.transform.smoothscale( circle, [int(min(rect.size) * radius)] * 2) radius = rectangle.blit(circle, (0, 0)) radius.bottomright = rect.bottomright rectangle.blit(circle, radius) radius.topright = rect.topright rectangle.blit(circle, radius) radius.bottomleft = rect.bottomleft rectangle.blit(circle, radius) rectangle.fill((0, 0, 0), rect.inflate(-radius.w, 0)) rectangle.fill((0, 0, 0), rect.inflate(0, -radius.h)) rectangle.fill(color, special_flags=pygame.BLEND_RGBA_MAX) rectangle.fill((255, 255, 255, alpha), special_flags=pygame.BLEND_RGBA_MIN) return surface.blit(rectangle, pos) def draw_text(r, font, color, position, shift_y, text): xp, yp = position # режем строку на блоки for line in text.split('\n'): # рисуем строку text = font.render(line, True, color) # переносим на отрисовочный слой r.blit(text, (xp, yp)) # переводим указатель на новую строку yp += shift_y class Board: def __init__(self, size_x=10, size_y=10): self.width = size_x self.height = size_y self.cells = np.zeros((size_y, size_y)) def clear(self): self.cells = np.zeros((self.width, self.height)) def set(self, pos, figure, color=1): width, height = len(figure), len(figure[0]) x_pos, y_pos = pos[0], pos[1] for y in range(y_pos, y_pos + height): for x in range(x_pos, x_pos + width): if figure[x - x_pos][y - y_pos]: self.cells[y, x] = color * figure[x - x_pos][y - y_pos] def can_set(self, pos, figure): width, height = len(figure), len(figure[0]) x_pos, y_pos = pos[0], pos[1] # проверка на выход из границ игрового поля pole_cond = x_pos >= 0 and x_pos + width <= self.width and\ y_pos >= 0 and y_pos + height <= self.height if not pole_cond: return False for y in range(y_pos, y_pos + height): for x in range(x_pos, x_pos + width): if self.cells[y, x] * figure[x - x_pos, y - y_pos] != 0: return False return True def draw(self, display): for j, row in enumerate(self.cells): for i, item in enumerate(row): rect = (shift_pos[0] + i * TILE_SIZE + TILE_SHIFT, shift_pos[1] + j * TILE_SIZE + TILE_SHIFT, TILE_SKIP, TILE_SKIP) AAfilledRoundedRect(display, rect, colors[item]) def get_lines(self): items = [] for row in self.cells: if np.all(row > 0): items.append(row) for col in self.cells.T: if np.all(col > 0): items.append(col) return items board = Board(size_x=BOARD_SIZE, size_y=BOARD_SIZE) figures = prepare_figures(figures) class App: MAX_COUNTDOWN = 1 GAME_FPS = 60 def __init__(self, width=game_width, height=game_height): self.figure_drag = False self.figure_index = -1 self.generate_figures() self.width = width self.height = height self._running = True self._display_surf = None self.game_over = False self.clock = pygame.time.Clock() self.cwd = Path(os.path.dirname(os.path.abspath(__file__))) self.remove_animation = False self.remove_countdown = App.MAX_COUNTDOWN self.game_score = 0 self.score_file = self.cwd / 'gamescore.txt' game_score_value = 0 if self.score_file.exists(): try: game_score_value = int(self.score_file.open('r').read()) except ValueError: pass self.game_highscore = game_score_value self.lines = None def generate_figures(self): self.basket_figures = np.random.choice(figures, size=MAX_BASKET_SIZE) self.basket_colors = np.random.randint(1, len(colors), size=MAX_BASKET_SIZE) self.basket_count = 0 def on_init(self): pygame.init() pygame.display.set_caption('1010') self._display_surf = pygame.display.set_mode((self.width, self.height), pygame.HWSURFACE) self._running = True path_to_font = str(self.cwd / 'resources' / 'FiraMono-Regular.ttf') self.font = pygame.font.Font(path_to_font, 20) self.bigfont = pygame.font.Font(path_to_font, 48) def on_event(self, event): if event.type == pygame.QUIT: self._running = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self._running = False if self.remove_animation: return if event.type == pygame.MOUSEBUTTONDOWN: if event.button == LEFT_MOUSE: x, y = pygame.mouse.get_pos() if not self.figure_drag and y >= basket_pos[0][1]: self.figure_index = x // (game_width // MAX_BASKET_SIZE) self.figure_drag = True elif self.figure_drag: # проверка на вхождения xy в границы игрового поля figure_in = x > shift_pos[0] and x < (shift_pos[0] + TILE_SIZE * board.width) and\ y > shift_pos[1] and y < (shift_pos[1] + TILE_SIZE * board.height) if figure_in: index_x = int(np.ceil((x - shift_pos[0] + TILE_SHIFT) / TILE_SIZE) - 1) index_y = int(np.ceil((y - shift_pos[1] + TILE_SHIFT) / TILE_SIZE) - 1) # можно ли установить фигуру на поле if board.can_set((index_x, index_y), self.basket_figures[self.figure_index]): self.game_score += int(self.basket_figures[self.figure_index].sum()) board.set( (index_x, index_y), self.basket_figures[self.figure_index], color=self.basket_colors[self.figure_index]) # удаляем фигуру из ячейки корзины self.basket_figures[self.figure_index] = np.array([[]]) self.basket_count += 1 # генерируем новые фигуры, если корзина пуста if self.basket_count == MAX_BASKET_SIZE: self.generate_figures() self.figure_drag = False self.figure_index = -1 if self.game_over: board.clear() self.generate_figures() self.game_highscore = max(self.game_score, self.game_highscore) self.save_game_score() self.game_over = False self.game_score = 0 def on_loop(self): if not self.remove_animation: # помещение блоков для анимации items = board.get_lines() if len(items) > 0: self.lines = items self.remove_animation = True if not self.game_over and not self.remove_animation: # проверка игры на проигрыш figure_cant_set = True for figure in self.basket_figures: if not figure_cant_set: break if figure.sum() == 0: continue for x, y in product(range(board.width), range(board.height)): if board.can_set((x, y), figure): figure_cant_set = False break if figure_cant_set: self.game_over = True else: # реализация анимации удаления заполенной полосы if self.remove_countdown == 0: all_clear = True for item in self.lines: if item.sum() > 0: all_clear = False item[item.astype('bool').argmax()] = 0 self.game_score += 1 if all_clear: self.remove_animation = False self.lines = None self.remove_countdown = App.MAX_COUNTDOWN else: self.remove_countdown -= 1 self.game_highscore = max(self.game_score, self.game_highscore) def on_render(self): # рисование подложки pygame.draw.rect(self._display_surf, background_color, (0, 0, self.width, self.height)) # рисование основого игрового поля board.draw(self._display_surf) # рисование подложки для фигур for k in range(MAX_BASKET_SIZE): for j in range(MAX_BASKET_TILES): for i in range(MAX_BASKET_TILES): rect = [shift_pos[0], shift_pos[1], TILE_SKIP, TILE_SKIP] rect[0] += k * TILE_SIZE * (MAX_BASKET_TILES + 1) + i * TILE_SIZE + TILE_SHIFT rect[1] += (board.height + 1) * TILE_SIZE + j * TILE_SIZE + TILE_SHIFT AAfilledRoundedRect(self._display_surf, rect, layout_color) # рисование фигура в корзинах for index, (x, y) in enumerate(basket_pos): if index == self.figure_index: x, y = pygame.mouse.get_pos() x -= TILE_SIZE // 2 y -= TILE_SIZE // 2 for j, row in enumerate(self.basket_figures[index].T): for i, item in enumerate(row): if item > 0: rect = (x + i * TILE_SIZE + TILE_SHIFT, y + j * TILE_SIZE + TILE_SHIFT, TILE_SKIP, TILE_SKIP) AAfilledRoundedRect( self._display_surf, rect, colors[self.basket_colors[index]]) # вывод игровых очков text_pos = (TILE_SIZE * (board.width + 1), shift_pos[1] + 1) render_text = f'набранный рекорд\n{self.game_highscore}\nтекущий счёт\n{self.game_score}' draw_text(self._display_surf, self.font, text_color, text_pos, 30, render_text) if self.game_over: AAfilledRoundedRect(self._display_surf, rect1, colors[1], 0.2) AAfilledRoundedRect(self._display_surf, rect2, layout_color, 0.2) draw_text(self._display_surf, self.bigfont, text_color, gmx_pos, 0, game_over_text) pygame.display.flip() def save_game_score(self): self.score_file.open('w').write(str(self.game_highscore)) def on_cleanup(self): pygame.quit() def on_execute(self): if self.on_init() is False: self._running = False while self._running: for event in pygame.event.get(): self.on_event(event) self.on_loop() self.on_render() self.clock.tick(App.GAME_FPS) self.save_game_score() self.on_cleanup() if __name__ == '__main__': app = App() app.on_execute()
[ "pygame.event.get", "numpy.empty", "pygame.Rect", "numpy.arange", "pygame.font.Font", "pygame.mouse.get_pos", "os.path.abspath", "pygame.display.set_mode", "numpy.random.choice", "pygame.display.set_caption", "pygame.quit", "pygame.Surface", "numpy.ceil", "pygame.draw.rect", "pygame.init", "pygame.time.Clock", "numpy.all", "pygame.Color", "numpy.zeros", "pygame.display.flip", "numpy.array" ]
[((764, 786), 'numpy.array', 'np.array', (['[[True] * 5]'], {}), '([[True] * 5])\n', (772, 786), True, 'import numpy as np\n'), ((792, 814), 'numpy.array', 'np.array', (['[[True] * 4]'], {}), '([[True] * 4])\n', (800, 814), True, 'import numpy as np\n'), ((820, 842), 'numpy.array', 'np.array', (['[[True] * 3]'], {}), '([[True] * 3])\n', (828, 842), True, 'import numpy as np\n'), ((848, 870), 'numpy.array', 'np.array', (['[[True] * 2]'], {}), '([[True] * 2])\n', (856, 870), True, 'import numpy as np\n'), ((899, 973), 'numpy.array', 'np.array', (['[[True, False, False], [True, False, False], [True, True, True]]'], {}), '([[True, False, False], [True, False, False], [True, True, True]])\n', (907, 973), True, 'import numpy as np\n'), ((979, 1054), 'numpy.array', 'np.array', (['[[True, False, False], [True, False, False], [True, True, False]]'], {}), '([[True, False, False], [True, False, False], [True, True, False]])\n', (987, 1054), True, 'import numpy as np\n'), ((1060, 1099), 'numpy.array', 'np.array', (['[[True, False], [True, True]]'], {}), '([[True, False], [True, True]])\n', (1068, 1099), True, 'import numpy as np\n'), ((2500, 2544), 'numpy.zeros', 'np.zeros', (['(side_size, side_size)'], {'dtype': 'bool'}), '((side_size, side_size), dtype=bool)\n', (2508, 2544), True, 'import numpy as np\n'), ((2681, 2715), 'numpy.empty', 'np.empty', (['figure.shape'], {'dtype': 'bool'}), '(figure.shape, dtype=bool)\n', (2689, 2715), True, 'import numpy as np\n'), ((3832, 3874), 'pygame.Surface', 'pygame.Surface', (['rect.size', 'pygame.SRCALPHA'], {}), '(rect.size, pygame.SRCALPHA)\n', (3846, 3874), False, 'import pygame\n'), ((617, 663), 'numpy.array', 'np.array', (['[[True] * 3, [True] * 3, [True] * 3]'], {}), '([[True] * 3, [True] * 3, [True] * 3])\n', (625, 663), True, 'import numpy as np\n'), ((671, 709), 'numpy.array', 'np.array', (['[[True, True], [True, True]]'], {}), '([[True, True], [True, True]])\n', (679, 709), True, 'import numpy as np\n'), ((717, 735), 'numpy.array', 'np.array', (['[[True]]'], {}), '([[True]])\n', (725, 735), True, 'import numpy as np\n'), ((1604, 1665), 'numpy.arange', 'np.arange', (['(0)', '(3 * MAX_BASKET_TILES * TILE_SIZE)', '(TILE_SIZE * 6)'], {}), '(0, 3 * MAX_BASKET_TILES * TILE_SIZE, TILE_SIZE * 6)\n', (1613, 1665), True, 'import numpy as np\n'), ((3693, 3710), 'pygame.Rect', 'pygame.Rect', (['rect'], {}), '(rect)\n', (3704, 3710), False, 'import pygame\n'), ((3712, 3732), 'pygame.Color', 'pygame.Color', (['*color'], {}), '(*color)\n', (3724, 3732), False, 'import pygame\n'), ((5163, 5189), 'numpy.zeros', 'np.zeros', (['(size_y, size_y)'], {}), '((size_y, size_y))\n', (5171, 5189), True, 'import numpy as np\n'), ((5233, 5268), 'numpy.zeros', 'np.zeros', (['(self.width, self.height)'], {}), '((self.width, self.height))\n', (5241, 5268), True, 'import numpy as np\n'), ((7275, 7294), 'pygame.time.Clock', 'pygame.time.Clock', ([], {}), '()\n', (7292, 7294), False, 'import pygame\n'), ((7878, 7925), 'numpy.random.choice', 'np.random.choice', (['figures'], {'size': 'MAX_BASKET_SIZE'}), '(figures, size=MAX_BASKET_SIZE)\n', (7894, 7925), True, 'import numpy as np\n'), ((8073, 8086), 'pygame.init', 'pygame.init', ([], {}), '()\n', (8084, 8086), False, 'import pygame\n'), ((8095, 8129), 'pygame.display.set_caption', 'pygame.display.set_caption', (['"""1010"""'], {}), "('1010')\n", (8121, 8129), False, 'import pygame\n'), ((8159, 8227), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(self.width, self.height)', 'pygame.HWSURFACE'], {}), '((self.width, self.height), pygame.HWSURFACE)\n', (8182, 8227), False, 'import pygame\n'), ((8354, 8388), 'pygame.font.Font', 'pygame.font.Font', (['path_to_font', '(20)'], {}), '(path_to_font, 20)\n', (8370, 8388), False, 'import pygame\n'), ((8412, 8446), 'pygame.font.Font', 'pygame.font.Font', (['path_to_font', '(48)'], {}), '(path_to_font, 48)\n', (8428, 8446), False, 'import pygame\n'), ((12543, 12634), 'pygame.draw.rect', 'pygame.draw.rect', (['self._display_surf', 'background_color', '(0, 0, self.width, self.height)'], {}), '(self._display_surf, background_color, (0, 0, self.width,\n self.height))\n', (12559, 12634), False, 'import pygame\n'), ((14493, 14514), 'pygame.display.flip', 'pygame.display.flip', ([], {}), '()\n', (14512, 14514), False, 'import pygame\n'), ((14648, 14661), 'pygame.quit', 'pygame.quit', ([], {}), '()\n', (14659, 14661), False, 'import pygame\n'), ((6631, 6646), 'numpy.all', 'np.all', (['(row > 0)'], {}), '(row > 0)\n', (6637, 6646), True, 'import numpy as np\n'), ((6730, 6745), 'numpy.all', 'np.all', (['(col > 0)'], {}), '(col > 0)\n', (6736, 6745), True, 'import numpy as np\n'), ((14813, 14831), 'pygame.event.get', 'pygame.event.get', ([], {}), '()\n', (14829, 14831), False, 'import pygame\n'), ((7335, 7360), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (7350, 7360), False, 'import os\n'), ((8843, 8865), 'pygame.mouse.get_pos', 'pygame.mouse.get_pos', ([], {}), '()\n', (8863, 8865), False, 'import pygame\n'), ((13396, 13418), 'pygame.mouse.get_pos', 'pygame.mouse.get_pos', ([], {}), '()\n', (13416, 13418), False, 'import pygame\n'), ((10216, 10230), 'numpy.array', 'np.array', (['[[]]'], {}), '([[]])\n', (10224, 10230), True, 'import numpy as np\n'), ((9430, 9482), 'numpy.ceil', 'np.ceil', (['((x - shift_pos[0] + TILE_SHIFT) / TILE_SIZE)'], {}), '((x - shift_pos[0] + TILE_SHIFT) / TILE_SIZE)\n', (9437, 9482), True, 'import numpy as np\n'), ((9526, 9578), 'numpy.ceil', 'np.ceil', (['((y - shift_pos[1] + TILE_SHIFT) / TILE_SIZE)'], {}), '((y - shift_pos[1] + TILE_SHIFT) / TILE_SIZE)\n', (9533, 9578), True, 'import numpy as np\n')]
#-------------------------------------------------------------- # This is a demo file intended to show the use of the SNIC algorithm # Please compile the C files of snic.h and snic.c using: # "python snic.c" on the command prompt prior to using this file. # # To see the demo use: "python SNICdemo.py" on the command prompt #------------------------------------------------------------------ import os import subprocess from PIL import Image from skimage.io import imread,imshow import numpy as np from timeit import default_timer as timer from _snic.lib import SNIC_main from cffi import FFI def segment(imgname,numsuperpixels,compactness,doRGBtoLAB): #-------------------------------------------------------------- # read image and change image shape from (h,w,c) to (c,h,w) #-------------------------------------------------------------- img = Image.open(imgname) # img = imread(imgname) img = np.asarray(img) print(img.shape) dims = img.shape h,w,c = dims[0],dims[1],1 if len(dims) > 1: c = dims[2] img = img.transpose(2,0,1) print(c, "channels") #-------------------------------------------------------------- # Reshape image to a single dimensional vector #-------------------------------------------------------------- img = img.reshape(-1).astype(np.double) labels = np.zeros((h,w), dtype = np.int32) numlabels = np.zeros(1,dtype = np.int32) #-------------------------------------------------------------- # Prepare the pointers to pass to the C function #-------------------------------------------------------------- ffibuilder = FFI() pinp = ffibuilder.cast("double*", ffibuilder.from_buffer(img)) plabels = ffibuilder.cast("int*", ffibuilder.from_buffer(labels.reshape(-1))) pnumlabels = ffibuilder.cast("int*", ffibuilder.from_buffer(numlabels)) start = timer() SNIC_main(pinp,w,h,c,numsuperpixels,compactness,doRGBtoLAB,plabels,pnumlabels) end = timer() #-------------------------------------------------------------- # Collect labels #-------------------------------------------------------------- print("number of superpixels: ", numlabels[0]) print("time taken in seconds: ", end-start) return labels.reshape(h,w),numlabels[0] # lib.SNICmain.argtypes = [np.ctypeslib.ndpointer(dtype=POINTER(c_double),ndim=2)]+[c_int]*4 +[c_double,c_bool,ctypes.data_as(POINTER(c_int)),ctypes.data_as(POINTER(c_int))] def drawBoundaries(imgname,labels,numlabels): img = Image.open(imgname) # img = imread(imgname) img = np.array(img) print(img.shape) ht,wd = labels.shape for y in range(1,ht-1): for x in range(1,wd-1): if labels[y,x-1] != labels[y,x+1] or labels[y-1,x] != labels[y+1,x]: img[y,x,:] = 0 return img # Before calling this function, please compile the C code using # "python compile.py" on the command line def snicdemo(): #-------------------------------------------------------------- # Set parameters and call the C function #-------------------------------------------------------------- numsuperpixels = 500 compactness = 20.0 doRGBtoLAB = True # only works if it is a three channel image # imgname = "/Users/achanta/Pictures/classics/lena.png" imgname = "bee.png" labels,numlabels = segment(imgname,numsuperpixels,compactness,doRGBtoLAB) #-------------------------------------------------------------- # Display segmentation result #------------------------------------------------------------ segimg = drawBoundaries(imgname,labels,numlabels) # Image.fromarray(segimg).show() Image.fromarray(segimg).save("bee_snic.png") return snicdemo()
[ "cffi.FFI", "timeit.default_timer", "numpy.asarray", "numpy.zeros", "PIL.Image.open", "numpy.array", "PIL.Image.fromarray", "_snic.lib.SNIC_main" ]
[((854, 873), 'PIL.Image.open', 'Image.open', (['imgname'], {}), '(imgname)\n', (864, 873), False, 'from PIL import Image\n'), ((906, 921), 'numpy.asarray', 'np.asarray', (['img'], {}), '(img)\n', (916, 921), True, 'import numpy as np\n'), ((1302, 1334), 'numpy.zeros', 'np.zeros', (['(h, w)'], {'dtype': 'np.int32'}), '((h, w), dtype=np.int32)\n', (1310, 1334), True, 'import numpy as np\n'), ((1349, 1376), 'numpy.zeros', 'np.zeros', (['(1)'], {'dtype': 'np.int32'}), '(1, dtype=np.int32)\n', (1357, 1376), True, 'import numpy as np\n'), ((1572, 1577), 'cffi.FFI', 'FFI', ([], {}), '()\n', (1575, 1577), False, 'from cffi import FFI\n'), ((1806, 1813), 'timeit.default_timer', 'timer', ([], {}), '()\n', (1811, 1813), True, 'from timeit import default_timer as timer\n'), ((1815, 1905), '_snic.lib.SNIC_main', 'SNIC_main', (['pinp', 'w', 'h', 'c', 'numsuperpixels', 'compactness', 'doRGBtoLAB', 'plabels', 'pnumlabels'], {}), '(pinp, w, h, c, numsuperpixels, compactness, doRGBtoLAB, plabels,\n pnumlabels)\n', (1824, 1905), False, 'from _snic.lib import SNIC_main\n'), ((1901, 1908), 'timeit.default_timer', 'timer', ([], {}), '()\n', (1906, 1908), True, 'from timeit import default_timer as timer\n'), ((2425, 2444), 'PIL.Image.open', 'Image.open', (['imgname'], {}), '(imgname)\n', (2435, 2444), False, 'from PIL import Image\n'), ((2477, 2490), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (2485, 2490), True, 'import numpy as np\n'), ((3487, 3510), 'PIL.Image.fromarray', 'Image.fromarray', (['segimg'], {}), '(segimg)\n', (3502, 3510), False, 'from PIL import Image\n')]
""" @brief test log(time=16s) """ import unittest import numpy from pandas import DataFrame from pyquickhelper.pycode import ExtTestCase from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.naive_bayes import BernoulliNB from skl2onnx import convert_sklearn from skl2onnx.common.data_types import FloatTensorType from mlprodict.onnxrt import OnnxInference from mlprodict.tools.asv_options_helper import get_opset_number_from_onnx, get_ir_version_from_onnx from mlprodict.testing.test_utils import _capture_output class TestRtValidateNaive(ExtTestCase): def fit_classification_model(self, model, n_classes, is_int=False, pos_features=False, label_string=False): X, y = make_classification(n_classes=n_classes, n_features=100, n_samples=1000, random_state=42, n_informative=7) if label_string: y = numpy.array(['cl%d' % cl for cl in y]) X = X.astype(numpy.int64) if is_int else X.astype(numpy.float32) if pos_features: X = numpy.abs(X) X_train, X_test, y_train, _ = train_test_split(X, y, test_size=0.5, random_state=42) model.fit(X_train, y_train) return model, X_test def test_model_bernoulli_nb_bc_python(self): model, X = self.fit_classification_model(BernoulliNB(), 2) model_onnx = convert_sklearn( model, "?", [("input", FloatTensorType([None, X.shape[1]]))]) exp1 = model.predict(X) exp = model.predict_proba(X) oinf = OnnxInference(model_onnx, runtime='python') got = oinf.run({'input': X}) self.assertEqualArray(exp1, got['output_label']) got2 = DataFrame(got['output_probability']).values self.assertEqualArray(exp, got2, decimal=4) def test_model_bernoulli_nb_bc_onnxruntime1(self): model, X = self.fit_classification_model(BernoulliNB(), 2) model_onnx = convert_sklearn( model, "?", [("input", FloatTensorType([None, X.shape[1]]))], target_opset=get_opset_number_from_onnx()) exp1 = model.predict(X) exp = model.predict_proba(X) model_onnx.ir_version = get_ir_version_from_onnx() oinf = _capture_output( lambda: OnnxInference(model_onnx, runtime='onnxruntime1'), 'c')[0] got = oinf.run({'input': X}) self.assertEqualArray(exp1, got['output_label']) got2 = DataFrame(got['output_probability']).values self.assertEqualArray(exp, got2, decimal=4) def test_model_bernoulli_nb_bc_onnxruntime2(self): model, X = self.fit_classification_model(BernoulliNB(), 2) model_onnx = convert_sklearn( model, "?", [("input", FloatTensorType([None, X.shape[1]]))], options={id(model): {'zipmap': False}}, target_opset=get_opset_number_from_onnx()) exp1 = model.predict(X) exp = model.predict_proba(X) model_onnx.ir_version = get_ir_version_from_onnx() oinf = _capture_output( lambda: OnnxInference(model_onnx, runtime='onnxruntime2'), 'c')[0] got = oinf.run({'input': X}) self.assertEqualArray(exp1, got['label']) got2 = DataFrame(got['probabilities']).values self.assertEqualArray(exp, got2, decimal=4) if __name__ == "__main__": unittest.main()
[ "unittest.main", "pandas.DataFrame", "mlprodict.tools.asv_options_helper.get_opset_number_from_onnx", "numpy.abs", "sklearn.model_selection.train_test_split", "mlprodict.tools.asv_options_helper.get_ir_version_from_onnx", "sklearn.datasets.make_classification", "skl2onnx.common.data_types.FloatTensorType", "numpy.array", "mlprodict.onnxrt.OnnxInference", "sklearn.naive_bayes.BernoulliNB" ]
[((3510, 3525), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3523, 3525), False, 'import unittest\n'), ((783, 893), 'sklearn.datasets.make_classification', 'make_classification', ([], {'n_classes': 'n_classes', 'n_features': '(100)', 'n_samples': '(1000)', 'random_state': '(42)', 'n_informative': '(7)'}), '(n_classes=n_classes, n_features=100, n_samples=1000,\n random_state=42, n_informative=7)\n', (802, 893), False, 'from sklearn.datasets import make_classification\n'), ((1205, 1259), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.5)', 'random_state': '(42)'}), '(X, y, test_size=0.5, random_state=42)\n', (1221, 1259), False, 'from sklearn.model_selection import train_test_split\n'), ((1694, 1737), 'mlprodict.onnxrt.OnnxInference', 'OnnxInference', (['model_onnx'], {'runtime': '"""python"""'}), "(model_onnx, runtime='python')\n", (1707, 1737), False, 'from mlprodict.onnxrt import OnnxInference\n'), ((2335, 2361), 'mlprodict.tools.asv_options_helper.get_ir_version_from_onnx', 'get_ir_version_from_onnx', ([], {}), '()\n', (2359, 2361), False, 'from mlprodict.tools.asv_options_helper import get_opset_number_from_onnx, get_ir_version_from_onnx\n'), ((3134, 3160), 'mlprodict.tools.asv_options_helper.get_ir_version_from_onnx', 'get_ir_version_from_onnx', ([], {}), '()\n', (3158, 3160), False, 'from mlprodict.tools.asv_options_helper import get_opset_number_from_onnx, get_ir_version_from_onnx\n'), ((1001, 1041), 'numpy.array', 'numpy.array', (["[('cl%d' % cl) for cl in y]"], {}), "([('cl%d' % cl) for cl in y])\n", (1012, 1041), False, 'import numpy\n'), ((1154, 1166), 'numpy.abs', 'numpy.abs', (['X'], {}), '(X)\n', (1163, 1166), False, 'import numpy\n'), ((1479, 1492), 'sklearn.naive_bayes.BernoulliNB', 'BernoulliNB', ([], {}), '()\n', (1490, 1492), False, 'from sklearn.naive_bayes import BernoulliNB\n'), ((1847, 1883), 'pandas.DataFrame', 'DataFrame', (["got['output_probability']"], {}), "(got['output_probability'])\n", (1856, 1883), False, 'from pandas import DataFrame\n'), ((2048, 2061), 'sklearn.naive_bayes.BernoulliNB', 'BernoulliNB', ([], {}), '()\n', (2059, 2061), False, 'from sklearn.naive_bayes import BernoulliNB\n'), ((2594, 2630), 'pandas.DataFrame', 'DataFrame', (["got['output_probability']"], {}), "(got['output_probability'])\n", (2603, 2630), False, 'from pandas import DataFrame\n'), ((2795, 2808), 'sklearn.naive_bayes.BernoulliNB', 'BernoulliNB', ([], {}), '()\n', (2806, 2808), False, 'from sklearn.naive_bayes import BernoulliNB\n'), ((3386, 3417), 'pandas.DataFrame', 'DataFrame', (["got['probabilities']"], {}), "(got['probabilities'])\n", (3395, 3417), False, 'from pandas import DataFrame\n'), ((2203, 2231), 'mlprodict.tools.asv_options_helper.get_opset_number_from_onnx', 'get_opset_number_from_onnx', ([], {}), '()\n', (2229, 2231), False, 'from mlprodict.tools.asv_options_helper import get_opset_number_from_onnx, get_ir_version_from_onnx\n'), ((3002, 3030), 'mlprodict.tools.asv_options_helper.get_opset_number_from_onnx', 'get_opset_number_from_onnx', ([], {}), '()\n', (3028, 3030), False, 'from mlprodict.tools.asv_options_helper import get_opset_number_from_onnx, get_ir_version_from_onnx\n'), ((1570, 1605), 'skl2onnx.common.data_types.FloatTensorType', 'FloatTensorType', (['[None, X.shape[1]]'], {}), '([None, X.shape[1]])\n', (1585, 1605), False, 'from skl2onnx.common.data_types import FloatTensorType\n'), ((2139, 2174), 'skl2onnx.common.data_types.FloatTensorType', 'FloatTensorType', (['[None, X.shape[1]]'], {}), '([None, X.shape[1]])\n', (2154, 2174), False, 'from skl2onnx.common.data_types import FloatTensorType\n'), ((2414, 2463), 'mlprodict.onnxrt.OnnxInference', 'OnnxInference', (['model_onnx'], {'runtime': '"""onnxruntime1"""'}), "(model_onnx, runtime='onnxruntime1')\n", (2427, 2463), False, 'from mlprodict.onnxrt import OnnxInference\n'), ((2886, 2921), 'skl2onnx.common.data_types.FloatTensorType', 'FloatTensorType', (['[None, X.shape[1]]'], {}), '([None, X.shape[1]])\n', (2901, 2921), False, 'from skl2onnx.common.data_types import FloatTensorType\n'), ((3213, 3262), 'mlprodict.onnxrt.OnnxInference', 'OnnxInference', (['model_onnx'], {'runtime': '"""onnxruntime2"""'}), "(model_onnx, runtime='onnxruntime2')\n", (3226, 3262), False, 'from mlprodict.onnxrt import OnnxInference\n')]
import numpy as np from mushroom.algorithms.agent import Agent from mushroom.approximators import Regressor from mushroom.approximators.parametric import LinearApproximator class SAC(Agent): """ Stochastic Actor critic in the episodic setting as presented in: "Model-Free Reinforcement Learning with Continuous Action in Practice". Degris T. et al.. 2012. """ def __init__(self, policy, mdp_info, alpha_theta, alpha_v, lambda_par=.9, value_function_features=None, policy_features=None): """ Constructor. Args: policy (ParametricPolicy): a differentiable stochastic policy; mdp_info: information about the MDP; alpha_theta (Parameter): learning rate for policy update; alpha_v (Parameter): learning rate for the value function; lambda_par (float, 0.9): trace decay parameter; value_function_features (Features, None): features used by the value function approximator; policy_features (Features, None): features used by the policy. """ self._psi = value_function_features self._alpha_theta = alpha_theta self._alpha_v = alpha_v self._lambda = lambda_par super().__init__(policy, mdp_info, policy_features) if self._psi is not None: input_shape = (self._psi.size,) else: input_shape = mdp_info.observation_space.shape self._V = Regressor(LinearApproximator, input_shape=input_shape, output_shape=(1,)) self._e_v = np.zeros(self._V.weights_size) self._e_theta = np.zeros(self.policy.weights_size) def episode_start(self): self._e_v = np.zeros(self._V.weights_size) self._e_theta = np.zeros(self.policy.weights_size) super().episode_start() def fit(self, dataset): for step in dataset: s, a, r, ss, absorbing, _ = step s_phi = self.phi(s) if self.phi is not None else s s_psi = self._psi(s) if self._psi is not None else s ss_psi = self._psi(ss) if self._psi is not None else ss v_next = self._V(ss_psi) if not absorbing else 0 # Compute TD error delta = r + self.mdp_info.gamma * v_next - self._V(s_psi) # Update traces self._e_v = self.mdp_info.gamma * self._lambda * self._e_v + s_psi self._e_theta = self.mdp_info.gamma * self._lambda * \ self._e_theta + self.policy.diff_log(s_phi, a) # Update value function delta_v = self._alpha_v(s, a) * delta * self._e_v v_new = self._V.get_weights() + delta_v self._V.set_weights(v_new) # Update policy delta_theta = self._alpha_theta(s, a) * delta * self._e_theta theta_new = self.policy.get_weights() + delta_theta self.policy.set_weights(theta_new) class SAC_AVG(Agent): """ Stochastic Actor critic in the average reward setting as presented in: "Model-Free Reinforcement Learning with Continuous Action in Practice". <NAME>. et al.. 2012. """ def __init__(self, policy, mdp_info, alpha_theta, alpha_v, alpha_r, lambda_par=.9, value_function_features=None, policy_features=None): """ Constructor. Args: policy (ParametricPolicy): a differentiable stochastic policy; mdp_info: information about the MDP; alpha_theta (Parameter): learning rate for policy update; alpha_v (Parameter): learning rate for the value function; alpha_r (Parameter): learning rate for the reward trace; lambda_par (float, 0.9): trace decay parameter; value_function_features (Features, None): features used by the value function approximator; policy_features (Features, None): features used by the policy. """ self._psi = value_function_features self._alpha_theta = alpha_theta self._alpha_v = alpha_v self._alpha_r = alpha_r self._lambda = lambda_par super().__init__(policy, mdp_info, policy_features) if self._psi is not None: input_shape = (self._psi.size,) else: input_shape = mdp_info.observation_space.shape self._V = Regressor(LinearApproximator, input_shape=input_shape, output_shape=(1,)) self._e_v = np.zeros(self._V.weights_size) self._e_theta = np.zeros(self.policy.weights_size) self._r_bar = 0 def episode_start(self): self._e_v = np.zeros(self._V.weights_size) self._e_theta = np.zeros(self.policy.weights_size) super().episode_start() def fit(self, dataset): for step in dataset: s, a, r, ss, absorbing, _ = step s_phi = self.phi(s) if self.phi is not None else s s_psi = self._psi(s) if self._psi is not None else s ss_psi = self._psi(ss) if self._psi is not None else ss v_next = self._V(ss_psi) if not absorbing else 0 # Compute TD error delta = r - self._r_bar + v_next - self._V(s_psi) # Update traces self._r_bar += self._alpha_r() * delta self._e_v = self._lambda * self._e_v + s_psi self._e_theta = self._lambda * self._e_theta + \ self.policy.diff_log(s_phi, a) # Update value function delta_v = self._alpha_v(s, a) * delta * self._e_v v_new = self._V.get_weights() + delta_v self._V.set_weights(v_new) # Update policy delta_theta = self._alpha_theta(s, a) * delta * self._e_theta theta_new = self.policy.get_weights() + delta_theta self.policy.set_weights(theta_new)
[ "numpy.zeros", "mushroom.approximators.Regressor" ]
[((1497, 1570), 'mushroom.approximators.Regressor', 'Regressor', (['LinearApproximator'], {'input_shape': 'input_shape', 'output_shape': '(1,)'}), '(LinearApproximator, input_shape=input_shape, output_shape=(1,))\n', (1506, 1570), False, 'from mushroom.approximators import Regressor\n'), ((1620, 1650), 'numpy.zeros', 'np.zeros', (['self._V.weights_size'], {}), '(self._V.weights_size)\n', (1628, 1650), True, 'import numpy as np\n'), ((1675, 1709), 'numpy.zeros', 'np.zeros', (['self.policy.weights_size'], {}), '(self.policy.weights_size)\n', (1683, 1709), True, 'import numpy as np\n'), ((1760, 1790), 'numpy.zeros', 'np.zeros', (['self._V.weights_size'], {}), '(self._V.weights_size)\n', (1768, 1790), True, 'import numpy as np\n'), ((1815, 1849), 'numpy.zeros', 'np.zeros', (['self.policy.weights_size'], {}), '(self.policy.weights_size)\n', (1823, 1849), True, 'import numpy as np\n'), ((4447, 4520), 'mushroom.approximators.Regressor', 'Regressor', (['LinearApproximator'], {'input_shape': 'input_shape', 'output_shape': '(1,)'}), '(LinearApproximator, input_shape=input_shape, output_shape=(1,))\n', (4456, 4520), False, 'from mushroom.approximators import Regressor\n'), ((4570, 4600), 'numpy.zeros', 'np.zeros', (['self._V.weights_size'], {}), '(self._V.weights_size)\n', (4578, 4600), True, 'import numpy as np\n'), ((4625, 4659), 'numpy.zeros', 'np.zeros', (['self.policy.weights_size'], {}), '(self.policy.weights_size)\n', (4633, 4659), True, 'import numpy as np\n'), ((4734, 4764), 'numpy.zeros', 'np.zeros', (['self._V.weights_size'], {}), '(self._V.weights_size)\n', (4742, 4764), True, 'import numpy as np\n'), ((4789, 4823), 'numpy.zeros', 'np.zeros', (['self.policy.weights_size'], {}), '(self.policy.weights_size)\n', (4797, 4823), True, 'import numpy as np\n')]
from Binary.Scripts.utils import * import scipy.optimize as opt from scipy import stats from sklearn.linear_model import LinearRegression import numpy as np np.random.seed(1234) # # def obj_fun(theta, x, y_): pre_dis = np.dot(x, theta) loss = np.sum((pre_dis - y_) ** 2) return loss class xai_rnn(object): """class for explaining the rnn prediction""" def __init__(self, model, data,): """ Args: model: target rnn model. data: data sample needed to be explained. label: label of the data sample. start: value of function start. """ self.model = model self.data = data self.seq_len = data.shape[1] self.seq_len = data[0].shape[0] def xai_feature(self, samp_num, option= 'None'): """extract the important features from the input data Arg: fea_num: number of features that needed by the user samp_num: number of data used for explanation return: fea: extracted features """ # cen = int(self.seq_len/2) # half_tl = int(self.tl/2) sample = np.random.randint(0, FEANUM, samp_num) data_explain = np.zeros([samp_num, 200]) for i, size in enumerate(sample, start=0): inactive = np.random.choice(FEANUM, size, replace=False) tmp_sampled = np.copy(self.data) tmp_sampled[0,inactive] = 0 # np.random.choice(range(257), size, replace = True) #1 - tmp_sampled[0,inactive] data_explain[i] = tmp_sampled # label_sampled = label_sampled.reshape(label_sampled.shape[0], 1) label_sampled = self.model.predict(data_explain, batch_size = 500, verbose = 0)[:, 100, 1:2] linreg = LinearRegression(fit_intercept=False) linreg.fit(data_explain, label_sampled) result = np.argsort(np.abs(linreg.coef_)).reshape([FEANUM]) importance_score = result[::-1] return importance_score def gauss_mix_model(self, X, y, model_num, min_err=0.1): [data_num, fea_num] = np.shape(X) mean = np.random.random([model_num, 1]) * 100 sigma = np.random.random([model_num, 1]) * 100 pi = np.ones([model_num, 1]) / model_num new_mean = np.zeros_like(mean) new_sigma = np.zeros_like(sigma) new_pi = np.zeros_like(pi) new_z = np.zeros([data_num, model_num]) err = np.linalg.norm(mean - new_mean) nk = np.zeros((model_num, 1)) while (err > min_err): for index in range(data_num): for kindex in range(model_num): new_z[index, kindex] = pi[kindex] * stats.norm(mean[kindex, 0], sigma[kindex, 0]).pdf(y[index]) new_z[index, :] = new_z[index, :] / np.sum(new_z[index, :]) for kindex in range(model_num): nk[kindex] = np.sum(new_z[:, kindex]) new_pi[kindex, 0] = np.sum(new_z[:, kindex]) / data_num sum_mean = 0 sum_sigma = 0 for nindex in range(data_num): tmp = new_z[nindex, kindex] * y[nindex] sum_mean = sum_mean + tmp new_mean[kindex, :] = sum_mean / nk[kindex] for nindex in range(data_num): vec = (y[nindex] - new_mean[kindex, 0]) tmp = new_z[nindex, kindex] * (vec * vec) sum_sigma = sum_sigma + tmp new_sigma[kindex, 0] = sum_sigma / nk[kindex] err = np.linalg.norm(new_mean - mean) sigma = new_sigma pi = new_pi mean = new_mean weight = np.zeros(fea_num) s = 1e4 init_k = np.ones([fea_num, 1]) cons = ({'type': 'ineq', 'fun': lambda x: np.array([s - (x[0] - x[1]) ** 2 - (x[1] - x[2]) ** 2])}) # for iindex in range(fea_num): # for kindex in range(model_num): # result = opt.minimize(obj_fun, init_k, args=(np.array(X), np.array(mean[kindex, :])), # constraints=cons) # weight[iindex] = result.x[iindex] * pi[kindex] + weight[iindex] result = opt.minimize(obj_fun, init_k, args=(np.array(X), np.array(mean[kindex, :])), constraints=cons) weight = result.x ###################################################################################### # X = r.matrix(X, nrow=data_explain.shape[0], ncol=data_explain.shape[1]) # Y = r.matrix(label_sampled, nrow=label_sampled.shape[0], ncol=label_sampled.shape[1]) # # n = r.nrow(X) # p = r.ncol(X) # results = r.fusedlasso1d(y=Y, X=X) # eps = 1e4 # # result = np.array(r.coef(results, np.sqrt(n * np.log(p)))[0])[:, -1] return weight
[ "numpy.zeros_like", "numpy.random.seed", "numpy.sum", "numpy.copy", "numpy.abs", "scipy.stats.norm", "numpy.zeros", "numpy.ones", "sklearn.linear_model.LinearRegression", "numpy.shape", "numpy.random.randint", "numpy.linalg.norm", "numpy.random.random", "numpy.array", "numpy.random.choice", "numpy.dot" ]
[((157, 177), 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), '(1234)\n', (171, 177), True, 'import numpy as np\n'), ((233, 249), 'numpy.dot', 'np.dot', (['x', 'theta'], {}), '(x, theta)\n', (239, 249), True, 'import numpy as np\n'), ((261, 288), 'numpy.sum', 'np.sum', (['((pre_dis - y_) ** 2)'], {}), '((pre_dis - y_) ** 2)\n', (267, 288), True, 'import numpy as np\n'), ((1175, 1213), 'numpy.random.randint', 'np.random.randint', (['(0)', 'FEANUM', 'samp_num'], {}), '(0, FEANUM, samp_num)\n', (1192, 1213), True, 'import numpy as np\n'), ((1237, 1262), 'numpy.zeros', 'np.zeros', (['[samp_num, 200]'], {}), '([samp_num, 200])\n', (1245, 1262), True, 'import numpy as np\n'), ((1794, 1831), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {'fit_intercept': '(False)'}), '(fit_intercept=False)\n', (1810, 1831), False, 'from sklearn.linear_model import LinearRegression\n'), ((2112, 2123), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (2120, 2123), True, 'import numpy as np\n'), ((2302, 2321), 'numpy.zeros_like', 'np.zeros_like', (['mean'], {}), '(mean)\n', (2315, 2321), True, 'import numpy as np\n'), ((2342, 2362), 'numpy.zeros_like', 'np.zeros_like', (['sigma'], {}), '(sigma)\n', (2355, 2362), True, 'import numpy as np\n'), ((2380, 2397), 'numpy.zeros_like', 'np.zeros_like', (['pi'], {}), '(pi)\n', (2393, 2397), True, 'import numpy as np\n'), ((2415, 2446), 'numpy.zeros', 'np.zeros', (['[data_num, model_num]'], {}), '([data_num, model_num])\n', (2423, 2446), True, 'import numpy as np\n'), ((2461, 2492), 'numpy.linalg.norm', 'np.linalg.norm', (['(mean - new_mean)'], {}), '(mean - new_mean)\n', (2475, 2492), True, 'import numpy as np\n'), ((2506, 2530), 'numpy.zeros', 'np.zeros', (['(model_num, 1)'], {}), '((model_num, 1))\n', (2514, 2530), True, 'import numpy as np\n'), ((3716, 3733), 'numpy.zeros', 'np.zeros', (['fea_num'], {}), '(fea_num)\n', (3724, 3733), True, 'import numpy as np\n'), ((3767, 3788), 'numpy.ones', 'np.ones', (['[fea_num, 1]'], {}), '([fea_num, 1])\n', (3774, 3788), True, 'import numpy as np\n'), ((1337, 1382), 'numpy.random.choice', 'np.random.choice', (['FEANUM', 'size'], {'replace': '(False)'}), '(FEANUM, size, replace=False)\n', (1353, 1382), True, 'import numpy as np\n'), ((1410, 1428), 'numpy.copy', 'np.copy', (['self.data'], {}), '(self.data)\n', (1417, 1428), True, 'import numpy as np\n'), ((2139, 2171), 'numpy.random.random', 'np.random.random', (['[model_num, 1]'], {}), '([model_num, 1])\n', (2155, 2171), True, 'import numpy as np\n'), ((2194, 2226), 'numpy.random.random', 'np.random.random', (['[model_num, 1]'], {}), '([model_num, 1])\n', (2210, 2226), True, 'import numpy as np\n'), ((2246, 2269), 'numpy.ones', 'np.ones', (['[model_num, 1]'], {}), '([model_num, 1])\n', (2253, 2269), True, 'import numpy as np\n'), ((3584, 3615), 'numpy.linalg.norm', 'np.linalg.norm', (['(new_mean - mean)'], {}), '(new_mean - mean)\n', (3598, 3615), True, 'import numpy as np\n'), ((2917, 2941), 'numpy.sum', 'np.sum', (['new_z[:, kindex]'], {}), '(new_z[:, kindex])\n', (2923, 2941), True, 'import numpy as np\n'), ((3856, 3911), 'numpy.array', 'np.array', (['[s - (x[0] - x[1]) ** 2 - (x[1] - x[2]) ** 2]'], {}), '([s - (x[0] - x[1]) ** 2 - (x[1] - x[2]) ** 2])\n', (3864, 3911), True, 'import numpy as np\n'), ((1908, 1928), 'numpy.abs', 'np.abs', (['linreg.coef_'], {}), '(linreg.coef_)\n', (1914, 1928), True, 'import numpy as np\n'), ((2820, 2843), 'numpy.sum', 'np.sum', (['new_z[index, :]'], {}), '(new_z[index, :])\n', (2826, 2843), True, 'import numpy as np\n'), ((2978, 3002), 'numpy.sum', 'np.sum', (['new_z[:, kindex]'], {}), '(new_z[:, kindex])\n', (2984, 3002), True, 'import numpy as np\n'), ((4297, 4308), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (4305, 4308), True, 'import numpy as np\n'), ((4310, 4335), 'numpy.array', 'np.array', (['mean[kindex, :]'], {}), '(mean[kindex, :])\n', (4318, 4335), True, 'import numpy as np\n'), ((2708, 2753), 'scipy.stats.norm', 'stats.norm', (['mean[kindex, 0]', 'sigma[kindex, 0]'], {}), '(mean[kindex, 0], sigma[kindex, 0])\n', (2718, 2753), False, 'from scipy import stats\n')]
import numpy as np import pandas as pd import matplotlib.pyplot as plt from scikitplot.metrics import plot_confusion_matrix, plot_roc class Plotting(): def plot_losses(self, training_losses, validation_losses): plt.figure() epochs = range(len(training_losses)) line1 = plt.plot(epochs, training_losses, label = "Training Loss") line2 = plt.plot(epochs, validation_losses, label = "Validation Loss") plt.xlabel("Epochs") plt.ylabel("Losses") plt.legend(loc = "upper right") plt.title("Training/Validation Loss Comparison") plt.savefig("plots/training_validation_loss_comp.png") plt.show() def stats_table(self, metrics): headers = list(metrics[0].keys()) table = pd.DataFrame(columns = headers) for metric in range(len(metrics)): table = table.append(metrics[metric], ignore_index = True) return table def visualise_images(self, images, labels, class_labels, fig_size = (25, 15), row_num = 5, col_num = 35): fig = plt.figure(figsize = fig_size) for i in np.arange(col_num): ax = fig.add_subplot(row_num, int(np.ceil(col_num / row_num)), i + 1, xticks = [], yticks = []) self._imshow(images[i]) ax.set_title(class_labels[labels[i]]) def _imshow(self, image): image = image / 2 + 0.5 #unnormalise image plt.imshow(np.transpose(image, (1, 2, 0))) def plot_roc_curve(self, model, probabilities, labels, figsize): plot_roc(labels, probabilities, figsize=figsize, title="ROC Curve") plt.savefig("plots/roc_curve.png") def plot_cm(self, model, predictions, labels, class_labels, figsize): plot_confusion_matrix(labels, predictions, figsize=figsize, labels=class_labels, x_tick_rotation=90, title="Confusion Matrix") plt.savefig("plots/confusion_matrix.png")
[ "matplotlib.pyplot.title", "pandas.DataFrame", "matplotlib.pyplot.show", "numpy.ceil", "matplotlib.pyplot.plot", "scikitplot.metrics.plot_roc", "matplotlib.pyplot.legend", "numpy.transpose", "matplotlib.pyplot.figure", "numpy.arange", "matplotlib.pyplot.ylabel", "scikitplot.metrics.plot_confusion_matrix", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.savefig" ]
[((225, 237), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (235, 237), True, 'import matplotlib.pyplot as plt\n'), ((299, 355), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs', 'training_losses'], {'label': '"""Training Loss"""'}), "(epochs, training_losses, label='Training Loss')\n", (307, 355), True, 'import matplotlib.pyplot as plt\n'), ((374, 434), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs', 'validation_losses'], {'label': '"""Validation Loss"""'}), "(epochs, validation_losses, label='Validation Loss')\n", (382, 434), True, 'import matplotlib.pyplot as plt\n'), ((445, 465), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epochs"""'], {}), "('Epochs')\n", (455, 465), True, 'import matplotlib.pyplot as plt\n'), ((474, 494), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Losses"""'], {}), "('Losses')\n", (484, 494), True, 'import matplotlib.pyplot as plt\n'), ((503, 532), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""'}), "(loc='upper right')\n", (513, 532), True, 'import matplotlib.pyplot as plt\n'), ((543, 591), 'matplotlib.pyplot.title', 'plt.title', (['"""Training/Validation Loss Comparison"""'], {}), "('Training/Validation Loss Comparison')\n", (552, 591), True, 'import matplotlib.pyplot as plt\n'), ((600, 654), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""plots/training_validation_loss_comp.png"""'], {}), "('plots/training_validation_loss_comp.png')\n", (611, 654), True, 'import matplotlib.pyplot as plt\n'), ((663, 673), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (671, 673), True, 'import matplotlib.pyplot as plt\n'), ((769, 798), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'headers'}), '(columns=headers)\n', (781, 798), True, 'import pandas as pd\n'), ((1091, 1119), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'fig_size'}), '(figsize=fig_size)\n', (1101, 1119), True, 'import matplotlib.pyplot as plt\n'), ((1140, 1158), 'numpy.arange', 'np.arange', (['col_num'], {}), '(col_num)\n', (1149, 1158), True, 'import numpy as np\n'), ((1611, 1678), 'scikitplot.metrics.plot_roc', 'plot_roc', (['labels', 'probabilities'], {'figsize': 'figsize', 'title': '"""ROC Curve"""'}), "(labels, probabilities, figsize=figsize, title='ROC Curve')\n", (1619, 1678), False, 'from scikitplot.metrics import plot_confusion_matrix, plot_roc\n'), ((1687, 1721), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""plots/roc_curve.png"""'], {}), "('plots/roc_curve.png')\n", (1698, 1721), True, 'import matplotlib.pyplot as plt\n'), ((1809, 1940), 'scikitplot.metrics.plot_confusion_matrix', 'plot_confusion_matrix', (['labels', 'predictions'], {'figsize': 'figsize', 'labels': 'class_labels', 'x_tick_rotation': '(90)', 'title': '"""Confusion Matrix"""'}), "(labels, predictions, figsize=figsize, labels=\n class_labels, x_tick_rotation=90, title='Confusion Matrix')\n", (1830, 1940), False, 'from scikitplot.metrics import plot_confusion_matrix, plot_roc\n'), ((1974, 2015), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""plots/confusion_matrix.png"""'], {}), "('plots/confusion_matrix.png')\n", (1985, 2015), True, 'import matplotlib.pyplot as plt\n'), ((1497, 1527), 'numpy.transpose', 'np.transpose', (['image', '(1, 2, 0)'], {}), '(image, (1, 2, 0))\n', (1509, 1527), True, 'import numpy as np\n'), ((1206, 1232), 'numpy.ceil', 'np.ceil', (['(col_num / row_num)'], {}), '(col_num / row_num)\n', (1213, 1232), True, 'import numpy as np\n')]
import meshio import numpy as np from src.htc_calculator.reference_face import ReferenceFace from src.htc_calculator.activated_reference_face import ActivatedReferenceFace from src.htc_calculator.construction import Material, Layer, ComponentConstruction from src.htc_calculator.meshing.mesh_setup import MeshSetup from src.htc_calculator.activated_reference_face import test_mesh_creation vertices = np.array([[0, 0, 0], [5, 0, 0], [5, 5, 0], [0, 5, 0]]) concrete = Material(name='concrete', density=2600, specific_heat_capacity=1000, heat_conductivity=2.5) rockwool = Material(name='rockwool', density=250, specific_heat_capacity=840, heat_conductivity=0.034) plaster = Material(name='plaster', density=1500, specific_heat_capacity=960, heat_conductivity=0.60) layer0 = Layer(name='layer0_plaster', material=plaster, thickness=0.02) layer1 = Layer(name='layer1_concrete', material=concrete, thickness=0.3) layer2 = Layer(name='layer2_rockwool', material=rockwool, thickness=0.3) layer3 = Layer(name='layer3_plaster', material=plaster, thickness=0.02) test_construction = ComponentConstruction(name='test_construction', layers=[layer1, layer2], side_1_offset=0.00) mesh_setup = MeshSetup(name='simple_mesh_setup') face = ReferenceFace(vertices=vertices, component_construction=test_construction, mesh_setup=mesh_setup) face.generate_reference_geometry() face.generate_3d_geometry() face.save_fcstd('/tmp/test.FCStd') face.export_step('/tmp/simple_test_geo.stp') # face.export_stl('TEST_MIT_Tomas.stl') # face.generate_mesh() # # print(face) # # tabs1 = ActivatedReferenceFace(vertices=vertices, component_construction=test_construction, start_edge=0, tube_diameter=0.1, tube_distance=0.25, tube_edge_distance=0.3, bending_radius=0.1, tube_side_1_offset=0.15, name='test1') # tabs1.generate_reference_geometry() tabs1.generate_3d_geometry() # tabs1.export_step('tabs_layers.stp') tabs1.generate_tube_spline() tabs1.generate_solid_pipe() # tabs1.export_solid_pipe('solid_pipe_test.stp') tabs1.generate_hole_part() tabs1.save_fcstd('/tmp/activated_test.FCStd') tabs1.export_step('/tmp/simple_test_geo_activated.stp') tabs1.export_solid_pipe('/tmp/solid_pipe.stp') tabs1.export_solids('/tmp/solids.FCStd') tabs1.generate_mesh() tabs1.export_step('finished.stp')
[ "src.htc_calculator.reference_face.ReferenceFace", "src.htc_calculator.construction.Layer", "src.htc_calculator.meshing.mesh_setup.MeshSetup", "numpy.array", "src.htc_calculator.construction.Material", "src.htc_calculator.construction.ComponentConstruction", "src.htc_calculator.activated_reference_face.ActivatedReferenceFace" ]
[((410, 464), 'numpy.array', 'np.array', (['[[0, 0, 0], [5, 0, 0], [5, 5, 0], [0, 5, 0]]'], {}), '([[0, 0, 0], [5, 0, 0], [5, 5, 0], [0, 5, 0]])\n', (418, 464), True, 'import numpy as np\n'), ((545, 640), 'src.htc_calculator.construction.Material', 'Material', ([], {'name': '"""concrete"""', 'density': '(2600)', 'specific_heat_capacity': '(1000)', 'heat_conductivity': '(2.5)'}), "(name='concrete', density=2600, specific_heat_capacity=1000,\n heat_conductivity=2.5)\n", (553, 640), False, 'from src.htc_calculator.construction import Material, Layer, ComponentConstruction\n'), ((714, 809), 'src.htc_calculator.construction.Material', 'Material', ([], {'name': '"""rockwool"""', 'density': '(250)', 'specific_heat_capacity': '(840)', 'heat_conductivity': '(0.034)'}), "(name='rockwool', density=250, specific_heat_capacity=840,\n heat_conductivity=0.034)\n", (722, 809), False, 'from src.htc_calculator.construction import Material, Layer, ComponentConstruction\n'), ((882, 975), 'src.htc_calculator.construction.Material', 'Material', ([], {'name': '"""plaster"""', 'density': '(1500)', 'specific_heat_capacity': '(960)', 'heat_conductivity': '(0.6)'}), "(name='plaster', density=1500, specific_heat_capacity=960,\n heat_conductivity=0.6)\n", (890, 975), False, 'from src.htc_calculator.construction import Material, Layer, ComponentConstruction\n'), ((1045, 1107), 'src.htc_calculator.construction.Layer', 'Layer', ([], {'name': '"""layer0_plaster"""', 'material': 'plaster', 'thickness': '(0.02)'}), "(name='layer0_plaster', material=plaster, thickness=0.02)\n", (1050, 1107), False, 'from src.htc_calculator.construction import Material, Layer, ComponentConstruction\n'), ((1118, 1181), 'src.htc_calculator.construction.Layer', 'Layer', ([], {'name': '"""layer1_concrete"""', 'material': 'concrete', 'thickness': '(0.3)'}), "(name='layer1_concrete', material=concrete, thickness=0.3)\n", (1123, 1181), False, 'from src.htc_calculator.construction import Material, Layer, ComponentConstruction\n'), ((1192, 1255), 'src.htc_calculator.construction.Layer', 'Layer', ([], {'name': '"""layer2_rockwool"""', 'material': 'rockwool', 'thickness': '(0.3)'}), "(name='layer2_rockwool', material=rockwool, thickness=0.3)\n", (1197, 1255), False, 'from src.htc_calculator.construction import Material, Layer, ComponentConstruction\n'), ((1266, 1328), 'src.htc_calculator.construction.Layer', 'Layer', ([], {'name': '"""layer3_plaster"""', 'material': 'plaster', 'thickness': '(0.02)'}), "(name='layer3_plaster', material=plaster, thickness=0.02)\n", (1271, 1328), False, 'from src.htc_calculator.construction import Material, Layer, ComponentConstruction\n'), ((1353, 1448), 'src.htc_calculator.construction.ComponentConstruction', 'ComponentConstruction', ([], {'name': '"""test_construction"""', 'layers': '[layer1, layer2]', 'side_1_offset': '(0.0)'}), "(name='test_construction', layers=[layer1, layer2],\n side_1_offset=0.0)\n", (1374, 1448), False, 'from src.htc_calculator.construction import Material, Layer, ComponentConstruction\n'), ((1548, 1583), 'src.htc_calculator.meshing.mesh_setup.MeshSetup', 'MeshSetup', ([], {'name': '"""simple_mesh_setup"""'}), "(name='simple_mesh_setup')\n", (1557, 1583), False, 'from src.htc_calculator.meshing.mesh_setup import MeshSetup\n'), ((1594, 1695), 'src.htc_calculator.reference_face.ReferenceFace', 'ReferenceFace', ([], {'vertices': 'vertices', 'component_construction': 'test_construction', 'mesh_setup': 'mesh_setup'}), '(vertices=vertices, component_construction=test_construction,\n mesh_setup=mesh_setup)\n', (1607, 1695), False, 'from src.htc_calculator.reference_face import ReferenceFace\n'), ((1987, 2219), 'src.htc_calculator.activated_reference_face.ActivatedReferenceFace', 'ActivatedReferenceFace', ([], {'vertices': 'vertices', 'component_construction': 'test_construction', 'start_edge': '(0)', 'tube_diameter': '(0.1)', 'tube_distance': '(0.25)', 'tube_edge_distance': '(0.3)', 'bending_radius': '(0.1)', 'tube_side_1_offset': '(0.15)', 'name': '"""test1"""'}), "(vertices=vertices, component_construction=\n test_construction, start_edge=0, tube_diameter=0.1, tube_distance=0.25,\n tube_edge_distance=0.3, bending_radius=0.1, tube_side_1_offset=0.15,\n name='test1')\n", (2009, 2219), False, 'from src.htc_calculator.activated_reference_face import ActivatedReferenceFace\n')]
import numpy as np from PuzzleLib.Backend import gpuarray from PuzzleLib.Backend.gpuarray import memoryPool as memPool from PuzzleLib.Backend.Kernels import Pad from PuzzleLib.Modules.Module import ModuleError, Module from PuzzleLib.Modules.Pad2D import PadMode class Pad1D(Module): def __init__(self, pad, mode="constant", fillValue=None, name=None): super().__init__(name) self.registerBlueprint(locals()) self.mode = PadMode(mode) self.pad = self.repeat(pad, 2) self.fillValue = 0 if fillValue is None else fillValue def updateData(self, data): if self.mode == PadMode.constant: insize = data.shape[2] lpad, rpad = self.pad outsize = insize + lpad + rpad self.data = gpuarray.empty(data.shape[:2] + (outsize, ), dtype=np.float32, allocator=memPool) self.data.fill(self.fillValue) self.data[:, :, lpad:self.data.shape[2] - rpad] = data elif self.mode == PadMode.reflect: self.data = Pad.reflectpad1d(data, self.pad) else: raise NotImplementedError(self.mode) def updateGrad(self, grad): if self.mode == PadMode.constant: size = grad.shape[2] lpad, rpad = self.pad self.grad = grad[:, :, lpad:size - rpad].copy(allocator=memPool) elif self.mode == PadMode.reflect: self.grad = Pad.reflectpad1dBackward(grad, self.pad) else: raise NotImplementedError(self.mode) def checkDataShape(self, shape): if len(shape) != 3: raise ModuleError("Data must be 3d tensor") lpad, rpad = self.pad size = shape[2] pad = max(lpad, rpad) if size < pad + 1: raise ModuleError("Data maps size is too small (got %d, expected >= %d)" % (size, pad + 1)) def checkGradShape(self, shape): if len(shape) != 3: raise ModuleError("Grad must be 3d tensor") lpad, rpad = self.pad size = shape[2] if size < lpad + rpad + 1: raise ModuleError("Grad maps size is too small (got %d, expected >= %d)" % (size, lpad + rpad + 1)) def dataShapeFrom(self, shape): batchsize, maps, size = shape lpad, rpad = self.pad return batchsize, maps, size + lpad + rpad def gradShapeFrom(self, shape): batchsize, maps, size = shape lpad, rpad = self.pad return batchsize, maps, size - lpad - rpad def calcMode(self, T): dtypes = {dtype for dtype, _ in gpuarray.dtypesSupported()} if T not in dtypes: raise ModuleError("Unsupported dtype %s" % T) self.calctype = T def unittest(): constantTest() reflectTest() def constantTest(): data = gpuarray.to_gpu(np.random.randn(3, 4, 5).astype(np.float32)) lpad, rpad = 0, 1 fillValue = -0.1 padmod = Pad1D(pad=(lpad, rpad), mode=PadMode.constant, fillValue=fillValue) padmod(data) assert padmod.dataShapeFrom(data.shape) == padmod.data.shape hostData, hostOutData = data.get(), padmod.data.get() assert np.allclose(hostOutData[:, :, lpad:hostOutData.shape[2] - rpad], hostData) assert np.isclose(hostOutData[0, 0, hostOutData.shape[2] - 1], fillValue) grad = gpuarray.to_gpu(np.random.randn(*hostOutData.shape).astype(np.float32)) padmod.backward(grad) assert padmod.gradShapeFrom(grad.shape) == data.shape assert np.allclose(padmod.grad.get(), grad.get()[:, :, lpad:grad.shape[2] - rpad]) def reflectTest(): batchsize, maps, insize = 4, 8, 48 lpad, rpad = 2, 3 data = gpuarray.to_gpu(np.random.randn(batchsize, maps, insize).astype(np.float32)) reflectpad = Pad1D(pad=(lpad, rpad), mode=PadMode.reflect) reflectpad(data) hostData, hostOutData = data.get(), reflectpad.data.get() outsize = hostOutData.shape[2] assert np.allclose(hostOutData[:, :, lpad:insize + lpad], hostData) assert np.allclose(hostOutData[:, :, :lpad][:, :, ::-1], hostData[:, :, 1:lpad+1]) assert np.allclose(hostOutData[:, :, insize + lpad:][:, :, ::-1], hostData[:, :, insize - 1 - rpad:insize - 1]) grad = gpuarray.to_gpu(np.random.randn(batchsize, maps, outsize).astype(np.float32)) reflectpad.backward(grad) hostGrad, hostInGrad = grad.get(), reflectpad.grad.get() assert np.allclose(hostInGrad[:, :, lpad + 1:insize - rpad - 1], hostGrad[:, :, 2 * lpad + 1:outsize - 2 * rpad - 1]) assert np.allclose(hostInGrad[:, :, 1:lpad + 1], hostGrad[:, :, :lpad][:, :, ::-1] + hostGrad[:, :, lpad + 1:2 * lpad + 1]) assert np.allclose(hostInGrad[:, :, insize - rpad - 1:insize - 1], hostGrad[:, :, outsize - rpad:][:, :, ::-1] + hostGrad[:, :, outsize - 2 * rpad - 1:outsize - rpad - 1]) if __name__ == "__main__": unittest()
[ "PuzzleLib.Modules.Pad2D.PadMode", "PuzzleLib.Backend.Kernels.Pad.reflectpad1dBackward", "numpy.random.randn", "numpy.allclose", "PuzzleLib.Backend.gpuarray.empty", "numpy.isclose", "PuzzleLib.Backend.gpuarray.dtypesSupported", "PuzzleLib.Backend.Kernels.Pad.reflectpad1d", "PuzzleLib.Modules.Module.ModuleError" ]
[((2767, 2841), 'numpy.allclose', 'np.allclose', (['hostOutData[:, :, lpad:hostOutData.shape[2] - rpad]', 'hostData'], {}), '(hostOutData[:, :, lpad:hostOutData.shape[2] - rpad], hostData)\n', (2778, 2841), True, 'import numpy as np\n'), ((2851, 2917), 'numpy.isclose', 'np.isclose', (['hostOutData[0, 0, hostOutData.shape[2] - 1]', 'fillValue'], {}), '(hostOutData[0, 0, hostOutData.shape[2] - 1], fillValue)\n', (2861, 2917), True, 'import numpy as np\n'), ((3504, 3564), 'numpy.allclose', 'np.allclose', (['hostOutData[:, :, lpad:insize + lpad]', 'hostData'], {}), '(hostOutData[:, :, lpad:insize + lpad], hostData)\n', (3515, 3564), True, 'import numpy as np\n'), ((3573, 3650), 'numpy.allclose', 'np.allclose', (['hostOutData[:, :, :lpad][:, :, ::-1]', 'hostData[:, :, 1:lpad + 1]'], {}), '(hostOutData[:, :, :lpad][:, :, ::-1], hostData[:, :, 1:lpad + 1])\n', (3584, 3650), True, 'import numpy as np\n'), ((3657, 3766), 'numpy.allclose', 'np.allclose', (['hostOutData[:, :, insize + lpad:][:, :, ::-1]', 'hostData[:, :, insize - 1 - rpad:insize - 1]'], {}), '(hostOutData[:, :, insize + lpad:][:, :, ::-1], hostData[:, :, \n insize - 1 - rpad:insize - 1])\n', (3668, 3766), True, 'import numpy as np\n'), ((3944, 4058), 'numpy.allclose', 'np.allclose', (['hostInGrad[:, :, lpad + 1:insize - rpad - 1]', 'hostGrad[:, :, 2 * lpad + 1:outsize - 2 * rpad - 1]'], {}), '(hostInGrad[:, :, lpad + 1:insize - rpad - 1], hostGrad[:, :, 2 *\n lpad + 1:outsize - 2 * rpad - 1])\n', (3955, 4058), True, 'import numpy as np\n'), ((4071, 4191), 'numpy.allclose', 'np.allclose', (['hostInGrad[:, :, 1:lpad + 1]', '(hostGrad[:, :, :lpad][:, :, ::-1] + hostGrad[:, :, lpad + 1:2 * lpad + 1])'], {}), '(hostInGrad[:, :, 1:lpad + 1], hostGrad[:, :, :lpad][:, :, ::-1] +\n hostGrad[:, :, lpad + 1:2 * lpad + 1])\n', (4082, 4191), True, 'import numpy as np\n'), ((4204, 4378), 'numpy.allclose', 'np.allclose', (['hostInGrad[:, :, insize - rpad - 1:insize - 1]', '(hostGrad[:, :, outsize - rpad:][:, :, ::-1] + hostGrad[:, :, outsize - 2 *\n rpad - 1:outsize - rpad - 1])'], {}), '(hostInGrad[:, :, insize - rpad - 1:insize - 1], hostGrad[:, :, \n outsize - rpad:][:, :, ::-1] + hostGrad[:, :, outsize - 2 * rpad - 1:\n outsize - rpad - 1])\n', (4215, 4378), True, 'import numpy as np\n'), ((432, 445), 'PuzzleLib.Modules.Pad2D.PadMode', 'PadMode', (['mode'], {}), '(mode)\n', (439, 445), False, 'from PuzzleLib.Modules.Pad2D import PadMode\n'), ((705, 790), 'PuzzleLib.Backend.gpuarray.empty', 'gpuarray.empty', (['(data.shape[:2] + (outsize,))'], {'dtype': 'np.float32', 'allocator': 'memPool'}), '(data.shape[:2] + (outsize,), dtype=np.float32, allocator=memPool\n )\n', (719, 790), False, 'from PuzzleLib.Backend import gpuarray\n'), ((1410, 1447), 'PuzzleLib.Modules.Module.ModuleError', 'ModuleError', (['"""Data must be 3d tensor"""'], {}), "('Data must be 3d tensor')\n", (1421, 1447), False, 'from PuzzleLib.Modules.Module import ModuleError, Module\n'), ((1547, 1636), 'PuzzleLib.Modules.Module.ModuleError', 'ModuleError', (["('Data maps size is too small (got %d, expected >= %d)' % (size, pad + 1))"], {}), "('Data maps size is too small (got %d, expected >= %d)' % (size,\n pad + 1))\n", (1558, 1636), False, 'from PuzzleLib.Modules.Module import ModuleError, Module\n'), ((1700, 1737), 'PuzzleLib.Modules.Module.ModuleError', 'ModuleError', (['"""Grad must be 3d tensor"""'], {}), "('Grad must be 3d tensor')\n", (1711, 1737), False, 'from PuzzleLib.Modules.Module import ModuleError, Module\n'), ((1820, 1917), 'PuzzleLib.Modules.Module.ModuleError', 'ModuleError', (["('Grad maps size is too small (got %d, expected >= %d)' % (size, lpad +\n rpad + 1))"], {}), "('Grad maps size is too small (got %d, expected >= %d)' % (size,\n lpad + rpad + 1))\n", (1831, 1917), False, 'from PuzzleLib.Modules.Module import ModuleError, Module\n'), ((2308, 2347), 'PuzzleLib.Modules.Module.ModuleError', 'ModuleError', (["('Unsupported dtype %s' % T)"], {}), "('Unsupported dtype %s' % T)\n", (2319, 2347), False, 'from PuzzleLib.Modules.Module import ModuleError, Module\n'), ((933, 965), 'PuzzleLib.Backend.Kernels.Pad.reflectpad1d', 'Pad.reflectpad1d', (['data', 'self.pad'], {}), '(data, self.pad)\n', (949, 965), False, 'from PuzzleLib.Backend.Kernels import Pad\n'), ((1253, 1293), 'PuzzleLib.Backend.Kernels.Pad.reflectpad1dBackward', 'Pad.reflectpad1dBackward', (['grad', 'self.pad'], {}), '(grad, self.pad)\n', (1277, 1293), False, 'from PuzzleLib.Backend.Kernels import Pad\n'), ((2248, 2274), 'PuzzleLib.Backend.gpuarray.dtypesSupported', 'gpuarray.dtypesSupported', ([], {}), '()\n', (2272, 2274), False, 'from PuzzleLib.Backend import gpuarray\n'), ((2464, 2488), 'numpy.random.randn', 'np.random.randn', (['(3)', '(4)', '(5)'], {}), '(3, 4, 5)\n', (2479, 2488), True, 'import numpy as np\n'), ((2943, 2978), 'numpy.random.randn', 'np.random.randn', (['*hostOutData.shape'], {}), '(*hostOutData.shape)\n', (2958, 2978), True, 'import numpy as np\n'), ((3263, 3303), 'numpy.random.randn', 'np.random.randn', (['batchsize', 'maps', 'insize'], {}), '(batchsize, maps, insize)\n', (3278, 3303), True, 'import numpy as np\n'), ((3787, 3828), 'numpy.random.randn', 'np.random.randn', (['batchsize', 'maps', 'outsize'], {}), '(batchsize, maps, outsize)\n', (3802, 3828), True, 'import numpy as np\n')]
import sys import os import numpy as np import tensorflow as tf import math import random from tensorflow import keras ''' import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F ''' import matplotlib.pyplot as plt class FittedQAgent(): ''' abstract class for the Torch and Keras implimentations, dont use directly ''' def get_action(self, state, explore_rate): ''' Choses action based on enivormental state, explore rate and current value estimates Parameters: state: environmental state explore_rate Returns: action ''' if np.random.random() < explore_rate: action = np.random.choice(range(self.layer_sizes[-1])) else: values = self.predict(state) self.values.append(values) action = np.argmax(values) assert action < self.n_actions, 'Invalid action' return action def get_inputs_targets(self): ''' gets fitted Q inputs and calculates targets for training the Q-network for episodic training ''' inputs = [] targets = [] # DO THIS WITH NUMPY TO MAKE IT FASTER for trajectory in self.memory: for transition in trajectory: # CHEKC TARGET IS BUILT CORRECTLY state, action, cost, next_state, done = transition inputs.append(state) # construct target values = self.predict(state) next_values = self.predict(next_state) assert len(values) == self.n_actions, 'neural network returning wrong number of values' assert len(next_values) == self.n_actions, 'neural network returning wrong number of values' #update the value for the taken action using cost function and current Q if not done: values[action] = cost + self.gamma*np.max(next_values) # could introduce step size here, maybe not needed for neural agent else: values[action] = cost targets.append(values) # shuffle inputs and target for IID inputs, targets = np.array(inputs), np.array(targets) randomize = np.arange(len(inputs)) np.random.shuffle(randomize) inputs = inputs[randomize] targets = targets[randomize] assert inputs.shape[1] == self.state_size, 'inputs to network wrong size' assert targets.shape[1] == self.n_actions, 'targets for network wrong size' return inputs, targets def fitted_Q_update(self, inputs = None, targets = None): ''' Uses a set of inputs and targets to update the Q network ''' if inputs is None and targets is None: inputs, targets = self.get_inputs_targets() # #tf.initialize_all_variables() # resinitialise netowrk without adding to tensorflow graph # try RMSprop and adam and maybe some from here https://arxiv.org/abs/1609.04747 self.reset_weights() history = self.fit(inputs, targets) #print('losses: ', history.history['loss'][0], history.history['loss'][-1]) return history def run_episode(self, env, explore_rate, tmax, train = True, remember = True): ''' Runs one fitted Q episode Parameters: env: the enirovment to train on and control explore_rate: explore rate for this episodes tmax: number of timesteps in the episode train: does the agent learn? remember: does the agent store eperience in its memory? Returns: env.sSol: time evolution of environmental states episode reward: total reward for this episode ''' # run trajectory with current policy and add to memory trajectory = [] actions = [] #self.values = [] state = env.get_state() episode_reward = 0 self.single_ep_reward = [] for i in range(tmax): action = self.get_action(state, explore_rate) actions.append(action) next_state, reward, done, info = env.step(action) #cost = -cost # as cartpole default returns a reward assert len(next_state) == self.state_size, 'env return state of wrong size' self.single_ep_reward.append(reward) if done: print(reward) # scale populations transition = (state, action, reward, next_state, done) state = next_state trajectory.append(transition) episode_reward += reward if done: break if remember: self.memory.append(trajectory) if train: self.actions = actions self.episode_lengths.append(i) self.episode_rewards.append(episode_reward) if len(self.memory[0]) * len(self.memory) < 100: #n_iters = 4 n_iters = 4 elif len(self.memory[0]) * len(self.memory) < 200: #n_iters = 5 n_iters = 5 else: n_iters = 10 #n_iters = 0 for _ in range(n_iters): self.fitted_Q_update() #env.plot_trajectory() #plt.show() return env.sSol, episode_reward def neural_fitted_Q(self, env, n_episodes, tmax): ''' runs a whole neural fitted Q experiment Parameters: env: environment to train on n_episodes: number of episodes tmax: timesteps in each episode ''' times = [] for i in range(n_episodes): print() print('EPISODE', i) # CONSTANT EXPLORE RATE OF 0.1 worked well explore_rate = self.get_rate(i, 0, 1, 2.5) #explore_rate = 0.1 #explore_rate = 0 print('explore_rate:', explore_rate) env.reset() trajectory, reward = self.run_episode(env, explore_rate, tmax) time = len(trajectory) print('Time: ', time) times.append(time) print(times) def plot_rewards(self): ''' Plots the total reward gained in each episode on a matplotlib figure ''' plt.figure(figsize = (16.0,12.0)) plt.plot(self.episode_rewards) def save_results(self, save_path): ''' saves numpy arrays of results of training ''' np.save(save_path + '/survival_times', self.episode_lengths) np.save(save_path + '/episode_rewards', self.episode_rewards) def get_rate(self, episode, MIN_LEARNING_RATE, MAX_LEARNING_RATE, denominator): ''' Calculates the logarithmically decreasing explore or learning rate Parameters: episode: the current episode MIN_LEARNING_RATE: the minimum possible step size MAX_LEARNING_RATE: maximum step size denominator: controls the rate of decay of the step size Returns: step_size: the Q-learning step size ''' # input validation if not 0 <= MIN_LEARNING_RATE <= 1: raise ValueError("MIN_LEARNING_RATE needs to be bewteen 0 and 1") if not 0 <= MAX_LEARNING_RATE <= 1: raise ValueError("MAX_LEARNING_RATE needs to be bewteen 0 and 1") if not 0 < denominator: raise ValueError("denominator needs to be above 0") rate = max(MIN_LEARNING_RATE, min(MAX_LEARNING_RATE, 1.0 - math.log10((episode+1)/denominator))) return rate class KerasFittedQAgent(FittedQAgent): def __init__(self, layer_sizes = [2,20,20,4]): self.memory = [] self.layer_sizes = layer_sizes self.network = self.initialise_network(layer_sizes) self.gamma = 0.9 self.state_size = layer_sizes[0] self.n_actions = layer_sizes[-1] self.episode_lengths = [] self.episode_rewards = [] self.single_ep_reward = [] self.total_loss = 0 self.values = [] def initialise_network(self, layer_sizes): ''' Creates Q network ''' tf.keras.backend.clear_session() initialiser = keras.initializers.RandomUniform(minval = -0.5, maxval = 0.5, seed = None) positive_initialiser = keras.initializers.RandomUniform(minval = 0., maxval = 0.35, seed = None) regulariser = keras.regularizers.l1_l2(l1=0.01, l2=0.01) network = keras.Sequential([ keras.layers.InputLayer([layer_sizes[0]]), keras.layers.Dense(layer_sizes[1], activation = tf.nn.relu), keras.layers.Dense(layer_sizes[2], activation = tf.nn.relu), keras.layers.Dense(layer_sizes[3]) # linear output layer ]) network.compile(optimizer = 'adam', loss = 'mean_squared_error') # TRY DIFFERENT OPTIMISERS return network def predict(self, state): ''' Predicts value estimates for each action base on currrent states ''' return self.network.predict(state.reshape(1,-1))[0] def fit(self, inputs, targets): ''' trains the Q network on a set of inputs and targets ''' history = self.network.fit(inputs, targets, epochs = 300, verbose = 0) # TRY DIFFERENT EPOCHS return history def reset_weights(model): ''' Reinitialises weights to random values ''' sess = tf.keras.backend.get_session() sess.run(tf.global_variables_initializer()) def save_network(self, save_path): ''' Saves current network weights ''' self.network.save(save_path + '/saved_network.h5') def save_network_tensorflow(self, save_path): ''' Saves current network weights using pure tensorflow, kerassaver seems to crash sometimes ''' saver = tf.train.Saver() sess = tf.keras.backend.get_session() path = saver.save(sess, save_path + "/saved/model.cpkt") def load_network_tensorflow(self, save_path): ''' Loads network weights from file using pure tensorflow, kerassaver seems to crash sometimes ''' saver = tf.train.Saver() sess = tf.keras.backend.get_session() saver.restore(sess, save_path +"/saved/model.cpkt") def load_network(self, load_path): #tested ''' Loads network weights from file ''' try: self.network = keras.models.load_model(load_path + '/saved_network.h5') # sometimes this crashes, apparently a bug in keras except: self.network.load_weights(load_path + '/saved_network.h5') # this requires model to be initialised exactly the same
[ "numpy.save", "tensorflow.keras.models.load_model", "matplotlib.pyplot.plot", "tensorflow.train.Saver", "numpy.argmax", "tensorflow.global_variables_initializer", "tensorflow.keras.backend.clear_session", "tensorflow.keras.layers.Dense", "tensorflow.keras.layers.InputLayer", "matplotlib.pyplot.figure", "tensorflow.keras.initializers.RandomUniform", "numpy.random.random", "tensorflow.keras.backend.get_session", "numpy.array", "tensorflow.keras.regularizers.l1_l2", "math.log10", "numpy.max", "numpy.random.shuffle" ]
[((2357, 2385), 'numpy.random.shuffle', 'np.random.shuffle', (['randomize'], {}), '(randomize)\n', (2374, 2385), True, 'import numpy as np\n'), ((6431, 6463), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(16.0, 12.0)'}), '(figsize=(16.0, 12.0))\n', (6441, 6463), True, 'import matplotlib.pyplot as plt\n'), ((6474, 6504), 'matplotlib.pyplot.plot', 'plt.plot', (['self.episode_rewards'], {}), '(self.episode_rewards)\n', (6482, 6504), True, 'import matplotlib.pyplot as plt\n'), ((6627, 6687), 'numpy.save', 'np.save', (["(save_path + '/survival_times')", 'self.episode_lengths'], {}), "(save_path + '/survival_times', self.episode_lengths)\n", (6634, 6687), True, 'import numpy as np\n'), ((6696, 6757), 'numpy.save', 'np.save', (["(save_path + '/episode_rewards')", 'self.episode_rewards'], {}), "(save_path + '/episode_rewards', self.episode_rewards)\n", (6703, 6757), True, 'import numpy as np\n'), ((8335, 8367), 'tensorflow.keras.backend.clear_session', 'tf.keras.backend.clear_session', ([], {}), '()\n', (8365, 8367), True, 'import tensorflow as tf\n'), ((8390, 8458), 'tensorflow.keras.initializers.RandomUniform', 'keras.initializers.RandomUniform', ([], {'minval': '(-0.5)', 'maxval': '(0.5)', 'seed': 'None'}), '(minval=-0.5, maxval=0.5, seed=None)\n', (8422, 8458), False, 'from tensorflow import keras\n'), ((8496, 8564), 'tensorflow.keras.initializers.RandomUniform', 'keras.initializers.RandomUniform', ([], {'minval': '(0.0)', 'maxval': '(0.35)', 'seed': 'None'}), '(minval=0.0, maxval=0.35, seed=None)\n', (8528, 8564), False, 'from tensorflow import keras\n'), ((8592, 8634), 'tensorflow.keras.regularizers.l1_l2', 'keras.regularizers.l1_l2', ([], {'l1': '(0.01)', 'l2': '(0.01)'}), '(l1=0.01, l2=0.01)\n', (8616, 8634), False, 'from tensorflow import keras\n'), ((9630, 9660), 'tensorflow.keras.backend.get_session', 'tf.keras.backend.get_session', ([], {}), '()\n', (9658, 9660), True, 'import tensorflow as tf\n'), ((10062, 10078), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (10076, 10078), True, 'import tensorflow as tf\n'), ((10094, 10124), 'tensorflow.keras.backend.get_session', 'tf.keras.backend.get_session', ([], {}), '()\n', (10122, 10124), True, 'import tensorflow as tf\n'), ((10382, 10398), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (10396, 10398), True, 'import tensorflow as tf\n'), ((10415, 10445), 'tensorflow.keras.backend.get_session', 'tf.keras.backend.get_session', ([], {}), '()\n', (10443, 10445), True, 'import tensorflow as tf\n'), ((673, 691), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (689, 691), True, 'import numpy as np\n'), ((892, 909), 'numpy.argmax', 'np.argmax', (['values'], {}), '(values)\n', (901, 909), True, 'import numpy as np\n'), ((2267, 2283), 'numpy.array', 'np.array', (['inputs'], {}), '(inputs)\n', (2275, 2283), True, 'import numpy as np\n'), ((2285, 2302), 'numpy.array', 'np.array', (['targets'], {}), '(targets)\n', (2293, 2302), True, 'import numpy as np\n'), ((9678, 9711), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (9709, 9711), True, 'import tensorflow as tf\n'), ((10659, 10715), 'tensorflow.keras.models.load_model', 'keras.models.load_model', (["(load_path + '/saved_network.h5')"], {}), "(load_path + '/saved_network.h5')\n", (10682, 10715), False, 'from tensorflow import keras\n'), ((8684, 8725), 'tensorflow.keras.layers.InputLayer', 'keras.layers.InputLayer', (['[layer_sizes[0]]'], {}), '([layer_sizes[0]])\n', (8707, 8725), False, 'from tensorflow import keras\n'), ((8739, 8796), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['layer_sizes[1]'], {'activation': 'tf.nn.relu'}), '(layer_sizes[1], activation=tf.nn.relu)\n', (8757, 8796), False, 'from tensorflow import keras\n'), ((8812, 8869), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['layer_sizes[2]'], {'activation': 'tf.nn.relu'}), '(layer_sizes[2], activation=tf.nn.relu)\n', (8830, 8869), False, 'from tensorflow import keras\n'), ((8885, 8919), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['layer_sizes[3]'], {}), '(layer_sizes[3])\n', (8903, 8919), False, 'from tensorflow import keras\n'), ((7688, 7727), 'math.log10', 'math.log10', (['((episode + 1) / denominator)'], {}), '((episode + 1) / denominator)\n', (7698, 7727), False, 'import math\n'), ((2003, 2022), 'numpy.max', 'np.max', (['next_values'], {}), '(next_values)\n', (2009, 2022), True, 'import numpy as np\n')]
from __future__ import print_function import unittest import numpy as np from openmdao.api import Problem, IndepVarComp, Group from openmdao.utils.assert_utils import assert_rel_error, assert_check_partials from CADRE.battery_dymos import BatterySOCComp class TestBatteryDymos(unittest.TestCase): @classmethod def setUpClass(cls): nn = 6 cls.p = Problem(model=Group()) ivc = cls.p.model.add_subsystem('ivc', IndepVarComp(), promotes_outputs=['*']) ivc.add_output('temperature', val=np.ones((nn,5))) ivc.add_output('P_bat', val=np.ones((nn,))) ivc.add_output('SOC', val=np.ones((nn,))) cls.p.model.add_subsystem('battery_soc_comp', BatterySOCComp(num_nodes=nn), promotes_inputs=['*'], promotes_outputs=['*']) cls.p.setup(check=True, force_alloc_complex=True) cls.p['temperature'] = 273 + np.random.rand(nn, 5) * 100 cls.p['P_bat'] = np.random.rand(nn) * 100 cls.p['SOC'] = np.random.rand(nn) cls.p.run_model() def test_results(self): self.assertTrue(np.all(self.p['dXdt:SOC'] < 0)) def test_partials(self): np.set_printoptions(linewidth=1024) cpd = self.p.check_partials(method='cs') assert_check_partials(cpd)
[ "openmdao.api.IndepVarComp", "numpy.set_printoptions", "CADRE.battery_dymos.BatterySOCComp", "openmdao.api.Group", "numpy.ones", "openmdao.utils.assert_utils.assert_check_partials", "numpy.random.rand", "numpy.all" ]
[((1013, 1031), 'numpy.random.rand', 'np.random.rand', (['nn'], {}), '(nn)\n', (1027, 1031), True, 'import numpy as np\n'), ((1182, 1217), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'linewidth': '(1024)'}), '(linewidth=1024)\n', (1201, 1217), True, 'import numpy as np\n'), ((1275, 1301), 'openmdao.utils.assert_utils.assert_check_partials', 'assert_check_partials', (['cpd'], {}), '(cpd)\n', (1296, 1301), False, 'from openmdao.utils.assert_utils import assert_rel_error, assert_check_partials\n'), ((448, 462), 'openmdao.api.IndepVarComp', 'IndepVarComp', ([], {}), '()\n', (460, 462), False, 'from openmdao.api import Problem, IndepVarComp, Group\n'), ((704, 732), 'CADRE.battery_dymos.BatterySOCComp', 'BatterySOCComp', ([], {'num_nodes': 'nn'}), '(num_nodes=nn)\n', (718, 732), False, 'from CADRE.battery_dymos import BatterySOCComp\n'), ((965, 983), 'numpy.random.rand', 'np.random.rand', (['nn'], {}), '(nn)\n', (979, 983), True, 'import numpy as np\n'), ((1112, 1142), 'numpy.all', 'np.all', (["(self.p['dXdt:SOC'] < 0)"], {}), "(self.p['dXdt:SOC'] < 0)\n", (1118, 1142), True, 'import numpy as np\n'), ((391, 398), 'openmdao.api.Group', 'Group', ([], {}), '()\n', (396, 398), False, 'from openmdao.api import Problem, IndepVarComp, Group\n'), ((530, 546), 'numpy.ones', 'np.ones', (['(nn, 5)'], {}), '((nn, 5))\n', (537, 546), True, 'import numpy as np\n'), ((583, 597), 'numpy.ones', 'np.ones', (['(nn,)'], {}), '((nn,))\n', (590, 597), True, 'import numpy as np\n'), ((633, 647), 'numpy.ones', 'np.ones', (['(nn,)'], {}), '((nn,))\n', (640, 647), True, 'import numpy as np\n'), ((912, 933), 'numpy.random.rand', 'np.random.rand', (['nn', '(5)'], {}), '(nn, 5)\n', (926, 933), True, 'import numpy as np\n')]
""" This module computes alignment solutions between all "a priori" solutions for a dataset and GAIA. """ import pytest import numpy as np from drizzlepac.haputils import testutils from ..resources import BaseACS, BaseWFC3 def compare_apriori(dataset): """This test will perform fits between ALL a priori solutions and GAIA. Success criteria: * Successful fit to GAIA for dataset * Fit was not compromised (fit_qual != 5) * radial offset for new WCS < radial offset for IDC_* WCS * scale for new WCS within 0.1% of scale for IDC_* WCS * rotation for new WCS is within 0.1% of rotation from IDC_* WCS ASSUMPTIONS: * OPUS-based WCS solutions are ignored * Some WCS's may be defined for one image in an ASN but not another, in which case, that WCS is ignored (silently). """ # Perform alignment of all WCS solutions with GAIA results_dict = testutils.compare_wcs_alignment(dataset) limit = 0.001 # Now compare results to see whether the a priori solutions succeeded # in improving the astrometry compared to default telescope pointing # reported by pipeline-defined WCS (IDC_* solution) wcsnames = list(results_dict.keys()) for idc_name in wcsnames: if 'IDC' in idc_name and '-' not in idc_name: wcsnames.remove(idc_name) break else: raise ValueError # Define pipeline-default fit pipeline_results = results_dict[idc_name] pipeline_offset = np.sqrt(pipeline_results['offset_x']**2 + pipeline_results['offset_y']**2) success = False # compare each WCS fit results with pipeline-default fit for wcs in wcsnames: print("Comparing fit for WCS='{}'...".format(wcs), end=' ') results = results_dict[wcs] # Check that fit for this WCS was successful status = (results['status'] == 0).all() # check that fit was not compromised or otherwise invalid fit_qual = (results['fit_qual'] < 5).all() # Check radial offset for this WCS compared to radial offset for # IDC* WCS offset = np.sqrt(results['offset_x']**2 + results['offset_y']**2) delta = ((offset < pipeline_offset).all() or np.allclose(offset, pipeline_offset, rtol=0, atol=1)) # Check that rotation and scale are within rot = np.allclose(results['rotation'], pipeline_results['rotation'], rtol=limit, atol=0) scale = np.allclose(results['scale'], pipeline_results['scale'], rtol=limit, atol=0) # Determine success/failure of this dataset's fit if all([status, fit_qual, delta, rot, scale]): # If at least one WCS succeeds, overall success # needs to be set to True success = True print("SUCCESS") else: print("FAILED due to:") if not status: print("\t* invalid STATUS") if not fit_qual: print("\t* invalid fit quality") if not delta: print("\t* increased offset from GAIA.") if not rot: print("\t* larger rotation from fit.") if not scale: print("\t* larger scale from fit.") assert success class TestAcsApriori(BaseACS): """ Tests which validate whether mosaics can be aligned to an astrometric standard, evaluate the quality of the fit, and generate a new WCS. * These can only be run using the pytest option: pytest --bigdata * This test is also compatible with pytest-xdist. """ @pytest.mark.bigdata @pytest.mark.parametrize('dataset', ['jb1601020', 'J9I408010']) def test_apriori(self, dataset): compare_apriori(dataset) class TestWFC3Apriori(BaseWFC3): """ Tests which validate whether mosaics can be aligned to an astrometric standard, evaluate the quality of the fit, and generate a new WCS. * These can only be run using the pytest option: pytest --bigdata * This test is also compatible with pytest-xdist. """ @pytest.mark.bigdata @pytest.mark.parametrize( 'dataset', ['ic0g0l010', 'icnw34040'] ) def test_apriori(self, dataset): compare_apriori(dataset)
[ "pytest.mark.parametrize", "numpy.allclose", "numpy.sqrt", "drizzlepac.haputils.testutils.compare_wcs_alignment" ]
[((925, 965), 'drizzlepac.haputils.testutils.compare_wcs_alignment', 'testutils.compare_wcs_alignment', (['dataset'], {}), '(dataset)\n', (956, 965), False, 'from drizzlepac.haputils import testutils\n'), ((1506, 1584), 'numpy.sqrt', 'np.sqrt', (["(pipeline_results['offset_x'] ** 2 + pipeline_results['offset_y'] ** 2)"], {}), "(pipeline_results['offset_x'] ** 2 + pipeline_results['offset_y'] ** 2)\n", (1513, 1584), True, 'import numpy as np\n'), ((3728, 3790), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""dataset"""', "['jb1601020', 'J9I408010']"], {}), "('dataset', ['jb1601020', 'J9I408010'])\n", (3751, 3790), False, 'import pytest\n'), ((4236, 4298), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""dataset"""', "['ic0g0l010', 'icnw34040']"], {}), "('dataset', ['ic0g0l010', 'icnw34040'])\n", (4259, 4298), False, 'import pytest\n'), ((2151, 2211), 'numpy.sqrt', 'np.sqrt', (["(results['offset_x'] ** 2 + results['offset_y'] ** 2)"], {}), "(results['offset_x'] ** 2 + results['offset_y'] ** 2)\n", (2158, 2211), True, 'import numpy as np\n'), ((2398, 2484), 'numpy.allclose', 'np.allclose', (["results['rotation']", "pipeline_results['rotation']"], {'rtol': 'limit', 'atol': '(0)'}), "(results['rotation'], pipeline_results['rotation'], rtol=limit,\n atol=0)\n", (2409, 2484), True, 'import numpy as np\n'), ((2523, 2599), 'numpy.allclose', 'np.allclose', (["results['scale']", "pipeline_results['scale']"], {'rtol': 'limit', 'atol': '(0)'}), "(results['scale'], pipeline_results['scale'], rtol=limit, atol=0)\n", (2534, 2599), True, 'import numpy as np\n'), ((2278, 2330), 'numpy.allclose', 'np.allclose', (['offset', 'pipeline_offset'], {'rtol': '(0)', 'atol': '(1)'}), '(offset, pipeline_offset, rtol=0, atol=1)\n', (2289, 2330), True, 'import numpy as np\n')]
""" Filter kernels (Szeliski 3.2) """ import numpy as np KERNEL_BILINEAR = 1.0/16 * np.array(((1, 2, 1), (2, 4, 2), (1, 2, 1))) KERNEL_GAUSSIAN = 1.0/256 * np.array(((1, 4, 6, 4, 1), (4, 16, 24, 16, 4), (6, 24, 36, 24, 6), (4, 16, 24, 16, 4), (1, 4, 6, 4, 1))) KERNEL_SOBEL = 1.0/8 * np.array(((-1, 0, 1), (-2, 0, 2), (-1, 0, 1))) KERNEL_CORNER = 1.0/4 * np.array((( 1, -2, 1), (-2, 4, -2), ( 1, -2, 1))) def gaussian_kernel(sigma_x, sigma_y=None): """ Normalized Gaussian kernel """ if not sigma_y: sigma_y = sigma_x X, Y = np.meshgrid(np.arange(-sigma_x, sigma_x+1, dtype=float), np.arange(-sigma_y, sigma_y+1, dtype=float)) G = np.exp(- (X**2 / (2*sigma_x**2) + Y**2 / (2*sigma_y**2))) # Normalize return G / G.sum()
[ "numpy.arange", "numpy.array", "numpy.exp" ]
[((86, 129), 'numpy.array', 'np.array', (['((1, 2, 1), (2, 4, 2), (1, 2, 1))'], {}), '(((1, 2, 1), (2, 4, 2), (1, 2, 1)))\n', (94, 129), True, 'import numpy as np\n'), ((231, 340), 'numpy.array', 'np.array', (['((1, 4, 6, 4, 1), (4, 16, 24, 16, 4), (6, 24, 36, 24, 6), (4, 16, 24, 16, 4\n ), (1, 4, 6, 4, 1))'], {}), '(((1, 4, 6, 4, 1), (4, 16, 24, 16, 4), (6, 24, 36, 24, 6), (4, 16, \n 24, 16, 4), (1, 4, 6, 4, 1)))\n', (239, 340), True, 'import numpy as np\n'), ((518, 564), 'numpy.array', 'np.array', (['((-1, 0, 1), (-2, 0, 2), (-1, 0, 1))'], {}), '(((-1, 0, 1), (-2, 0, 2), (-1, 0, 1)))\n', (526, 564), True, 'import numpy as np\n'), ((656, 703), 'numpy.array', 'np.array', (['((1, -2, 1), (-2, 4, -2), (1, -2, 1))'], {}), '(((1, -2, 1), (-2, 4, -2), (1, -2, 1)))\n', (664, 703), True, 'import numpy as np\n'), ((1060, 1128), 'numpy.exp', 'np.exp', (['(-(X ** 2 / (2 * sigma_x ** 2) + Y ** 2 / (2 * sigma_y ** 2)))'], {}), '(-(X ** 2 / (2 * sigma_x ** 2) + Y ** 2 / (2 * sigma_y ** 2)))\n', (1066, 1128), True, 'import numpy as np\n'), ((939, 984), 'numpy.arange', 'np.arange', (['(-sigma_x)', '(sigma_x + 1)'], {'dtype': 'float'}), '(-sigma_x, sigma_x + 1, dtype=float)\n', (948, 984), True, 'import numpy as np\n'), ((1007, 1052), 'numpy.arange', 'np.arange', (['(-sigma_y)', '(sigma_y + 1)'], {'dtype': 'float'}), '(-sigma_y, sigma_y + 1, dtype=float)\n', (1016, 1052), True, 'import numpy as np\n')]
import numpy as np import torch import torch.nn as nn from torch.distributions.log_normal import LogNormal from geometry import get_ang,get_dih,get_cb fold_params = { "SG7" : np.array([[[-2,3,6,7,6,3,-2]]])/21, "SG9" : np.array([[[-21,14,39,54,59,54,39,14,-21]]])/231, "DCUT" : 19.5, "ALPHA" : 1.57, # TODO: add Cb to the motif "NCAC" : np.array([[-0.676, -1.294, 0. ], [ 0. , 0. , 0. ], [ 1.5 , -0.174, 0. ]], dtype=np.float32), "CLASH" : 2.0, "PCUT" : 0.5, "DSTEP" : 0.5, "ASTEP" : np.deg2rad(10.0), "WANG" : 0.1, "WCST" : 0.1 } fold_params["SG"] = fold_params["SG9"] def perturb_init(xyz, batch, noise=0.5): L = xyz.shape[0] pert = torch.tensor(np.random.uniform(noise, size=(batch, L, 3)), dtype=xyz.dtype, device=xyz.device) xyz = xyz.unsqueeze(0) + pert.detach() return xyz def init_xyz_edm(mu,sigma,batch=1,steps=50): '''generate initial Ca trace from mu,sigma of predicted log-normal distributions''' device = mu.device L = mu.shape[-1] m = mu.detach() s = sigma.detach() # approximate initial distances by the mode # of lognormal distributions D = torch.exp(m-s*s) sampler = LogNormal(mu[0],sigma[0]) Ds = sampler.sample((batch,)) Ds[0] = D[0] # convert distance matrix to a Gramm matrix J = torch.eye(L,device=device)-torch.ones((L,L),device=device)/L G = -0.5*J@Ds**2@J # use three leading eigenvectors to approximate # initial coordinates e,v = torch.symeig(G,eigenvectors=True) ca = v[:,:,-3:]*e[:,-3:].unsqueeze(1)**0.5 def nll(xyz): dist = torch.cdist(xyz,xyz)+1e-6*torch.eye(L,device=device) nll = (0.5*((torch.log(dist)-m)/s + torch.log(dist*s*(2*np.pi)**0.5))**2).mean() return nll nll0 = nll(ca) nll1 = nll0 # fine-tuning by minimization of log-likelihoods shift = torch.zeros_like(ca,device=device,requires_grad=True) if steps>0: minimizer = torch.optim.Adam([shift], lr=0.5) for i in range(steps): minimizer.zero_grad() nll1 = nll(ca+shift) nll1.backward() minimizer.step() return ca+shift #,nll0,nll1 def Q2R(Q): '''convert quaternions to rotation matrices''' b,l,_ = Q.shape w,x,y,z = Q[...,0],Q[...,1],Q[...,2],Q[...,3] xx,xy,xz,xw = x*x, x*y, x*z, x*w yy,yz,yw = y*y, y*z, y*w zz,zw = z*z, z*w R = torch.stack([1-2*yy-2*zz, 2*xy-2*zw, 2*xz+2*yw, 2*xy+2*zw, 1-2*xx-2*zz, 2*yz-2*xw, 2*xz-2*yw, 2*yz+2*xw, 1-2*xx-2*yy],dim=-1).view(b,l,3,3) return R class TRFold(): def __init__(self, pred, params=fold_params): self.pred = pred self.params = params self.device = self.pred[0].device # dfire background correction for distograms self.bkgd = (torch.linspace(4.25,19.75,32,device=self.device)/ self.params['DCUT'])**self.params['ALPHA'] # background correction for phi ang = torch.linspace(0,np.pi,19,device=self.device)[:-1] self.bkgp = 0.5*(torch.cos(ang)-torch.cos(ang+np.deg2rad(10.0))) # Sav-Gol filter self.sg = torch.from_numpy(self.params['SG']).float().to(self.device) # paddings for distograms: # left - linear clash; right - zeroes padRsize = self.sg.shape[-1]//2+3 padLsize = padRsize + 8 padR = torch.zeros(padRsize,device=self.device) padL = torch.arange(1,padLsize+1,device=self.device).flip(0)*self.params['CLASH'] self.padR = padR[:,None] self.padL = padL[:,None] # backbone motif self.ncac = torch.from_numpy(self.params['NCAC']).to(self.device) def akima(self, y,h): ''' Akima spline coefficients (boundaries trimmed to [2:-2]) https://doi.org/10.1145/321607.321609 ''' m = (y[:,1:]-y[:,:-1])/h #m += 1e-3*torch.randn(m.shape, device=m.device) m4m3 = torch.abs(m[:,3:]-m[:,2:-1]) m2m1 = torch.abs(m[:,1:-2]-m[:,:-3]) t = (m4m3*m[:,1:-2] + m2m1*m[:,2:-1])/(m4m3+m2m1) t[torch.isnan(t)] = 0.0 dy = y[:,3:-2]-y[:,2:-3] coef = torch.stack([y[:,2:-3], t[:,:-1], (3*dy/h - 2*t[:,:-1] - t[:,1:])/h, (t[:,:-1]+t[:,1:] - 2*dy/h)/h**2], dim=-1) return coef def fold(self, lognorm=None, ca_trace=None, batch=32, lr=0.2, nsteps=100): pd,po,pt,pp = self.pred L = pd.shape[-1] p20 = (6.0-pd[-1]-po[-1]-pt[-1]-pp[-1]-(pt[-1]+pp[-1]).T)/6 i,j = torch.triu_indices(L,L,1,device=self.device) sel = torch.where(p20[i,j]>self.params['PCUT'])[0] # indices for dist and omega (symmetric) i_s,j_s = i[sel], j[sel] # indices for theta and phi (asymmetric) i_a,j_a = torch.hstack([i_s,j_s]), torch.hstack([j_s,i_s]) # background-corrected initial restraints cstd = -torch.log(pd[4:36,i_s,j_s]/self.bkgd[:,None]) csto = -torch.log(po[0:36,i_s,j_s]/(1./36)) # omega and theta cstt = -torch.log(pt[0:36,i_a,j_a]/(1./36)) # are almost uniform cstp = -torch.log(pp[0:18,i_a,j_a]/self.bkgp[:,None]) # padded restraints pad = self.sg.shape[-1]//2+3 cstd = torch.cat([self.padL+cstd[0],cstd,self.padR+cstd[-1]],dim=0) csto = torch.cat([csto[-pad:],csto,csto[:pad]],dim=0) cstt = torch.cat([cstt[-pad:],cstt,cstt[:pad]],dim=0) cstp = torch.cat([cstp[:pad].flip(0),cstp,cstp[-pad:].flip(0)],dim=0) # smoothed restraints cstd,csto,cstt,cstp = [nn.functional.conv1d(cst.T.unsqueeze(1),self.sg)[:,0] for cst in [cstd,csto,cstt,cstp]] # force distance restraints vanish at long distances cstd = cstd-cstd[:,-1][:,None] # akima spline coefficients coefd = self.akima(cstd, self.params['DSTEP']).detach() coefo = self.akima(csto, self.params['ASTEP']).detach() coeft = self.akima(cstt, self.params['ASTEP']).detach() coefp = self.akima(cstp, self.params['ASTEP']).detach() astep = self.params['ASTEP'] ko = torch.arange(i_s.shape[0],device=self.device).repeat(batch) kt = torch.arange(i_a.shape[0],device=self.device).repeat(batch) # initial Ca placement if lognorm is not None: # using EDM+minimization mu = lognorm[...,0] sigma = lognorm[...,1] xyz = init_xyz_edm(mu,sigma,batch,50) elif ca_trace is not None: # using predicted backbone xyz = perturb_init(ca_trace, batch) # (batch, L, 3) else: sys.exit('Either "xyz" or "ca_trace" should be specified.') # optimization variables: T - shift vectors, Q - rotation quaternions T = torch.zeros_like(xyz,device=self.device,requires_grad=True) Q = torch.randn([batch,L,4],device=self.device,requires_grad=True) bb0 = self.ncac[None,:,None,:].repeat(batch,1,L,1) opt = torch.optim.Adam([T,Q], lr=lr) for step in range(nsteps): R = Q2R(Q/torch.norm(Q,dim=-1,keepdim=True)) bb = torch.einsum("blij,bklj->bkli",R,bb0)+(xyz+T)[:,None] # TODO: include Cb in the motif N,Ca,C = bb[:,0],bb[:,1],bb[:,2] Cb = get_cb(N,Ca,C) o = get_dih(Ca[:,i_s],Cb[:,i_s],Cb[:,j_s],Ca[:,j_s]) + np.pi t = get_dih(N[:,i_a],Ca[:,i_a],Cb[:,i_a],Cb[:,j_a]) + np.pi p = get_ang(Ca[:,i_a],Cb[:,i_a],Cb[:,j_a]) dij = torch.norm(Cb[:,i_s]-Cb[:,j_s],dim=-1) b,k = torch.where(dij<20.0) dk = dij[b,k] kbin = torch.ceil((dk-0.25)/0.5).long() dx = (dk-0.25)%0.5 c = coefd[k,kbin] lossd = c[:,0]+c[:,1]*dx+c[:,2]*dx**2+c[:,3]*dx**3 # omega obin = torch.ceil((o.view(-1)-astep/2)/astep).long() do = (o.view(-1)-astep/2)%astep co = coefo[ko,obin] losso = (co[:,0]+co[:,1]*do+co[:,2]*do**2+co[:,3]*do**3).view(batch,-1) #.mean(1) # theta tbin = torch.ceil((t.view(-1)-astep/2)/astep).long() dt = (t.view(-1)-astep/2)%astep ct = coeft[kt,tbin] losst = (ct[:,0]+ct[:,1]*dt+ct[:,2]*dt**2+ct[:,3]*dt**3).view(batch,-1) #.mean(1) # phi pbin = torch.ceil((p.view(-1)-astep/2)/astep).long() dp = (p.view(-1)-astep/2)%astep cp = coefp[kt,pbin] lossp = (cp[:,0]+cp[:,1]*dp+cp[:,2]*dp**2+cp[:,3]*dp**3).view(batch,-1) #.mean(1) # restrain geometry of peptide bonds loss_nc = (torch.norm(C[:,:-1]-N[:,1:],dim=-1)-1.32868)**2 loss_cacn = (get_ang(Ca[:,:-1], C[:,:-1], N[:,1:]) - 2.02807)**2 loss_canc = (get_ang(Ca[:,1:], N[:,1:], C[:,:-1]) - 2.12407)**2 loss_geom = loss_nc.mean(1) + loss_cacn.mean(1) + loss_canc.mean(1) loss_ang = losst.mean(1) + losso.mean(1) + lossp.mean(1) # coefficient for ramping up geometric restraints during minimization coef = (1.0+step)/nsteps loss = lossd.mean() + self.params['WANG']*loss_ang.mean() + coef*self.params['WCST']*loss_geom.mean() opt.zero_grad() loss.backward() opt.step() lossd = torch.stack([lossd[b==i].mean() for i in range(batch)]) loss = lossd + self.params['WANG']*loss_ang + self.params['WCST']*loss_geom minidx = torch.argmin(loss) return bb[minidx] #.permute(1,0,2)
[ "torch.eye", "geometry.get_cb", "torch.cat", "torch.randn", "torch.cos", "torch.ceil", "torch.arange", "torch.isnan", "torch.ones", "torch.hstack", "torch.triu_indices", "geometry.get_dih", "torch.exp", "geometry.get_ang", "torch.zeros", "torch.log", "torch.zeros_like", "torch.where", "torch.norm", "torch.distributions.log_normal.LogNormal", "torch.abs", "torch.einsum", "torch.optim.Adam", "torch.from_numpy", "numpy.random.uniform", "torch.stack", "torch.symeig", "numpy.deg2rad", "torch.cdist", "numpy.array", "torch.linspace", "torch.argmin" ]
[((379, 471), 'numpy.array', 'np.array', (['[[-0.676, -1.294, 0.0], [0.0, 0.0, 0.0], [1.5, -0.174, 0.0]]'], {'dtype': 'np.float32'}), '([[-0.676, -1.294, 0.0], [0.0, 0.0, 0.0], [1.5, -0.174, 0.0]],\n dtype=np.float32)\n', (387, 471), True, 'import numpy as np\n'), ((618, 634), 'numpy.deg2rad', 'np.deg2rad', (['(10.0)'], {}), '(10.0)\n', (628, 634), True, 'import numpy as np\n'), ((1267, 1287), 'torch.exp', 'torch.exp', (['(m - s * s)'], {}), '(m - s * s)\n', (1276, 1287), False, 'import torch\n'), ((1298, 1324), 'torch.distributions.log_normal.LogNormal', 'LogNormal', (['mu[0]', 'sigma[0]'], {}), '(mu[0], sigma[0])\n', (1307, 1324), False, 'from torch.distributions.log_normal import LogNormal\n'), ((1613, 1647), 'torch.symeig', 'torch.symeig', (['G'], {'eigenvectors': '(True)'}), '(G, eigenvectors=True)\n', (1625, 1647), False, 'import torch\n'), ((2003, 2058), 'torch.zeros_like', 'torch.zeros_like', (['ca'], {'device': 'device', 'requires_grad': '(True)'}), '(ca, device=device, requires_grad=True)\n', (2019, 2058), False, 'import torch\n'), ((184, 221), 'numpy.array', 'np.array', (['[[[-2, 3, 6, 7, 6, 3, -2]]]'], {}), '([[[-2, 3, 6, 7, 6, 3, -2]]])\n', (192, 221), True, 'import numpy as np\n'), ((236, 288), 'numpy.array', 'np.array', (['[[[-21, 14, 39, 54, 59, 54, 39, 14, -21]]]'], {}), '([[[-21, 14, 39, 54, 59, 54, 39, 14, -21]]])\n', (244, 288), True, 'import numpy as np\n'), ((806, 850), 'numpy.random.uniform', 'np.random.uniform', (['noise'], {'size': '(batch, L, 3)'}), '(noise, size=(batch, L, 3))\n', (823, 850), True, 'import numpy as np\n'), ((1436, 1463), 'torch.eye', 'torch.eye', (['L'], {'device': 'device'}), '(L, device=device)\n', (1445, 1463), False, 'import torch\n'), ((2093, 2126), 'torch.optim.Adam', 'torch.optim.Adam', (['[shift]'], {'lr': '(0.5)'}), '([shift], lr=0.5)\n', (2109, 2126), False, 'import torch\n'), ((3593, 3634), 'torch.zeros', 'torch.zeros', (['padRsize'], {'device': 'self.device'}), '(padRsize, device=self.device)\n', (3604, 3634), False, 'import torch\n'), ((4145, 4177), 'torch.abs', 'torch.abs', (['(m[:, 3:] - m[:, 2:-1])'], {}), '(m[:, 3:] - m[:, 2:-1])\n', (4154, 4177), False, 'import torch\n'), ((4189, 4222), 'torch.abs', 'torch.abs', (['(m[:, 1:-2] - m[:, :-3])'], {}), '(m[:, 1:-2] - m[:, :-3])\n', (4198, 4222), False, 'import torch\n'), ((4357, 4496), 'torch.stack', 'torch.stack', (['[y[:, 2:-3], t[:, :-1], (3 * dy / h - 2 * t[:, :-1] - t[:, 1:]) / h, (t[:,\n :-1] + t[:, 1:] - 2 * dy / h) / h ** 2]'], {'dim': '(-1)'}), '([y[:, 2:-3], t[:, :-1], (3 * dy / h - 2 * t[:, :-1] - t[:, 1:]) /\n h, (t[:, :-1] + t[:, 1:] - 2 * dy / h) / h ** 2], dim=-1)\n', (4368, 4496), False, 'import torch\n'), ((4802, 4849), 'torch.triu_indices', 'torch.triu_indices', (['L', 'L', '(1)'], {'device': 'self.device'}), '(L, L, 1, device=self.device)\n', (4820, 4849), False, 'import torch\n'), ((5522, 5589), 'torch.cat', 'torch.cat', (['[self.padL + cstd[0], cstd, self.padR + cstd[-1]]'], {'dim': '(0)'}), '([self.padL + cstd[0], cstd, self.padR + cstd[-1]], dim=0)\n', (5531, 5589), False, 'import torch\n'), ((5598, 5647), 'torch.cat', 'torch.cat', (['[csto[-pad:], csto, csto[:pad]]'], {'dim': '(0)'}), '([csto[-pad:], csto, csto[:pad]], dim=0)\n', (5607, 5647), False, 'import torch\n'), ((5660, 5709), 'torch.cat', 'torch.cat', (['[cstt[-pad:], cstt, cstt[:pad]]'], {'dim': '(0)'}), '([cstt[-pad:], cstt, cstt[:pad]], dim=0)\n', (5669, 5709), False, 'import torch\n'), ((7112, 7173), 'torch.zeros_like', 'torch.zeros_like', (['xyz'], {'device': 'self.device', 'requires_grad': '(True)'}), '(xyz, device=self.device, requires_grad=True)\n', (7128, 7173), False, 'import torch\n'), ((7184, 7250), 'torch.randn', 'torch.randn', (['[batch, L, 4]'], {'device': 'self.device', 'requires_grad': '(True)'}), '([batch, L, 4], device=self.device, requires_grad=True)\n', (7195, 7250), False, 'import torch\n'), ((7329, 7360), 'torch.optim.Adam', 'torch.optim.Adam', (['[T, Q]'], {'lr': 'lr'}), '([T, Q], lr=lr)\n', (7345, 7360), False, 'import torch\n'), ((9913, 9931), 'torch.argmin', 'torch.argmin', (['loss'], {}), '(loss)\n', (9925, 9931), False, 'import torch\n'), ((1463, 1496), 'torch.ones', 'torch.ones', (['(L, L)'], {'device': 'device'}), '((L, L), device=device)\n', (1473, 1496), False, 'import torch\n'), ((1732, 1753), 'torch.cdist', 'torch.cdist', (['xyz', 'xyz'], {}), '(xyz, xyz)\n', (1743, 1753), False, 'import torch\n'), ((2549, 2743), 'torch.stack', 'torch.stack', (['[1 - 2 * yy - 2 * zz, 2 * xy - 2 * zw, 2 * xz + 2 * yw, 2 * xy + 2 * zw, 1 -\n 2 * xx - 2 * zz, 2 * yz - 2 * xw, 2 * xz - 2 * yw, 2 * yz + 2 * xw, 1 -\n 2 * xx - 2 * yy]'], {'dim': '(-1)'}), '([1 - 2 * yy - 2 * zz, 2 * xy - 2 * zw, 2 * xz + 2 * yw, 2 * xy +\n 2 * zw, 1 - 2 * xx - 2 * zz, 2 * yz - 2 * xw, 2 * xz - 2 * yw, 2 * yz +\n 2 * xw, 1 - 2 * xx - 2 * yy], dim=-1)\n', (2560, 2743), False, 'import torch\n'), ((3178, 3226), 'torch.linspace', 'torch.linspace', (['(0)', 'np.pi', '(19)'], {'device': 'self.device'}), '(0, np.pi, 19, device=self.device)\n', (3192, 3226), False, 'import torch\n'), ((4287, 4301), 'torch.isnan', 'torch.isnan', (['t'], {}), '(t)\n', (4298, 4301), False, 'import torch\n'), ((4861, 4905), 'torch.where', 'torch.where', (["(p20[i, j] > self.params['PCUT'])"], {}), "(p20[i, j] > self.params['PCUT'])\n", (4872, 4905), False, 'import torch\n'), ((5065, 5089), 'torch.hstack', 'torch.hstack', (['[i_s, j_s]'], {}), '([i_s, j_s])\n', (5077, 5089), False, 'import torch\n'), ((5090, 5114), 'torch.hstack', 'torch.hstack', (['[j_s, i_s]'], {}), '([j_s, i_s])\n', (5102, 5114), False, 'import torch\n'), ((5182, 5232), 'torch.log', 'torch.log', (['(pd[4:36, i_s, j_s] / self.bkgd[:, None])'], {}), '(pd[4:36, i_s, j_s] / self.bkgd[:, None])\n', (5191, 5232), False, 'import torch\n'), ((5244, 5286), 'torch.log', 'torch.log', (['(po[0:36, i_s, j_s] / (1.0 / 36))'], {}), '(po[0:36, i_s, j_s] / (1.0 / 36))\n', (5253, 5286), False, 'import torch\n'), ((5314, 5356), 'torch.log', 'torch.log', (['(pt[0:36, i_a, j_a] / (1.0 / 36))'], {}), '(pt[0:36, i_a, j_a] / (1.0 / 36))\n', (5323, 5356), False, 'import torch\n'), ((5387, 5437), 'torch.log', 'torch.log', (['(pp[0:18, i_a, j_a] / self.bkgp[:, None])'], {}), '(pp[0:18, i_a, j_a] / self.bkgp[:, None])\n', (5396, 5437), False, 'import torch\n'), ((7632, 7648), 'geometry.get_cb', 'get_cb', (['N', 'Ca', 'C'], {}), '(N, Ca, C)\n', (7638, 7648), False, 'from geometry import get_ang, get_dih, get_cb\n'), ((7821, 7864), 'geometry.get_ang', 'get_ang', (['Ca[:, i_a]', 'Cb[:, i_a]', 'Cb[:, j_a]'], {}), '(Ca[:, i_a], Cb[:, i_a], Cb[:, j_a])\n', (7828, 7864), False, 'from geometry import get_ang, get_dih, get_cb\n'), ((7891, 7934), 'torch.norm', 'torch.norm', (['(Cb[:, i_s] - Cb[:, j_s])'], {'dim': '(-1)'}), '(Cb[:, i_s] - Cb[:, j_s], dim=-1)\n', (7901, 7934), False, 'import torch\n'), ((7948, 7971), 'torch.where', 'torch.where', (['(dij < 20.0)'], {}), '(dij < 20.0)\n', (7959, 7971), False, 'import torch\n'), ((1758, 1785), 'torch.eye', 'torch.eye', (['L'], {'device': 'device'}), '(L, device=device)\n', (1767, 1785), False, 'import torch\n'), ((3001, 3052), 'torch.linspace', 'torch.linspace', (['(4.25)', '(19.75)', '(32)'], {'device': 'self.device'}), '(4.25, 19.75, 32, device=self.device)\n', (3015, 3052), False, 'import torch\n'), ((3254, 3268), 'torch.cos', 'torch.cos', (['ang'], {}), '(ang)\n', (3263, 3268), False, 'import torch\n'), ((3840, 3877), 'torch.from_numpy', 'torch.from_numpy', (["self.params['NCAC']"], {}), "(self.params['NCAC'])\n", (3856, 3877), False, 'import torch\n'), ((6421, 6467), 'torch.arange', 'torch.arange', (['i_s.shape[0]'], {'device': 'self.device'}), '(i_s.shape[0], device=self.device)\n', (6433, 6467), False, 'import torch\n'), ((6494, 6540), 'torch.arange', 'torch.arange', (['i_a.shape[0]'], {'device': 'self.device'}), '(i_a.shape[0], device=self.device)\n', (6506, 6540), False, 'import torch\n'), ((7471, 7510), 'torch.einsum', 'torch.einsum', (['"""blij,bklj->bkli"""', 'R', 'bb0'], {}), "('blij,bklj->bkli', R, bb0)\n", (7483, 7510), False, 'import torch\n'), ((7676, 7731), 'geometry.get_dih', 'get_dih', (['Ca[:, i_s]', 'Cb[:, i_s]', 'Cb[:, j_s]', 'Ca[:, j_s]'], {}), '(Ca[:, i_s], Cb[:, i_s], Cb[:, j_s], Ca[:, j_s])\n', (7683, 7731), False, 'from geometry import get_ang, get_dih, get_cb\n'), ((7749, 7803), 'geometry.get_dih', 'get_dih', (['N[:, i_a]', 'Ca[:, i_a]', 'Cb[:, i_a]', 'Cb[:, j_a]'], {}), '(N[:, i_a], Ca[:, i_a], Cb[:, i_a], Cb[:, j_a])\n', (7756, 7803), False, 'from geometry import get_ang, get_dih, get_cb\n'), ((3649, 3698), 'torch.arange', 'torch.arange', (['(1)', '(padLsize + 1)'], {'device': 'self.device'}), '(1, padLsize + 1, device=self.device)\n', (3661, 3698), False, 'import torch\n'), ((7419, 7454), 'torch.norm', 'torch.norm', (['Q'], {'dim': '(-1)', 'keepdim': '(True)'}), '(Q, dim=-1, keepdim=True)\n', (7429, 7454), False, 'import torch\n'), ((8016, 8045), 'torch.ceil', 'torch.ceil', (['((dk - 0.25) / 0.5)'], {}), '((dk - 0.25) / 0.5)\n', (8026, 8045), False, 'import torch\n'), ((9036, 9076), 'torch.norm', 'torch.norm', (['(C[:, :-1] - N[:, 1:])'], {'dim': '(-1)'}), '(C[:, :-1] - N[:, 1:], dim=-1)\n', (9046, 9076), False, 'import torch\n'), ((9109, 9149), 'geometry.get_ang', 'get_ang', (['Ca[:, :-1]', 'C[:, :-1]', 'N[:, 1:]'], {}), '(Ca[:, :-1], C[:, :-1], N[:, 1:])\n', (9116, 9149), False, 'from geometry import get_ang, get_dih, get_cb\n'), ((9186, 9225), 'geometry.get_ang', 'get_ang', (['Ca[:, 1:]', 'N[:, 1:]', 'C[:, :-1]'], {}), '(Ca[:, 1:], N[:, 1:], C[:, :-1])\n', (9193, 9225), False, 'from geometry import get_ang, get_dih, get_cb\n'), ((3283, 3299), 'numpy.deg2rad', 'np.deg2rad', (['(10.0)'], {}), '(10.0)\n', (3293, 3299), True, 'import numpy as np\n'), ((3354, 3389), 'torch.from_numpy', 'torch.from_numpy', (["self.params['SG']"], {}), "(self.params['SG'])\n", (3370, 3389), False, 'import torch\n'), ((1829, 1869), 'torch.log', 'torch.log', (['(dist * s * (2 * np.pi) ** 0.5)'], {}), '(dist * s * (2 * np.pi) ** 0.5)\n', (1838, 1869), False, 'import torch\n'), ((1806, 1821), 'torch.log', 'torch.log', (['dist'], {}), '(dist)\n', (1815, 1821), False, 'import torch\n')]
# coding: utf-8 # In[6]: import pandas as pd import numpy as np import matplotlib.pyplot as plt get_ipython().magic('matplotlib inline') #D:\Book4.csv data = input('enter the data path ') sep = input('enter the seperater ') df = pd.read_csv(data,sep) #select all non-num data ap=df.select_dtypes(exclude=['number']) #convert into array df2=ap.as_matrix() #numpy array ap_2d = np.array(df2) #list of all non-numerical col first_col = list(ap) print(first_col) #plot for a in first_col: df.boxplot(by=a,figsize=(20,10))
[ "pandas.read_csv", "numpy.array" ]
[((235, 257), 'pandas.read_csv', 'pd.read_csv', (['data', 'sep'], {}), '(data, sep)\n', (246, 257), True, 'import pandas as pd\n'), ((385, 398), 'numpy.array', 'np.array', (['df2'], {}), '(df2)\n', (393, 398), True, 'import numpy as np\n')]
import numpy as np from os import path import MCPM class TpfRectangles(object): """ Keeps information on rectangles that are used in TPF files. Note that there may be multple rectangles for a single TPF, some rectangles are not full, and some may have width or height of 1 pixel """ def __init__(self, campaign, channel): self.campaign = campaign self.channel = channel file_name = "tpf_rectangles_{:}_{:}.data".format(campaign, channel) if int(self.campaign) in [91, 92]: subdir = 'K2C9' elif int(self.campaign) in [111, 112]: subdir = 'K2C11' else: msg = 'expected campaigns: 91, 92, 111, or 112; got {:}' raise ValueError(msg.format(self.campaign)) directory = path.join(MCPM.MODULE_PATH, 'data', subdir) path_ = path.join(directory, 'tpf_rectangles', file_name) load = np.loadtxt(path_, unpack=True, dtype=int) (epic, self.min_x, self.max_x, self.min_y, self.max_y) = load self.epic = np.array(epic, dtype=str) self.center_x = (self.max_x + self.min_x) / 2. self.center_y = (self.max_y + self.min_y) / 2. self.half_size_x = self.max_x - self.center_x self.half_size_y = self.max_y - self.center_y def point_distances(self, x, y): """get distance from given (x,y) point to all the rectangles""" dx = np.maximum(np.abs(x - self.center_x) - self.half_size_x, 0.) dy = np.maximum(np.abs(y - self.center_y) - self.half_size_y, 0.) return np.sqrt(dx**2 + dy**2) def closest_epics(self, x, y): """for given point (x,y), calculate all the distances and then sort them so that sorted list of epics is returned; takes into account only the closest rectangle from given epic""" distances = self.point_distances(x=x, y=y) indexes = np.argsort(distances) out_epic = [] out_distance = [] for i in indexes: if self.epic[i] in out_epic: continue out_epic.append(self.epic[i]) out_distance.append(distances[i]) return (np.array(out_epic), np.array(out_distance)) def get_epic_id_for_pixel(self, x, y): """find in which TPF given pixel lies""" distances = self.point_distances(x=x, y=y) selection = (distances == 0.) if not selection.any(): return None else: return self.epic[np.argmax(selection)] def get_nearest_epic(self, x, y): """find the nearest epic; return its id and distance (0 if point is inside it)""" distances = self.point_distances(x=x, y=y) index = np.argmin(distances) return (self.epic[index], distances[index])
[ "numpy.abs", "numpy.argmax", "numpy.argmin", "numpy.argsort", "numpy.array", "numpy.loadtxt", "os.path.join", "numpy.sqrt" ]
[((814, 857), 'os.path.join', 'path.join', (['MCPM.MODULE_PATH', '"""data"""', 'subdir'], {}), "(MCPM.MODULE_PATH, 'data', subdir)\n", (823, 857), False, 'from os import path\n'), ((875, 924), 'os.path.join', 'path.join', (['directory', '"""tpf_rectangles"""', 'file_name'], {}), "(directory, 'tpf_rectangles', file_name)\n", (884, 924), False, 'from os import path\n'), ((940, 981), 'numpy.loadtxt', 'np.loadtxt', (['path_'], {'unpack': '(True)', 'dtype': 'int'}), '(path_, unpack=True, dtype=int)\n', (950, 981), True, 'import numpy as np\n'), ((1072, 1097), 'numpy.array', 'np.array', (['epic'], {'dtype': 'str'}), '(epic, dtype=str)\n', (1080, 1097), True, 'import numpy as np\n'), ((1615, 1641), 'numpy.sqrt', 'np.sqrt', (['(dx ** 2 + dy ** 2)'], {}), '(dx ** 2 + dy ** 2)\n', (1622, 1641), True, 'import numpy as np\n'), ((1957, 1978), 'numpy.argsort', 'np.argsort', (['distances'], {}), '(distances)\n', (1967, 1978), True, 'import numpy as np\n'), ((2789, 2809), 'numpy.argmin', 'np.argmin', (['distances'], {}), '(distances)\n', (2798, 2809), True, 'import numpy as np\n'), ((2223, 2241), 'numpy.array', 'np.array', (['out_epic'], {}), '(out_epic)\n', (2231, 2241), True, 'import numpy as np\n'), ((2243, 2265), 'numpy.array', 'np.array', (['out_distance'], {}), '(out_distance)\n', (2251, 2265), True, 'import numpy as np\n'), ((1476, 1501), 'numpy.abs', 'np.abs', (['(x - self.center_x)'], {}), '(x - self.center_x)\n', (1482, 1501), True, 'import numpy as np\n'), ((1550, 1575), 'numpy.abs', 'np.abs', (['(y - self.center_y)'], {}), '(y - self.center_y)\n', (1556, 1575), True, 'import numpy as np\n'), ((2551, 2571), 'numpy.argmax', 'np.argmax', (['selection'], {}), '(selection)\n', (2560, 2571), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Tue May 19 17:54:12 2020 @author: Shaji,Charu,Selva """ import scipy import numpy as np import pandas as pd from sklearn.impute import KNNImputer pd.set_option('mode.chained_assignment', None) from . import helper from . import exceptions def get_distance(dataset, start_latitude, start_longitude, end_latitude, end_longitude): """ Usage: [arg1]:[Pandas DataFrame],[arg2]:[column-start_latitude],[arg3]:[column-start_longitude],[arg4]:[column-end_latitude],[arg5]:[column-end_longitude] Returns: DataFrame with additional column [Distance in kilometers] """ print("This module (ctrl4ai.preprocessing) will be depreciated by the end of 2021. Please plan to switch to the same functions in ctrl4ai.prepdata") dataset['kms_'+start_latitude+'_'+end_latitude]=dataset.apply(lambda row: helper.distance_calculator(row[start_latitude], row[start_longitude],row[end_latitude],row[end_longitude]),axis=1) return dataset def get_timediff(dataset, start_time, end_time): """ Usage: [arg1]:[Pandas DataFrame],[arg2]:[column-start_time],[arg3]:[column-end_time] Returns: DataFrame with additional column [Duration in seconds] """ print("This module (ctrl4ai.preprocessing) will be depreciated by the end of 2021. Please plan to switch to the same functions in ctrl4ai.prepdata") dataset['secs_diff_'+start_time+'_'+end_time]=(dataset[end_time]-dataset[start_time]).dt.total_seconds() return dataset def derive_from_datetime(dataset): """ Usage: [arg1]:[pandas dataframe] Prerequisite: Type for datetime columns to be defined correctly Description: Derives the hour, weekday, year and month from a datetime column Returns: Dataframe [with new columns derived from datetime columns] """ print("This module (ctrl4ai.preprocessing) will be depreciated by the end of 2021. Please plan to switch to the same functions in ctrl4ai.prepdata") for column,dtype in dataset.dtypes.items(): if 'datetime' in str(dtype): dataset['hour_of_'+column]=dataset[column].apply(lambda x: x.hour) dataset['weekday_of_'+column]=dataset[column].apply(lambda x: x.weekday()) dataset['year_of_'+column]=dataset[column].apply(lambda x: x.year) dataset['month_of_'+column]=dataset[column].apply(lambda x: x.month) return dataset def log_transform(dataset,method='yeojohnson',categorical_threshold=0.3): """ Usage: [arg1]:[pandas dataframe],[method]=['yeojohnson'/'added_constant'] Description: Checks if the a continuous column is skewed and does log transformation Returns: Dataframe [with all skewed columns normalized using appropriate approach] """ print("This module (ctrl4ai.preprocessing) will be depreciated by the end of 2021. Please plan to switch to the same functions in ctrl4ai.prepdata") for col in dataset.columns: if helper.check_categorical_col(dataset[col],categorical_threshold=categorical_threshold)==False and helper.check_numeric_col(dataset[col]) and np.abs(scipy.stats.skew(dataset[col]))>1: print('Log Normalization('+method+') applied for '+col) if method=='yeojohnson': dataset[col]=dataset[col].apply(lambda x: helper.yeojohnsonlog(x)) elif method=='added_constant': dataset=helper.added_constant_log(dataset,col) return dataset def drop_null_fields(dataset, dropna_threshold=0.7): """ Usage: [arg1]:[pandas dataframe],[dropna_threshold(default=0.7)]:[What percentage of nulls should account for the column top be removed] Description: Drop columns that has more null values Returns: Dataframe [with null dominated columns removed] """ print("This module (ctrl4ai.preprocessing) will be depreciated by the end of 2021. Please plan to switch to the same functions in ctrl4ai.prepdata") no_of_records=dataset.shape[0] select_cols=[] for index,val in dataset.isnull().sum().items(): if val/no_of_records<dropna_threshold: select_cols.append(index) else: print('Dropping null dominated column(s) '+index) return(dataset[select_cols]) def drop_single_valued_cols(dataset): """ Usage: [arg1]:[pandas dataframe] Description: Drop columns that has only one value in it Returns: Dataframe [without single valued columns] """ print("This module (ctrl4ai.preprocessing) will be depreciated by the end of 2021. Please plan to switch to the same functions in ctrl4ai.prepdata") single_valued_cols=[] for col in dataset.columns: if helper.single_valued_col(dataset[col]): single_valued_cols.append(col) if len(single_valued_cols)>0: print('Dropping single valued column(s) '+','.join(single_valued_cols)) dataset=dataset.drop(single_valued_cols,axis=1) return dataset def get_ohe_df(dataset, target_variable=None, ignore_cols=[], categorical_threshold=0.3): """ Usage: [arg1]:[pandas dataframe],[target_variable(default=None)]:[Dependent variable for Regression/Classification],[ignore_cols]:[categorical columns where one hot encoding need not be done],[categorical_threshold(default=0.3)]:[Threshold for determining categorical column based on the percentage of unique values(optional)] Description: Auto identifies categorical features in the dataframe and does one hot encoding Note: Consumes more system mermory if the size of the dataset is huge Returns: Dataframe [with separate column for each categorical values] """ print("This module (ctrl4ai.preprocessing) will be depreciated by the end of 2021. Please plan to switch to the same functions in ctrl4ai.prepdata") for col in dataset.columns: if helper.check_categorical_col(dataset[col],categorical_threshold=categorical_threshold) and col!=target_variable and col not in ignore_cols: print('One hot encoding '+col) dataset=helper.one_hot_encoding(dataset,[col]) return dataset def drop_non_numeric(dataset): """ Usage: [arg1]:[pandas dataframe] Description: Drop columns that are not numeric Returns: Dataframe [only numeric features] """ print("This module (ctrl4ai.preprocessing) will be depreciated by the end of 2021. Please plan to switch to the same functions in ctrl4ai.prepdata") drop_cols=[] for col in dataset.columns: if helper.check_numeric_col(dataset[col])==False: drop_cols.append(col) if len(drop_cols)>0: print("Dropping non categorical/continuous column(s):"+','.join(drop_cols)) dataset=dataset.drop(drop_cols,axis=1) return dataset def impute_nulls(dataset, method='central_tendency'): """ Usage: [arg1]:[pandas dataframe],[method(default=central_tendency)]:[Choose either central_tendency or KNN] Description: Auto identifies the type of distribution in the column and imputes null values Note: KNN consumes more system mermory if the size of the dataset is huge Returns: Dataframe [with separate column for each categorical values] """ print("This module (ctrl4ai.preprocessing) will be depreciated by the end of 2021. Please plan to switch to the same functions in ctrl4ai.prepdata") if str.lower(method)=='knn': k_knn=int(np.ceil(np.sqrt(dataset.shape[0]))) if k_knn%2==0: k_knn+=1 imputer = KNNImputer(n_neighbors=k_knn) knn_imputed_array = imputer.fit_transform(dataset) dataset=pd.DataFrame(knn_imputed_array,columns=dataset.columns) return dataset elif method=='central_tendency': for col,value in dataset.isnull().sum().items(): if value>0: if helper.check_categorical_col(dataset[col]): print("Replaced nulls in "+col+" with mode") mode_val=dataset[col].mode()[0] dataset[col]=dataset[col].fillna(mode_val) elif helper.check_numeric_col(dataset[col]): if np.abs(scipy.stats.skew(dataset[col]))>1: print("Replaced nulls in "+col+" with median") median_val=dataset[col].median() dataset[col]=dataset[col].fillna(median_val) else: print("Replaced nulls in "+col+" with mean") mean_val=dataset[col].mean() dataset[col]=dataset[col].fillna(mean_val) return dataset else: print('Method should be either central_tendency or knn') raise exceptions.ParameterError def label_encode(dataset, col): """ Usage: [arg1]:[pandas dataframe],[arg1]:[column to be encoded] Description: Labelling categorical features with numbers from 0 to n categories Returns: Label Dict , Dataframe """ print("This module (ctrl4ai.preprocessing) will be depreciated by the end of 2021. Please plan to switch to the same functions in ctrl4ai.prepdata") mode_val=dataset[col].mode()[0] dataset[col]=dataset[col].apply(lambda x:str(x).strip()).astype(str).fillna(mode_val) label_dict=dict(zip(dataset[col].unique(),np.arange(dataset[col].unique().shape[0]))) dataset=dataset.replace({col:label_dict}) dataset[col]=dataset[col].astype('int') dataset[col]=dataset[col].astype('category') return label_dict,dataset def remove_outlier_df(dataset, cols): """ Usage: [arg1]:[pandas dataframe],[arg2]:[list of columns to check and remove outliers] Description: The column needs to be continuous Returns: DataFrame with outliers removed for the specific columns """ print("This module (ctrl4ai.preprocessing) will be depreciated by the end of 2021. Please plan to switch to the same functions in ctrl4ai.prepdata") for col in cols: outlier_temp_dataset=pd.DataFrame(dataset[col]) outlier_temp_dataset=impute_nulls(outlier_temp_dataset) Q1 = outlier_temp_dataset.quantile(0.25) Q3 = outlier_temp_dataset.quantile(0.75) IQR = Q3 - Q1 outlier_bool_dataset=((outlier_temp_dataset > (Q1 - 1.5 * IQR)) & (outlier_temp_dataset < (Q3 + 1.5 * IQR))) select_index=outlier_bool_dataset.index[outlier_bool_dataset[col] == True] print('No. of outlier rows removed based on '+col+' is '+str(outlier_temp_dataset.shape[0]-len(select_index))) dataset=dataset.iloc[select_index].reset_index(drop=True) return dataset def auto_remove_outliers(dataset, ignore_cols=[], categorical_threshold=0.3): """ Usage: [arg1]:[pandas dataframe],[ignore_cols]:[list of columns to be ignored],[categorical_threshold(default=0.3)]:[Threshold for determining categorical column based on the percentage of unique values(optional)] Description: Checks if the column is continuous and removes outliers Returns: DataFrame with outliers removed """ print("This module (ctrl4ai.preprocessing) will be depreciated by the end of 2021. Please plan to switch to the same functions in ctrl4ai.prepdata") continuous_columns=[] for col in dataset.columns: if helper.check_categorical_col(dataset[col],categorical_threshold=categorical_threshold)==False and helper.check_numeric_col(dataset[col])==True: continuous_columns.append(col) dataset=remove_outlier_df(dataset,continuous_columns) return dataset def get_label_encoded_df(dataset, categorical_threshold=0.3): """ Usage: [arg1]:[pandas dataframe],[categorical_threshold(default=0.3)]:[Threshold for determining categorical column based on the percentage of unique values(optional)] Description: Auto identifies categorical features in the dataframe and does label encoding Returns: Dataframe [with separate column for each categorical values] """ print("This module (ctrl4ai.preprocessing) will be depreciated by the end of 2021. Please plan to switch to the same functions in ctrl4ai.prepdata") column_labels=dict() for col in dataset.columns: if helper.check_numeric_col(dataset[col]): pass elif helper.check_categorical_col(dataset[col],categorical_threshold=categorical_threshold): labels,dataset=label_encode(dataset,col) print('Labels for '+col+': '+str(labels)) column_labels[col]=labels return column_labels,dataset def cramersv_corr(x, y): """ Usage: [arg1]:[categorical series],[arg2]:[categorical series] Description: Cramer's V Correlation is a measure of association between two categorical variables Returns: A value between 0 and +1 """ print("This module (ctrl4ai.preprocessing) will be depreciated by the end of 2021. Please plan to switch to the same functions in ctrl4ai.prepdata") confusion_matrix = pd.crosstab(x,y) chi2 = scipy.stats.chi2_contingency(confusion_matrix)[0] n = confusion_matrix.sum().sum() phi2 = chi2/n r,k = confusion_matrix.shape phi2corr = max(0, phi2-((k-1)*(r-1))/(n-1)) rcorr = r-((r-1)**2)/(n-1) kcorr = k-((k-1)**2)/(n-1) return np.sqrt(phi2corr/min((kcorr-1),(rcorr-1))) def kendalltau_corr(x, y): """ Usage: [arg1]:[continuous series],[arg2]:[categorical series] Description: Kendall Tau Correlation is a measure of association between a continuous variable and a categorical variable Returns: A value between -1 and +1 """ print("This module (ctrl4ai.preprocessing) will be depreciated by the end of 2021. Please plan to switch to the same functions in ctrl4ai.prepdata") x_arr=np.array(impute_nulls(pd.DataFrame(x))) y_arr=np.array(impute_nulls(pd.DataFrame(y))) corr,_=scipy.stats.kendalltau(x_arr,y_arr) return corr def pearson_corr(x, y): """ Usage: [arg1]:[continuous series],[arg2]:[continuous series] Description: Pearson Correlation is a measure of association between two continuous variables Returns: A value between -1 and +1 """ print("This module (ctrl4ai.preprocessing) will be depreciated by the end of 2021. Please plan to switch to the same functions in ctrl4ai.prepdata") x=pd.to_numeric(x) y=pd.to_numeric(y) return np.corrcoef(x,y)[0,1] def get_correlated_features(dataset, target_col, target_type, categorical_threshold=0.3): """ Usage: [arg1]:[pandas dataframe],[arg2]:[target/dependent variable],[arg3]:['continuous'/'categorical'],,[categorical_threshold(default=0.3)]:[Threshold for determining categorical column based on the percentage of unique values(optional)] Description: Only for supervised learning to select independent variables that has some correlation with target/dependent variable (Uses Pearson correlation between two continuous variables, CramersV correlation between two categorical variables, Kendalls Tau correlation between a categorical and a continuos variable) Returns: Dictionary of correlation coefficients, List of columns that have considerable correlation """ print("This module (ctrl4ai.preprocessing) will be depreciated by the end of 2021. Please plan to switch to the same functions in ctrl4ai.prepdata") categorical_cols=[] continuous_cols=[] col_corr=dict() for col in dataset: if col!=target_col: if helper.check_categorical_col(dataset[col],categorical_threshold=categorical_threshold): categorical_cols.append(col) elif helper.check_numeric_col(dataset[col]): continuous_cols.append(col) if target_type=='continuous': for col in continuous_cols: coeff=pearson_corr(dataset[col],dataset[target_col]) col_corr[col]=coeff for col in categorical_cols: coeff=kendalltau_corr(dataset[col],dataset[target_col]) col_corr[col]=coeff if target_type=='categorical': for col in continuous_cols: coeff=kendalltau_corr(dataset[col],dataset[target_col]) col_corr[col]=coeff for col in categorical_cols: coeff=cramersv_corr(dataset[col],dataset[target_col]) col_corr[col]=coeff selected_features=[] for col in col_corr.keys(): if float(col_corr[col])>np.abs(2/np.sqrt(dataset.shape[0])): selected_features.append(col) return col_corr,selected_features
[ "pandas.DataFrame", "pandas.crosstab", "numpy.corrcoef", "scipy.stats.skew", "sklearn.impute.KNNImputer", "scipy.stats.chi2_contingency", "scipy.stats.kendalltau", "pandas.set_option", "pandas.to_numeric", "numpy.sqrt" ]
[((187, 233), 'pandas.set_option', 'pd.set_option', (['"""mode.chained_assignment"""', 'None'], {}), "('mode.chained_assignment', None)\n", (200, 233), True, 'import pandas as pd\n'), ((12490, 12507), 'pandas.crosstab', 'pd.crosstab', (['x', 'y'], {}), '(x, y)\n', (12501, 12507), True, 'import pandas as pd\n'), ((13326, 13362), 'scipy.stats.kendalltau', 'scipy.stats.kendalltau', (['x_arr', 'y_arr'], {}), '(x_arr, y_arr)\n', (13348, 13362), False, 'import scipy\n'), ((13765, 13781), 'pandas.to_numeric', 'pd.to_numeric', (['x'], {}), '(x)\n', (13778, 13781), True, 'import pandas as pd\n'), ((13786, 13802), 'pandas.to_numeric', 'pd.to_numeric', (['y'], {}), '(y)\n', (13799, 13802), True, 'import pandas as pd\n'), ((7310, 7339), 'sklearn.impute.KNNImputer', 'KNNImputer', ([], {'n_neighbors': 'k_knn'}), '(n_neighbors=k_knn)\n', (7320, 7339), False, 'from sklearn.impute import KNNImputer\n'), ((7407, 7463), 'pandas.DataFrame', 'pd.DataFrame', (['knn_imputed_array'], {'columns': 'dataset.columns'}), '(knn_imputed_array, columns=dataset.columns)\n', (7419, 7463), True, 'import pandas as pd\n'), ((9604, 9630), 'pandas.DataFrame', 'pd.DataFrame', (['dataset[col]'], {}), '(dataset[col])\n', (9616, 9630), True, 'import pandas as pd\n'), ((12516, 12562), 'scipy.stats.chi2_contingency', 'scipy.stats.chi2_contingency', (['confusion_matrix'], {}), '(confusion_matrix)\n', (12544, 12562), False, 'import scipy\n'), ((13812, 13829), 'numpy.corrcoef', 'np.corrcoef', (['x', 'y'], {}), '(x, y)\n', (13823, 13829), True, 'import numpy as np\n'), ((13251, 13266), 'pandas.DataFrame', 'pd.DataFrame', (['x'], {}), '(x)\n', (13263, 13266), True, 'import pandas as pd\n'), ((13299, 13314), 'pandas.DataFrame', 'pd.DataFrame', (['y'], {}), '(y)\n', (13311, 13314), True, 'import pandas as pd\n'), ((7234, 7259), 'numpy.sqrt', 'np.sqrt', (['dataset.shape[0]'], {}), '(dataset.shape[0])\n', (7241, 7259), True, 'import numpy as np\n'), ((3084, 3114), 'scipy.stats.skew', 'scipy.stats.skew', (['dataset[col]'], {}), '(dataset[col])\n', (3100, 3114), False, 'import scipy\n'), ((15799, 15824), 'numpy.sqrt', 'np.sqrt', (['dataset.shape[0]'], {}), '(dataset.shape[0])\n', (15806, 15824), True, 'import numpy as np\n'), ((7866, 7896), 'scipy.stats.skew', 'scipy.stats.skew', (['dataset[col]'], {}), '(dataset[col])\n', (7882, 7896), False, 'import scipy\n')]
import cv2 as cv import os import glob import numpy as np # Checkerboard contains 25mm squares - 8x6 vertices, 9x7 squares # 28mm (equivalent) f/1.8 lens with OIS # https://www.camerafv5.com/devices/manufacturers/google/pixel_3a_xl_bonito_0/ # 12.2Mp 1/2.55-inch sensor with 1.4µm pixel width pixel_size = 1.4e-6 # number of pixels in 1 square mm # termination criteria criteria = (cv.TermCriteria_EPS + cv.TERM_CRITERIA_MAX_ITER, 30, 0.001) # object points checker_square_size = np.mean([23.36, 23.35, 23.32, 23.22, 23.43, 23.20, 23.28]) # size in mm objp = np.zeros((8 * 6, 3), np.float32) objp[:, :2] = np.mgrid[0:8, 0:6].T.reshape(-1, 2) objp = checker_square_size * objp objpoints = [] # 3D point in world coords imgpoints = [] # 2D point in image coords path = "F:/Documents/Python Scripts/Phone Calibration Images/" os.chdir(path) images = glob.glob("*.jpg") patternSize = (8, 6) flags = None for i, fname in enumerate(images): img = cv.imread(fname) gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) ret, corners = cv.findChessboardCorners(gray, patternSize, flags) print(f'Completed {i + 1} images.') if ret is True: objpoints.append(objp) corners2 = cv.cornerSubPix(gray, corners, winSize=(11, 11), zeroZone=(-1, -1), criteria=criteria) imgpoints.append(corners) cv.drawChessboardCorners(img, patternSize, corners2, ret) # cv.imshow('img', img) cv.waitKey(100) cv.destroyAllWindows() os.chdir("F:/Documents/Python Scripts/") ret, mtx, dist, rvecs, tvecs = cv.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None) # mtx[:2, :] = mtx[:2, :] * (pixel_size * 1e3) # Converts focal length to mm mean_error = 0 for i in range(len(objpoints)): imgpoints2, _ = cv.projectPoints(objpoints[i], rvecs[i], tvecs[i], mtx, dist) error = cv.norm(imgpoints[i], imgpoints2, cv.NORM_L2)/len(imgpoints2) mean_error += error total_reproj_err = mean_error/len(objpoints) print("total error: {}".format(total_reproj_err)) np.savez('calibration_data', ret=ret, calibratoin_matrix=mtx, distortion_params=dist, rotation_vecs=rvecs, translation_vecs=tvecs, reprojection_error=total_reproj_err) cv.namedWindow("original", cv.WINDOW_NORMAL) # Create window with freedom of dimensions im = cv.imread("PXL_20210407_172636685.jpg") # Read image imS = cv.resize(im, (1240, 1080)) # Resize image cv.imshow("original", imS) # Show image cv.waitKey(100) # Display the image infinitely until any keypress img = cv.imread('PXL_20210407_172636685.jpg') h, w = img.shape[:2] newcameramtx, roi = cv.getOptimalNewCameraMatrix(mtx, dist, (w, h), 1, (w, h)) dst = cv.undistort(img, mtx, dist, None, newcameramtx) x, y, w, h = roi dst = dst[y:y+h, x:x+w] cv.imwrite('calibresult.png', dst)
[ "numpy.mean", "glob.glob", "cv2.imshow", "os.chdir", "cv2.undistort", "cv2.cvtColor", "cv2.imwrite", "cv2.destroyAllWindows", "cv2.resize", "cv2.getOptimalNewCameraMatrix", "cv2.waitKey", "cv2.projectPoints", "cv2.calibrateCamera", "cv2.norm", "numpy.savez", "cv2.drawChessboardCorners", "cv2.findChessboardCorners", "numpy.zeros", "cv2.cornerSubPix", "cv2.imread", "cv2.namedWindow" ]
[((501, 558), 'numpy.mean', 'np.mean', (['[23.36, 23.35, 23.32, 23.22, 23.43, 23.2, 23.28]'], {}), '([23.36, 23.35, 23.32, 23.22, 23.43, 23.2, 23.28])\n', (508, 558), True, 'import numpy as np\n'), ((584, 616), 'numpy.zeros', 'np.zeros', (['(8 * 6, 3)', 'np.float32'], {}), '((8 * 6, 3), np.float32)\n', (592, 616), True, 'import numpy as np\n'), ((860, 874), 'os.chdir', 'os.chdir', (['path'], {}), '(path)\n', (868, 874), False, 'import os\n'), ((885, 903), 'glob.glob', 'glob.glob', (['"""*.jpg"""'], {}), "('*.jpg')\n", (894, 903), False, 'import glob\n'), ((1501, 1523), 'cv2.destroyAllWindows', 'cv.destroyAllWindows', ([], {}), '()\n', (1521, 1523), True, 'import cv2 as cv\n'), ((1525, 1565), 'os.chdir', 'os.chdir', (['"""F:/Documents/Python Scripts/"""'], {}), "('F:/Documents/Python Scripts/')\n", (1533, 1565), False, 'import os\n'), ((1600, 1670), 'cv2.calibrateCamera', 'cv.calibrateCamera', (['objpoints', 'imgpoints', 'gray.shape[::-1]', 'None', 'None'], {}), '(objpoints, imgpoints, gray.shape[::-1], None, None)\n', (1618, 1670), True, 'import cv2 as cv\n'), ((2086, 2261), 'numpy.savez', 'np.savez', (['"""calibration_data"""'], {'ret': 'ret', 'calibratoin_matrix': 'mtx', 'distortion_params': 'dist', 'rotation_vecs': 'rvecs', 'translation_vecs': 'tvecs', 'reprojection_error': 'total_reproj_err'}), "('calibration_data', ret=ret, calibratoin_matrix=mtx,\n distortion_params=dist, rotation_vecs=rvecs, translation_vecs=tvecs,\n reprojection_error=total_reproj_err)\n", (2094, 2261), True, 'import numpy as np\n'), ((2267, 2311), 'cv2.namedWindow', 'cv.namedWindow', (['"""original"""', 'cv.WINDOW_NORMAL'], {}), "('original', cv.WINDOW_NORMAL)\n", (2281, 2311), True, 'import cv2 as cv\n'), ((2368, 2407), 'cv2.imread', 'cv.imread', (['"""PXL_20210407_172636685.jpg"""'], {}), "('PXL_20210407_172636685.jpg')\n", (2377, 2407), True, 'import cv2 as cv\n'), ((2435, 2462), 'cv2.resize', 'cv.resize', (['im', '(1240, 1080)'], {}), '(im, (1240, 1080))\n', (2444, 2462), True, 'import cv2 as cv\n'), ((2497, 2523), 'cv2.imshow', 'cv.imshow', (['"""original"""', 'imS'], {}), "('original', imS)\n", (2506, 2523), True, 'import cv2 as cv\n'), ((2563, 2578), 'cv2.waitKey', 'cv.waitKey', (['(100)'], {}), '(100)\n', (2573, 2578), True, 'import cv2 as cv\n'), ((2674, 2713), 'cv2.imread', 'cv.imread', (['"""PXL_20210407_172636685.jpg"""'], {}), "('PXL_20210407_172636685.jpg')\n", (2683, 2713), True, 'import cv2 as cv\n'), ((2757, 2815), 'cv2.getOptimalNewCameraMatrix', 'cv.getOptimalNewCameraMatrix', (['mtx', 'dist', '(w, h)', '(1)', '(w, h)'], {}), '(mtx, dist, (w, h), 1, (w, h))\n', (2785, 2815), True, 'import cv2 as cv\n'), ((2825, 2873), 'cv2.undistort', 'cv.undistort', (['img', 'mtx', 'dist', 'None', 'newcameramtx'], {}), '(img, mtx, dist, None, newcameramtx)\n', (2837, 2873), True, 'import cv2 as cv\n'), ((2918, 2952), 'cv2.imwrite', 'cv.imwrite', (['"""calibresult.png"""', 'dst'], {}), "('calibresult.png', dst)\n", (2928, 2952), True, 'import cv2 as cv\n'), ((991, 1007), 'cv2.imread', 'cv.imread', (['fname'], {}), '(fname)\n', (1000, 1007), True, 'import cv2 as cv\n'), ((1020, 1055), 'cv2.cvtColor', 'cv.cvtColor', (['img', 'cv.COLOR_BGR2GRAY'], {}), '(img, cv.COLOR_BGR2GRAY)\n', (1031, 1055), True, 'import cv2 as cv\n'), ((1078, 1128), 'cv2.findChessboardCorners', 'cv.findChessboardCorners', (['gray', 'patternSize', 'flags'], {}), '(gray, patternSize, flags)\n', (1102, 1128), True, 'import cv2 as cv\n'), ((1822, 1883), 'cv2.projectPoints', 'cv.projectPoints', (['objpoints[i]', 'rvecs[i]', 'tvecs[i]', 'mtx', 'dist'], {}), '(objpoints[i], rvecs[i], tvecs[i], mtx, dist)\n', (1838, 1883), True, 'import cv2 as cv\n'), ((1249, 1339), 'cv2.cornerSubPix', 'cv.cornerSubPix', (['gray', 'corners'], {'winSize': '(11, 11)', 'zeroZone': '(-1, -1)', 'criteria': 'criteria'}), '(gray, corners, winSize=(11, 11), zeroZone=(-1, -1),\n criteria=criteria)\n', (1264, 1339), True, 'import cv2 as cv\n'), ((1382, 1439), 'cv2.drawChessboardCorners', 'cv.drawChessboardCorners', (['img', 'patternSize', 'corners2', 'ret'], {}), '(img, patternSize, corners2, ret)\n', (1406, 1439), True, 'import cv2 as cv\n'), ((1482, 1497), 'cv2.waitKey', 'cv.waitKey', (['(100)'], {}), '(100)\n', (1492, 1497), True, 'import cv2 as cv\n'), ((1897, 1942), 'cv2.norm', 'cv.norm', (['imgpoints[i]', 'imgpoints2', 'cv.NORM_L2'], {}), '(imgpoints[i], imgpoints2, cv.NORM_L2)\n', (1904, 1942), True, 'import cv2 as cv\n')]
import numpy as np import pandas as pd import matplotlib.pyplot as plt import codecademylib3 null_outcomes = [] for i in range(10000): simulated_monthly_visitors = np.random.choice(['y', 'n'], size=500, p=[0.1, 0.9]) num_purchased = np.sum(simulated_monthly_visitors == 'y') null_outcomes.append(num_purchased) #calculate the 90% interval here: null_90CI = np.percentile(null_outcomes, [5,95]) print(null_90CI)
[ "numpy.percentile", "numpy.sum", "numpy.random.choice" ]
[((368, 405), 'numpy.percentile', 'np.percentile', (['null_outcomes', '[5, 95]'], {}), '(null_outcomes, [5, 95])\n', (381, 405), True, 'import numpy as np\n'), ((168, 220), 'numpy.random.choice', 'np.random.choice', (["['y', 'n']"], {'size': '(500)', 'p': '[0.1, 0.9]'}), "(['y', 'n'], size=500, p=[0.1, 0.9])\n", (184, 220), True, 'import numpy as np\n'), ((240, 281), 'numpy.sum', 'np.sum', (["(simulated_monthly_visitors == 'y')"], {}), "(simulated_monthly_visitors == 'y')\n", (246, 281), True, 'import numpy as np\n')]
import json import logging import multiprocessing as mp import sys import pandas as pd import random import daisy import numpy as np from pymongo import MongoClient from scipy.spatial import KDTree import sqlite3 from funlib.math import cantor_number from . import database, synapse, evaluation logger = logging.getLogger(__name__) try: from lsd import local_segmentation except ImportError: local_segmentation = None logger.warning('Could not import lsd, mapping using a local segmentation is not possible') def get_random_links(num_samples, cursor, table='synlinks', fast=False): cols = ['pre_x', 'pre_y', 'pre_z', 'post_x', 'post_y', 'post_z', 'scores', 'segmentid_pre', 'segmentid_post', 'cleft_scores'] if fast: com = 'SELECT {} FROM {} WHERE random() % 1000 = 0 LIMIT {};'.format( ','.join(cols), table, num_samples) else: com = 'SELECT {} FROM {} ORDER BY Random() LIMIT {};'.format( ','.join(cols), table, num_samples) cursor.execute(com) return pd.DataFrame(cursor.fetchall(), columns=cols) class SynapseMapping(object): '''Maps synapses to ground truth skeletons and writes them into a database. It uses euclidean distance to cope with ambigious cases, eg. if one segment contains multiple skeletons, the pre/post site is mapped to the closest skeleton in euclidean space. If distance_upper_bound is set, only synapses are mapped to a skeleton if it closer than distance_upper_bound. Synapses that have been not mapped because of distance_upper_bound are marked with a skel_id of -2 (but still written out to database). Args: skel_db_name (``str``): Skeletons used for mapping. skel_db_host (``str``): Skeletons used for mapping. skel_db_col (``str``): Skeletons used for mapping. output_db_name (``str``): Mongodb name to which synapses are written out. If not provided syn_db_name is used. output_db_host (``str``)": If not provided, syn_db_host is used. output_db_col (``str``): If not provided, syn_db_col is used and distance_upper_bound is added. syndir (``str``): Synapses to be mapped stored in hirachical directory structure. syn_db_name (``str``): Synapses to be mapped stored in mongodb. syn_db_host (``str``): Synapses to be mapped stored in mongodb. syn_db_col (``str``): Synapses to be mapped stored in mongodb. gtsyn_db_name (``str``): If provided, those synapses are used as additional "skeletons" to which the synapses can be mapped to. Those nodes are ignored by num_skel_nodes_ignore eg. they are always used for mapping. gtsyn_db_host (``str``). gtsyn_db_col (``str``) seg_agglomeration_json (``str``): Jsonfile to produce a local segmentation. distance_upper_bound (float): If synapses are further away than distance_upper_bound, they are not mapped to the skeleton, although they are intersecting the same segment. num_skel_nodes_ignore (``int``): Ignore skeletons that intersect with number of skeletons: num_skel_nodes_ignore or less. This is used to account for noisy/incorrectly placed skeleton nodes, which should be ignored during mapping. multiprocess (``bool``): Whether to parallelize synapse mapping using the python-package multiprocessing mp_processes (``int``): Number of processes when multiprocess is set to true. draw_random_from_sql (``str``): sql database, from which randomly synapses are drawn. If this is set, syn_db_name is not used, instead, synapse direction vectors are drawn at random from provided database. Can be used to generate a "baseline" experiment. Only synapses are written out that have different pre and post skeleton ids (to reduce #of synapses). random_density (``float``): if draw_random_sql is set, provide the density in # synapses / cubic micron ''' def __init__(self, skel_db_name, skel_db_host, skel_db_col, output_db_name=None, output_db_host=None, output_db_col=None, syndir=None, syn_db_name=None, syn_db_host=None, syn_db_col=None, gtsyn_db_name=None, gtsyn_db_host=None, gtsyn_db_col=None, seg_agglomeration_json=None, distance_upper_bound=None, num_skel_nodes_ignore=0, multiprocess=False, mp_processes=40, draw_random_from_sql=None, random_density=10): assert syndir is not None or syn_db_col is not None or draw_random_from_sql is not None, 'synapses have to be ' \ 'provided either in syndir format or db format' self.skel_db_name = skel_db_name self.skel_db_host = skel_db_host self.skel_db_col = skel_db_col self.syn_db_name = syn_db_name self.syn_db_host = syn_db_host self.syn_db_col = syn_db_col self.syndir = syndir self.gtsyn_db_name = gtsyn_db_name self.gtsyn_db_host = gtsyn_db_host self.gtsyn_db_col = gtsyn_db_col self.output_db_name = output_db_name if output_db_name is not None else self.syn_db_name self.output_db_host = output_db_host if output_db_host is not None else self.syn_db_host output_db_col = output_db_col if output_db_col is not None else self.syn_db_col self.output_db_col = output_db_col + '_skel_{}'.format('inf' if distance_upper_bound is None else distance_upper_bound) self.seg_agglomeration_json = seg_agglomeration_json self.distance_upper_bound = distance_upper_bound self.num_skel_nodes_ignore = num_skel_nodes_ignore self.multiprocess = multiprocess self.mp_processes = mp_processes self.skel_df = pd.DataFrame() self.draw_random_from_sql = draw_random_from_sql self.random_density = random_density def __match_position_to_closest_skeleton(self, position, seg_id, skel_ids): distances = [] for skel_id in skel_ids: locations = list(self.skel_df[(self.skel_df.seg_id == seg_id) & (self.skel_df.neuron_id == skel_id)].position.apply(np.array)) tree = KDTree(locations) dist = tree.query(x=np.array(position), k=1, eps=0, p=2, distance_upper_bound=np.inf)[0] distances.append(dist) indexmin = np.argmin(np.array(distances)) logger.debug('matching node to skeleton with distance: %0.2f ' 'compared to average distance: %0.2f' % ( distances[indexmin], np.mean(distances))) if self.distance_upper_bound is not None: if distances[indexmin] > self.distance_upper_bound: logger.debug( 'synapse not mapped because distance {:0.2} ' 'bigger than {:}'.format( distances[indexmin], self.distance_upper_bound)) return -2 return skel_ids[indexmin] def match_synapses_to_skeleton(self, synapses): for ii, syn in enumerate(synapses): logger.debug('{}/{}'.format(ii, len(synapses))) # Which skeletons intersect with segmentation id ? skel_ids = list(np.unique(self.skel_df[self.skel_df['seg_id'] == syn.id_segm_pre]['neuron_id'])) if self.num_skel_nodes_ignore > 0: for skel_id in skel_ids: # With how many nodes does the skeleton intersect # current segment ? num_nodes = len(np.unique(self.skel_df[(self.skel_df[ 'seg_id'] == syn.id_segm_pre) & ( self.skel_df[ 'neuron_id'] == skel_id)][ 'id'])) node_types = np.unique(self.skel_df[(self.skel_df[ 'seg_id'] == syn.id_segm_pre) & ( self.skel_df[ 'neuron_id'] == skel_id)][ 'type']) include_node = 'connector' in node_types or 'post_tree_node' in node_types # Exclude skeletons when they have fewer numbers inside the # segment than num_skel_nodes_ignore. if 0 < num_nodes <= self.num_skel_nodes_ignore and not include_node: logger.debug( 'ignoring skel id: {} syn id: {}'.format( skel_id, syn.id)) skel_ids.remove(skel_id) if len(skel_ids) > 0: skel_ids = [ self.__match_position_to_closest_skeleton(syn.location_pre, syn.id_segm_pre, skel_ids)] syn.id_skel_pre = skel_ids[0] if len(skel_ids) > 0 else None skel_ids = list(np.unique(self.skel_df[self.skel_df['seg_id'] == syn.id_segm_post]['neuron_id'])) for skel_id in skel_ids: num_nodes = len(np.unique(self.skel_df[(self.skel_df[ 'seg_id'] == syn.id_segm_post) & ( self.skel_df[ 'neuron_id'] == skel_id)][ 'id'])) node_types = np.unique(self.skel_df[(self.skel_df[ 'seg_id'] == syn.id_segm_post) & ( self.skel_df[ 'neuron_id'] == skel_id)][ 'type']) include_node = 'connector' in node_types or 'post_tree_node' in node_types # Exclude skeletons when they have fewer numbers inside the # segment than num_skel_nodes_ignore. if 0 < num_nodes <= self.num_skel_nodes_ignore and not include_node: logger.debug( 'ignoring skel id: {} syn id: {}'.format( skel_id, syn.id)) skel_ids.remove(skel_id) if len(skel_ids) > 0: skel_ids = [ self.__match_position_to_closest_skeleton(syn.location_post, syn.id_segm_post, skel_ids)] syn.id_skel_post = skel_ids[0] if len(skel_ids) > 0 else None syn_db = database.SynapseDatabase(self.output_db_name, db_host=self.output_db_host, db_col_name=self.output_db_col, mode='r+') if self.draw_random_from_sql is not None: synapses = [syn for syn in synapses if syn.id_skel_pre != syn.id_skel_post] syn_db.write_synapses(synapses) logger.info('wrote mapped synapses') def add_skel_ids_daisy(self, roi_core, roi_context, seg_thr, seg_ids_ignore): """Maps synapses using a local segmentation. Args: roi_core: (``daisy.ROI``): The ROI that is used to read in the synapses. roi_context (``daisy.ROI``): The ROI that is used to read in skeletons and ground truth synapses, that are used for mapping. seg_thr (``float``): Edge score threshold used for agglomerating fragments to produce a local segmentation used for mapping. seg_ids_ignore (``list`` of ``int``): List of ids that are not used for mapping. Eg. all skeletons whose seg id are in seg_ids_ignore are removed and not used for mapping. """ with open(self.seg_agglomeration_json) as f: seg_config = json.load(f) # Get actual segmentation ROI seg = daisy.open_ds(seg_config['fragments_file'], seg_config['fragments_dataset']) # This reads in all synapses, where postsynaptic site is in ROI, but # it is not guaranteed, that presynaptic site is also in ROI. if self.draw_random_from_sql is None: if self.syndir is not None: synapses = synapse.read_synapses_in_roi(self.syndir, roi_core) else: syn_db = database.SynapseDatabase(self.syn_db_name, db_host=self.syn_db_host, db_col_name=self.syn_db_col, mode='r') synapses = syn_db.read_synapses(roi=roi_core) synapses = synapse.create_synapses_from_db(synapses) else: size_cubmicrons = roi_core.size()/1000**3 num_of_synapses = int(size_cubmicrons*self.random_density) # Generate num_of_synapses postsynaptic random locations. # if N of possible points gets really big, this solution is not nice :( zlist = range(int(roi_core.get_begin()[0]/seg.voxel_size[0]), int(roi_core.get_end()[0]/seg.voxel_size[0])) ylist = range(int(roi_core.get_begin()[1]/seg.voxel_size[1]), int(roi_core.get_end()[1]/seg.voxel_size[1])) xlist = range(int(roi_core.get_begin()[2]/seg.voxel_size[2]), int(roi_core.get_end()[2]/seg.voxel_size[2])) coords = [[z, y, x] for x in xlist for y in ylist for z in zlist] post_sites = random.sample(coords, num_of_synapses) conn = sqlite3.connect(self.draw_random_from_sql) c = conn.cursor() links = get_random_links(num_of_synapses, c) # returns pandas dataframe synapses = [] for ii, location_post in enumerate(post_sites): id = cantor_number(location_post) location_post *= np.array(seg.voxel_size) link = links.loc[ii] dir_vec = np.array((link.pre_z, link.pre_y, link.pre_x))-np.array((link.post_z, link.post_y, link.post_x)) syn = synapse.Synapse( id=np.int64(id), score=link.scores, location_pre=location_post+dir_vec, location_post=location_post ) synapses.append(syn) # Make sure to only look at synapses that are inside segmentation ROI. synapses = [syn for syn in synapses if seg.roi.contains(syn.location_pre) and seg.roi.contains(syn.location_post)] if len(synapses) == 0: logger.debug('no synapse in roi') return 0 pre_locations = [daisy.Coordinate(syn.location_pre) for syn in synapses] post_locations = [daisy.Coordinate(syn.location_post) for syn in synapses] # Compute Bounding box for pre_locations z_min, y_min, x_min = np.min(np.array(pre_locations), axis=0) z_max, y_max, x_max = np.min(np.array(pre_locations), axis=0) roi_big = daisy.Roi((z_min, y_min, x_min), (z_max - z_min, y_max - y_min, x_max - x_min)) roi_big = roi_big.union(roi_context) roi_big = roi_big.snap_to_grid(seg.voxel_size) roi_big = seg.roi.intersect(roi_big) # Load skeletons. gt_db = database.DAGDatabase(self.skel_db_name, db_host=self.skel_db_host, db_col_name=self.skel_db_col, mode='r') nodes = gt_db.read_nodes(roi_context) logger.info('number of skel nodes {}'.format(len(nodes))) if self.gtsyn_db_name is not None: gt_db = database.SynapseDatabase(self.gtsyn_db_name, db_host=self.gtsyn_db_host, db_col_name=self.gtsyn_db_col, mode='r') gt_synapses = gt_db.read_synapses(pre_post_roi=roi_big) gt_synapses = pd.DataFrame(gt_synapses) else: gt_synapses = pd.DataFrame([]) if len(nodes) == 0 and len(gt_synapses) == 0: logger.info('Neither skeleton nor synapse node found.') return 0 logger.debug('creating a local segmentation') locseg = local_segmentation.LocalSegmentationExtractor(**seg_config) seg = locseg.get_local_segmentation(roi_big, seg_thr) nodes_df = pd.DataFrame(nodes) if len(nodes_df) > 0: nodes_df = nodes_df[nodes_df.apply( lambda row: seg.roi.contains(daisy.Coordinate(row['position'])), axis=1)] nodes_df['seg_id'] = nodes_df.apply(lambda row: seg[daisy.Coordinate(row['position'])], axis=1) # # Also add ground truth connectors. if self.gtsyn_db_name is not None: use_tree_node = True if not 'pre_node_id' in gt_synapses: logger.warning( 'No tree nodes available, assining new node ids. ' 'Neuron nodes and synapse nodes might be counted multiple times.') use_tree_node = False if len(gt_synapses) == 0: logger.debug('No Ground Truth synapses') else: logger.info( 'number of catmaid synapses: {}'.format(len(gt_synapses))) pre_nodes = pd.DataFrame() pre_nodes['neuron_id'] = gt_synapses['pre_skel_id'] pre_nodes['position'] = list( zip(gt_synapses['pre_z'], gt_synapses['pre_y'], gt_synapses['pre_x'])) pre_nodes['type'] = 'connector' pre_nodes['id'] = gt_synapses.pre_node_id if use_tree_node else list(range(len(gt_synapses))) post_nodes = pd.DataFrame() post_nodes['neuron_id'] = gt_synapses['post_skel_id'] post_nodes['position'] = list( zip(gt_synapses['post_z'], gt_synapses['post_y'], gt_synapses['post_x'])) post_nodes['type'] = 'post_tree_node' post_nodes['id'] = gt_synapses.post_node_id if use_tree_node else list(range(len(gt_synapses), 2*len(gt_synapses))) syn_nodes = pd.concat([pre_nodes, post_nodes]) syn_nodes = syn_nodes[syn_nodes.apply( lambda row: seg.roi.contains(daisy.Coordinate(row['position'])), axis=1)] syn_nodes['seg_id'] = syn_nodes.apply(lambda row: seg[daisy.Coordinate( row['position'])], axis=1) nodes_df = nodes_df.append(syn_nodes, sort=False) # if len(nodes_df) == 0: # logger.info('Neither skeleton nor synapse node found.') # return 0 nodes_df = nodes_df[~nodes_df.seg_id.isin(seg_ids_ignore)] pre_ids = [seg[pre_loc] for pre_loc in pre_locations] post_ids = [seg[post_loc] for post_loc in post_locations] syn_on_skels = [] for ii, syn in enumerate(synapses): pre_id = pre_ids[ii] post_id = post_ids[ii] # Test whether segment intersects with a skeleton skel_syn_pre = not nodes_df[nodes_df.seg_id == pre_id].empty skel_syn_post = not nodes_df[nodes_df.seg_id == post_id].empty if skel_syn_pre or skel_syn_post: syn.id_segm_pre = pre_id syn.id_segm_post = post_id syn_on_skels.append(syn) self.skel_df = nodes_df logger.debug( 'matching {} synapses to skeletons, original number of synapses {}'.format( len(syn_on_skels), len(synapses))) self.match_synapses_to_skeleton(syn_on_skels) def add_skel_ids(self, seg_ids_ignore=[]): """Maps synapses to ground truth skeletons and writes them into a database. It is assumend that each ground truth neuron and each pre and postsynaptic site has already a segmentation ID assigned. Args: seg_ids_ignore (``list`` of ``int``): List of ids that are not used for mapping. Eg. all skeletons whose seg id are in seg_ids_ignore are removed and not used for mapping. """ gt_db = database.DAGDatabase(self.skel_db_name, db_host=self.skel_db_host, db_col_name=self.skel_db_col, mode='r') pred_db = database.SynapseDatabase(self.syn_db_name, db_host=self.syn_db_host, db_col_name=self.syn_db_col, mode='r') nodes = gt_db.read_nodes() nodes_df = pd.DataFrame(nodes) # Also add ground truth connectors. if self.gtsyn_db_name is not None: gt_db = database.SynapseDatabase(self.gtsyn_db_name, db_host=self.gtsyn_db_host, db_col_name=self.gtsyn_db_col, mode='r') gt_synapses = gt_db.read_synapses() gt_synapses = pd.DataFrame(gt_synapses) use_tree_node = True if not 'pre_node_id' in gt_synapses: logger.warning( 'No tree nodes available, assining new node ids. ' 'Neuron nodes and synapse nodes might be counted multiple times.') use_tree_node = False if len(gt_synapses) == 0: logger.debug('No Ground Truth synapses') else: logger.info( 'number of catmaid synapses: {}'.format(len(gt_synapses))) pre_nodes = pd.DataFrame() pre_nodes['neuron_id'] = gt_synapses['pre_skel_id'] pre_nodes['position'] = list( zip(gt_synapses['pre_z'], gt_synapses['pre_y'], gt_synapses['pre_x'])) pre_nodes['type'] = 'connector' pre_nodes['id'] = gt_synapses.pre_node_id if use_tree_node else list(range(len(gt_synapses))) pre_nodes['seg_id'] = gt_synapses.pre_seg_id post_nodes = pd.DataFrame() post_nodes['neuron_id'] = gt_synapses['post_skel_id'] post_nodes['position'] = list( zip(gt_synapses['post_z'], gt_synapses['post_y'], gt_synapses['post_x'])) post_nodes['type'] = 'post_tree_node' post_nodes['id'] = gt_synapses.post_node_id if use_tree_node else list(range(len(gt_synapses), 2*len(gt_synapses))) post_nodes['seg_id'] = gt_synapses.post_seg_id syn_nodes = pd.concat([pre_nodes, post_nodes]) nodes_df = nodes_df.append(syn_nodes, sort=False) if len(nodes_df) == 0: logger.info('Neither skeleton nor synapse node found.') return 0 nodes_df = nodes_df[~nodes_df.seg_id.isin(seg_ids_ignore)] self.skel_df = nodes_df seg_ids = list(np.unique(nodes_df.seg_id)) seg_ids = [int(id) for id in seg_ids] synapses = pred_db.synapses.find({'$or': [ {'pre_seg_id': {'$in': seg_ids}}, {'post_seg_id': {'$in': seg_ids}}, ]}) synapses = synapse.create_synapses_from_db(synapses) logger.info('found {} synapses '.format(len(synapses))) logger.info('Overwriting {}/{}/{}'.format(self.output_db_name, self.output_db_host, self.output_db_col)) syn_db = database.SynapseDatabase(self.output_db_name, db_host=self.output_db_host, db_col_name=self.output_db_col, mode='w') batch_size = 100 args = [] for ii in range(0, len(synapses), batch_size): if self.multiprocess: args.append(synapses[ii:ii + batch_size]) else: self.match_synapses_to_skeleton(synapses[ii:ii + batch_size]) if self.multiprocess: pool = mp.Pool(self.mp_processes) pool.map(self.match_synapses_to_skeleton, args) pool.close() pool.join()
[ "pandas.DataFrame", "daisy.open_ds", "json.load", "daisy.Coordinate", "random.sample", "numpy.unique", "lsd.local_segmentation.LocalSegmentationExtractor", "daisy.Roi", "numpy.mean", "numpy.array", "sqlite3.connect", "scipy.spatial.KDTree", "multiprocessing.Pool", "funlib.math.cantor_number", "numpy.int64", "pandas.concat", "logging.getLogger" ]
[((307, 334), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (324, 334), False, 'import logging\n'), ((6222, 6236), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (6234, 6236), True, 'import pandas as pd\n'), ((12961, 13037), 'daisy.open_ds', 'daisy.open_ds', (["seg_config['fragments_file']", "seg_config['fragments_dataset']"], {}), "(seg_config['fragments_file'], seg_config['fragments_dataset'])\n", (12974, 13037), False, 'import daisy\n'), ((16210, 16289), 'daisy.Roi', 'daisy.Roi', (['(z_min, y_min, x_min)', '(z_max - z_min, y_max - y_min, x_max - x_min)'], {}), '((z_min, y_min, x_min), (z_max - z_min, y_max - y_min, x_max - x_min))\n', (16219, 16289), False, 'import daisy\n'), ((17542, 17601), 'lsd.local_segmentation.LocalSegmentationExtractor', 'local_segmentation.LocalSegmentationExtractor', ([], {}), '(**seg_config)\n', (17587, 17601), False, 'from lsd import local_segmentation\n'), ((17684, 17703), 'pandas.DataFrame', 'pd.DataFrame', (['nodes'], {}), '(nodes)\n', (17696, 17703), True, 'import pandas as pd\n'), ((22261, 22280), 'pandas.DataFrame', 'pd.DataFrame', (['nodes'], {}), '(nodes)\n', (22273, 22280), True, 'import pandas as pd\n'), ((6634, 6651), 'scipy.spatial.KDTree', 'KDTree', (['locations'], {}), '(locations)\n', (6640, 6651), False, 'from scipy.spatial import KDTree\n'), ((6847, 6866), 'numpy.array', 'np.array', (['distances'], {}), '(distances)\n', (6855, 6866), True, 'import numpy as np\n'), ((12895, 12907), 'json.load', 'json.load', (['f'], {}), '(f)\n', (12904, 12907), False, 'import json\n'), ((14624, 14662), 'random.sample', 'random.sample', (['coords', 'num_of_synapses'], {}), '(coords, num_of_synapses)\n', (14637, 14662), False, 'import random\n'), ((14682, 14724), 'sqlite3.connect', 'sqlite3.connect', (['self.draw_random_from_sql'], {}), '(self.draw_random_from_sql)\n', (14697, 14724), False, 'import sqlite3\n'), ((15837, 15871), 'daisy.Coordinate', 'daisy.Coordinate', (['syn.location_pre'], {}), '(syn.location_pre)\n', (15853, 15871), False, 'import daisy\n'), ((15919, 15954), 'daisy.Coordinate', 'daisy.Coordinate', (['syn.location_post'], {}), '(syn.location_post)\n', (15935, 15954), False, 'import daisy\n'), ((16088, 16111), 'numpy.array', 'np.array', (['pre_locations'], {}), '(pre_locations)\n', (16096, 16111), True, 'import numpy as np\n'), ((16158, 16181), 'numpy.array', 'np.array', (['pre_locations'], {}), '(pre_locations)\n', (16166, 16181), True, 'import numpy as np\n'), ((17243, 17268), 'pandas.DataFrame', 'pd.DataFrame', (['gt_synapses'], {}), '(gt_synapses)\n', (17255, 17268), True, 'import pandas as pd\n'), ((17309, 17325), 'pandas.DataFrame', 'pd.DataFrame', (['[]'], {}), '([])\n', (17321, 17325), True, 'import pandas as pd\n'), ((22712, 22737), 'pandas.DataFrame', 'pd.DataFrame', (['gt_synapses'], {}), '(gt_synapses)\n', (22724, 22737), True, 'import pandas as pd\n'), ((24665, 24691), 'numpy.unique', 'np.unique', (['nodes_df.seg_id'], {}), '(nodes_df.seg_id)\n', (24674, 24691), True, 'import numpy as np\n'), ((25830, 25856), 'multiprocessing.Pool', 'mp.Pool', (['self.mp_processes'], {}), '(self.mp_processes)\n', (25837, 25856), True, 'import multiprocessing as mp\n'), ((7709, 7788), 'numpy.unique', 'np.unique', (["self.skel_df[self.skel_df['seg_id'] == syn.id_segm_pre]['neuron_id']"], {}), "(self.skel_df[self.skel_df['seg_id'] == syn.id_segm_pre]['neuron_id'])\n", (7718, 7788), True, 'import numpy as np\n'), ((9748, 9833), 'numpy.unique', 'np.unique', (["self.skel_df[self.skel_df['seg_id'] == syn.id_segm_post]['neuron_id']"], {}), "(self.skel_df[self.skel_df['seg_id'] == syn.id_segm_post]['neuron_id']\n )\n", (9757, 9833), True, 'import numpy as np\n'), ((10286, 10409), 'numpy.unique', 'np.unique', (["self.skel_df[(self.skel_df['seg_id'] == syn.id_segm_post) & (self.skel_df[\n 'neuron_id'] == skel_id)]['type']"], {}), "(self.skel_df[(self.skel_df['seg_id'] == syn.id_segm_post) & (self\n .skel_df['neuron_id'] == skel_id)]['type'])\n", (10295, 10409), True, 'import numpy as np\n'), ((14946, 14974), 'funlib.math.cantor_number', 'cantor_number', (['location_post'], {}), '(location_post)\n', (14959, 14974), False, 'from funlib.math import cantor_number\n'), ((15008, 15032), 'numpy.array', 'np.array', (['seg.voxel_size'], {}), '(seg.voxel_size)\n', (15016, 15032), True, 'import numpy as np\n'), ((18694, 18708), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (18706, 18708), True, 'import pandas as pd\n'), ((19126, 19140), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (19138, 19140), True, 'import pandas as pd\n'), ((19591, 19625), 'pandas.concat', 'pd.concat', (['[pre_nodes, post_nodes]'], {}), '([pre_nodes, post_nodes])\n', (19600, 19625), True, 'import pandas as pd\n'), ((23298, 23312), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (23310, 23312), True, 'import pandas as pd\n'), ((23791, 23805), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (23803, 23805), True, 'import pandas as pd\n'), ((24319, 24353), 'pandas.concat', 'pd.concat', (['[pre_nodes, post_nodes]'], {}), '([pre_nodes, post_nodes])\n', (24328, 24353), True, 'import pandas as pd\n'), ((7048, 7066), 'numpy.mean', 'np.mean', (['distances'], {}), '(distances)\n', (7055, 7066), True, 'import numpy as np\n'), ((8438, 8560), 'numpy.unique', 'np.unique', (["self.skel_df[(self.skel_df['seg_id'] == syn.id_segm_pre) & (self.skel_df[\n 'neuron_id'] == skel_id)]['type']"], {}), "(self.skel_df[(self.skel_df['seg_id'] == syn.id_segm_pre) & (self.\n skel_df['neuron_id'] == skel_id)]['type'])\n", (8447, 8560), True, 'import numpy as np\n'), ((9899, 10020), 'numpy.unique', 'np.unique', (["self.skel_df[(self.skel_df['seg_id'] == syn.id_segm_post) & (self.skel_df[\n 'neuron_id'] == skel_id)]['id']"], {}), "(self.skel_df[(self.skel_df['seg_id'] == syn.id_segm_post) & (self\n .skel_df['neuron_id'] == skel_id)]['id'])\n", (9908, 10020), True, 'import numpy as np\n'), ((15096, 15142), 'numpy.array', 'np.array', (['(link.pre_z, link.pre_y, link.pre_x)'], {}), '((link.pre_z, link.pre_y, link.pre_x))\n', (15104, 15142), True, 'import numpy as np\n'), ((15143, 15192), 'numpy.array', 'np.array', (['(link.post_z, link.post_y, link.post_x)'], {}), '((link.post_z, link.post_y, link.post_x))\n', (15151, 15192), True, 'import numpy as np\n'), ((6684, 6702), 'numpy.array', 'np.array', (['position'], {}), '(position)\n', (6692, 6702), True, 'import numpy as np\n'), ((8024, 8144), 'numpy.unique', 'np.unique', (["self.skel_df[(self.skel_df['seg_id'] == syn.id_segm_pre) & (self.skel_df[\n 'neuron_id'] == skel_id)]['id']"], {}), "(self.skel_df[(self.skel_df['seg_id'] == syn.id_segm_pre) & (self.\n skel_df['neuron_id'] == skel_id)]['id'])\n", (8033, 8144), True, 'import numpy as np\n'), ((15255, 15267), 'numpy.int64', 'np.int64', (['id'], {}), '(id)\n', (15263, 15267), True, 'import numpy as np\n'), ((18000, 18033), 'daisy.Coordinate', 'daisy.Coordinate', (["row['position']"], {}), "(row['position'])\n", (18016, 18033), False, 'import daisy\n'), ((17827, 17860), 'daisy.Coordinate', 'daisy.Coordinate', (["row['position']"], {}), "(row['position'])\n", (17843, 17860), False, 'import daisy\n'), ((19919, 19952), 'daisy.Coordinate', 'daisy.Coordinate', (["row['position']"], {}), "(row['position'])\n", (19935, 19952), False, 'import daisy\n'), ((19730, 19763), 'daisy.Coordinate', 'daisy.Coordinate', (["row['position']"], {}), "(row['position'])\n", (19746, 19763), False, 'import daisy\n')]
import numpy as np import tensorflow as tf class AbstractDiayn: def __init__(self, n_skills, n_envs, train_on_trajectory=None): assert train_on_trajectory is not None, "must pass argparse args" self.train_on_trajectory = train_on_trajectory self.n_skills = n_skills self.n_envs = n_envs pass def augment(self, timestep, score=None): # TODO add z to timestep or wtv obs = timestep.observation image = obs["image"] direction = obs["direction"] augmented_image = image.numpy() # tensorflow is an atrocity of a framework for i in range(self.n_envs): augmented_image[i,:,:,2] = self.skills[i] from tensorflow.python.framework.ops import EagerTensor augmented_image = tf.convert_to_tensor(augmented_image) from collections import OrderedDict augmented_obs = OrderedDict([("direction", direction), ("image",augmented_image)]) if score is not None: score = tf.convert_to_tensor(score) else: score = timestep.reward import tf_agents augmented_timestep = tf_agents.trajectories.time_step.TimeStep(timestep.step_type, score, timestep.discount, augmented_obs) return augmented_timestep def score_and_augment(self, timestep, as_one_hot=True): raise NotImplemented() return augmented_scored_timestep def train_on_trajectory(self, traj): if self.train_on_trajectory: self._train_on_trajectory(self, traj) def train_on_single_event(self, traj): if not self.train_on_trajectory: self._train_on_trajectory(self, traj) def _train_on_trajectory(self, traj): raise NotImplemented() def _reset_skills(self): self.skills = np.arange(self.n_skills) np.random.shuffle(self.skills) self.skills = self.skills[:self.n_envs] def reset(self, obs): self._reset_skills() return self.augment(obs) # NOTE: we don't score here! def reset_agent(self): raise NotImplemented()
[ "tensorflow.convert_to_tensor", "numpy.arange", "collections.OrderedDict", "tf_agents.trajectories.time_step.TimeStep", "numpy.random.shuffle" ]
[((791, 828), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['augmented_image'], {}), '(augmented_image)\n', (811, 828), True, 'import tensorflow as tf\n'), ((898, 965), 'collections.OrderedDict', 'OrderedDict', (["[('direction', direction), ('image', augmented_image)]"], {}), "([('direction', direction), ('image', augmented_image)])\n", (909, 965), False, 'from collections import OrderedDict\n'), ((1149, 1255), 'tf_agents.trajectories.time_step.TimeStep', 'tf_agents.trajectories.time_step.TimeStep', (['timestep.step_type', 'score', 'timestep.discount', 'augmented_obs'], {}), '(timestep.step_type, score,\n timestep.discount, augmented_obs)\n', (1190, 1255), False, 'import tf_agents\n'), ((1809, 1833), 'numpy.arange', 'np.arange', (['self.n_skills'], {}), '(self.n_skills)\n', (1818, 1833), True, 'import numpy as np\n'), ((1842, 1872), 'numpy.random.shuffle', 'np.random.shuffle', (['self.skills'], {}), '(self.skills)\n', (1859, 1872), True, 'import numpy as np\n'), ((1016, 1043), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['score'], {}), '(score)\n', (1036, 1043), True, 'import tensorflow as tf\n')]
""" PROJECT: IMAGE CLASSIFICATION FOR DOG - CAT IMAGEs FROM KAGGLE """ from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.neural_network import MLPClassifier from sklearn.svm import SVC import numpy import cv2 import os import glob # input images for img in glob.glob("D:/SP19/CIS-559_data mining/PROJECT/train1/*.jpg"): #folder train1 contains multiple dog and cat images in .jpg imagePaths = list(glob.glob("D:/SP19/CIS-559_data mining/PROJECT/train1/*.jpg")) #Extract the image into vector def image_vector(image, size=(128, 128)): return cv2.resize(image, size).flatten() # initialize the pixel intensities matrix, labels list imagemaxtrix = [] imagelabels = [] #Build image vector matrix for (i, path) in enumerate(imagePaths): # load the image and extract the class label, image intensities image = cv2.imread(path) label = path.split(os.path.sep)[-1].split(".")[0] pixels = image_vector(image) # update the images and labels matricies respectively imagemaxtrix.append(pixels) imagelabels.append(label) imagemaxtrix = numpy.array(imagemaxtrix) imagelabels = numpy.array(imagelabels) #Prepare data for training and testing (train_img, test_img, train_label, test_label) = train_test_split( imagemaxtrix, imagelabels, test_size=0.2, random_state=50) '''SVM MODEL IN SKLEARN''' model1 = SVC(max_iter=-1, kernel ='linear', class_weight='balanced', gamma ='scale')#kernel linear is better Gausian kernel here model1.fit(train_img, train_label) acc1 = model1.score(test_img, test_label) print("SVM model accuracy: {:.2f}%".format(acc1 * 100)) #ww= model1.coef_ #print(ww) #print(model1) '''KNN MODEL IN SKLEARN''' model2 = KNeighborsClassifier(n_neighbors=5, n_jobs=-1) model2.fit(train_img, train_label) acc2 = model2.score(test_img, test_label) print("KNN model accuracy: {:.2f}%".format(acc2 * 100)) '''ANN MODEL IN SKLEARN''' model3 = MLPClassifier(hidden_layer_sizes=(100,), max_iter=1000, alpha=1e-4, solver='sgd', tol=1e-4, random_state=1, learning_rate_init=.1) model3.fit(train_img, train_label) acc3 = model3.score(test_img, test_label) acc4 = model3.score(train_img, train_label) print(" TEST accuracy: {:.2f}%".format(acc3 * 100)) print(" TRAIN accuracy: {:.2f}%".format(acc4 * 100)) '''ANN MODEL IN TENSORFLOW AND KERAS''' #change the label from [cat,dog] into [0,1] for index, i in enumerate(train_label): if i =='cat': train_label[index] = 1 else: train_label[index] = 0 train_label for index, i in enumerate(test_label): if i =='cat': test_label[index] = 1 else: test_label[index] = 0 test_label from tensorflow.keras.models import Sequential model = Sequential() from tensorflow.keras.layers import Dense# Add the first hidden layer model.add(Dense(50, activation='relu', input_dim=49152)) #Dense: many connect many model.add(Dense(25, activation='relu'))# Add the second hidden layer model.add(Dense(1, activation='sigmoid'))# Add the output layer # Compile the model model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) #loss (internal the model) vs. accuracy (accuracy of prediction) # Train the model for 200 epochs model.fit(train_img, train_label, epochs=200) #train (80%) , test (15%), validation (5%) scores = model.evaluate(train_img, train_label) print("Training Accuracy: %.2f%%\n" % (scores[1]*100)) scores = model.evaluate(test_img, test_label) print("Testing Accuracy: %.2f%%\n" % (scores[1]*100)) '''PREDICATION SAMPLE''' rawImages1=[] pixel1= image_vector(cv2.imread("unseen_image.jpg")) rawImages1.append(pixels) rawImages1 = numpy.array(rawImages1) prediction1 = model1.predict(rawImages1) print(prediction1) prediction2 = model2.predict(rawImages1) print(prediction2)
[ "tensorflow.keras.layers.Dense", "sklearn.model_selection.train_test_split", "cv2.imread", "sklearn.neighbors.KNeighborsClassifier", "numpy.array", "tensorflow.keras.models.Sequential", "sklearn.neural_network.MLPClassifier", "sklearn.svm.SVC", "glob.glob", "cv2.resize" ]
[((341, 402), 'glob.glob', 'glob.glob', (['"""D:/SP19/CIS-559_data mining/PROJECT/train1/*.jpg"""'], {}), "('D:/SP19/CIS-559_data mining/PROJECT/train1/*.jpg')\n", (350, 402), False, 'import glob\n'), ((1147, 1172), 'numpy.array', 'numpy.array', (['imagemaxtrix'], {}), '(imagemaxtrix)\n', (1158, 1172), False, 'import numpy\n'), ((1188, 1212), 'numpy.array', 'numpy.array', (['imagelabels'], {}), '(imagelabels)\n', (1199, 1212), False, 'import numpy\n'), ((1305, 1380), 'sklearn.model_selection.train_test_split', 'train_test_split', (['imagemaxtrix', 'imagelabels'], {'test_size': '(0.2)', 'random_state': '(50)'}), '(imagemaxtrix, imagelabels, test_size=0.2, random_state=50)\n', (1321, 1380), False, 'from sklearn.model_selection import train_test_split\n'), ((1424, 1497), 'sklearn.svm.SVC', 'SVC', ([], {'max_iter': '(-1)', 'kernel': '"""linear"""', 'class_weight': '"""balanced"""', 'gamma': '"""scale"""'}), "(max_iter=-1, kernel='linear', class_weight='balanced', gamma='scale')\n", (1427, 1497), False, 'from sklearn.svm import SVC\n'), ((1769, 1815), 'sklearn.neighbors.KNeighborsClassifier', 'KNeighborsClassifier', ([], {'n_neighbors': '(5)', 'n_jobs': '(-1)'}), '(n_neighbors=5, n_jobs=-1)\n', (1789, 1815), False, 'from sklearn.neighbors import KNeighborsClassifier\n'), ((1994, 2133), 'sklearn.neural_network.MLPClassifier', 'MLPClassifier', ([], {'hidden_layer_sizes': '(100,)', 'max_iter': '(1000)', 'alpha': '(0.0001)', 'solver': '"""sgd"""', 'tol': '(0.0001)', 'random_state': '(1)', 'learning_rate_init': '(0.1)'}), "(hidden_layer_sizes=(100,), max_iter=1000, alpha=0.0001,\n solver='sgd', tol=0.0001, random_state=1, learning_rate_init=0.1)\n", (2007, 2133), False, 'from sklearn.neural_network import MLPClassifier\n'), ((2817, 2829), 'tensorflow.keras.models.Sequential', 'Sequential', ([], {}), '()\n', (2827, 2829), False, 'from tensorflow.keras.models import Sequential\n'), ((3763, 3786), 'numpy.array', 'numpy.array', (['rawImages1'], {}), '(rawImages1)\n', (3774, 3786), False, 'import numpy\n'), ((912, 928), 'cv2.imread', 'cv2.imread', (['path'], {}), '(path)\n', (922, 928), False, 'import cv2\n'), ((2912, 2957), 'tensorflow.keras.layers.Dense', 'Dense', (['(50)'], {'activation': '"""relu"""', 'input_dim': '(49152)'}), "(50, activation='relu', input_dim=49152)\n", (2917, 2957), False, 'from tensorflow.keras.layers import Dense\n'), ((2996, 3024), 'tensorflow.keras.layers.Dense', 'Dense', (['(25)'], {'activation': '"""relu"""'}), "(25, activation='relu')\n", (3001, 3024), False, 'from tensorflow.keras.layers import Dense\n'), ((3066, 3096), 'tensorflow.keras.layers.Dense', 'Dense', (['(1)'], {'activation': '"""sigmoid"""'}), "(1, activation='sigmoid')\n", (3071, 3096), False, 'from tensorflow.keras.layers import Dense\n'), ((3689, 3719), 'cv2.imread', 'cv2.imread', (['"""unseen_image.jpg"""'], {}), "('unseen_image.jpg')\n", (3699, 3719), False, 'import cv2\n'), ((487, 548), 'glob.glob', 'glob.glob', (['"""D:/SP19/CIS-559_data mining/PROJECT/train1/*.jpg"""'], {}), "('D:/SP19/CIS-559_data mining/PROJECT/train1/*.jpg')\n", (496, 548), False, 'import glob\n'), ((636, 659), 'cv2.resize', 'cv2.resize', (['image', 'size'], {}), '(image, size)\n', (646, 659), False, 'import cv2\n')]
#!/usr/bin/python3 """ Simple artificial neuron with 2d input - input two numerical values separated by "," - usage: python neuron.py --input 1,0 """ import argparse import numpy as np def sigmoid(x): """Sigmoid activation function: f(x) = 1 / (1 + e^(-x)) """ return 1 / (1 + np.exp(-x)) class Neuron: def __init__(self, weights, bias): self.weights = weights self.bias = bias def feedforward(self, inputs): """ Weight inputs, add bias, then use the activation function """ total = np.dot(self.weights, inputs) + self.bias return sigmoid(total) def main(): ap = argparse.ArgumentParser(description="[Info] neuron with two inputs") ap.add_argument("-i", "--input", required=True, type=str, help="2d input array to neuron") ap.add_argument("-b", "--bias", required=False, type=int, default=2, help="integer bias") args = vars(ap.parse_args()) # parameters x = np.array([float(i) for i in args["input"].split(",")]) w = np.array([0, 1]) b = args["bias"] # instance n = Neuron(w, b) # inference y_hat = n.feedforward(x) print("[INFO] output is {}".format(round(y_hat, 3))) # decision if y_hat > .5: print("[INFO] it is a dog") else: print("[INFO] it is a cat") if __name__ == '__main__': main()
[ "numpy.dot", "numpy.exp", "numpy.array", "argparse.ArgumentParser" ]
[((650, 718), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""[Info] neuron with two inputs"""'}), "(description='[Info] neuron with two inputs')\n", (673, 718), False, 'import argparse\n'), ((1034, 1050), 'numpy.array', 'np.array', (['[0, 1]'], {}), '([0, 1])\n', (1042, 1050), True, 'import numpy as np\n'), ((298, 308), 'numpy.exp', 'np.exp', (['(-x)'], {}), '(-x)\n', (304, 308), True, 'import numpy as np\n'), ((555, 583), 'numpy.dot', 'np.dot', (['self.weights', 'inputs'], {}), '(self.weights, inputs)\n', (561, 583), True, 'import numpy as np\n')]