INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Prints and/ or plots the exposures of the top 10 held positions of all time.
def show_and_plot_top_positions(returns, positions_alloc, show_and_plot=2, hide_positions=False, legend_loc='real_best', ax=None, **kwargs): """ Prints and/or plots the exposures of the top 10 held positions of a...
Plots the max and median of long and short position concentrations over the time.
def plot_max_median_position_concentration(positions, ax=None, **kwargs): """ Plots the max and median of long and short position concentrations over the time. Parameters ---------- positions : pd.DataFrame The positions that the strategy takes over time. ax : matplotlib.Axes, optio...
Plots the sector exposures of the portfolio over time.
def plot_sector_allocations(returns, sector_alloc, ax=None, **kwargs): """ Plots the sector exposures of the portfolio over time. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. sect...
Creates a box plot of daily weekly and monthly return distributions.
def plot_return_quantiles(returns, live_start_date=None, ax=None, **kwargs): """ Creates a box plot of daily, weekly, and monthly return distributions. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create...
Plots turnover vs. date.
def plot_turnover(returns, transactions, positions, legend_loc='best', ax=None, **kwargs): """ Plots turnover vs. date. Turnover is the number of shares traded for a period as a fraction of total shares. Displays daily total, daily average per month, and all-time daily averag...
Plots equity curves at different per - dollar slippage assumptions.
def plot_slippage_sweep(returns, positions, transactions, slippage_params=(3, 8, 10, 12, 15, 20, 50), ax=None, **kwargs): """ Plots equity curves at different per-dollar slippage assumptions. Parameters ---------- returns : pd.Series Timeserie...
Plots curve relating per - dollar slippage to average annual returns.
def plot_slippage_sensitivity(returns, positions, transactions, ax=None, **kwargs): """ Plots curve relating per-dollar slippage to average annual returns. Parameters ---------- returns : pd.Series Timeseries of portfolio returns to be adjusted for various ...
Plots a histogram of daily turnover rates.
def plot_daily_turnover_hist(transactions, positions, ax=None, **kwargs): """ Plots a histogram of daily turnover rates. Parameters ---------- transactions : pd.DataFrame Prices and amounts of executed trades. One row per trade. - See full explanation i...
Plots trading volume per day vs. date.
def plot_daily_volume(returns, transactions, ax=None, **kwargs): """ Plots trading volume per day vs. date. Also displays all-time daily average. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full...
Plots a histogram of transaction times binning the times into buckets of a given duration.
def plot_txn_time_hist(transactions, bin_minutes=5, tz='America/New_York', ax=None, **kwargs): """ Plots a histogram of transaction times, binning the times into buckets of a given duration. Parameters ---------- transactions : pd.DataFrame Prices and amounts of e...
Prints information about the worst drawdown periods.
def show_worst_drawdown_periods(returns, top=5): """ Prints information about the worst drawdown periods. Prints peak dates, valley dates, recovery dates, and net drawdowns. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full ...
Plots monthly returns as a timeseries.
def plot_monthly_returns_timeseries(returns, ax=None, **kwargs): """ Plots monthly returns as a timeseries. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. ax : matplotlib.Axes, opti...
Plots timespans and directions of a sample of round trip trades.
def plot_round_trip_lifetimes(round_trips, disp_amount=16, lsize=18, ax=None): """ Plots timespans and directions of a sample of round trip trades. Parameters ---------- round_trips : pd.DataFrame DataFrame with one row per round trip trade. - See full explanation in round_trips.ext...
Prints the share of total PnL contributed by each traded name.
def show_profit_attribution(round_trips): """ Prints the share of total PnL contributed by each traded name. Parameters ---------- round_trips : pd.DataFrame DataFrame with one row per round trip trade. - See full explanation in round_trips.extract_round_trips ax : matplotli...
Plots a probability distribution for the event of making a profitable trade.
def plot_prob_profit_trade(round_trips, ax=None): """ Plots a probability distribution for the event of making a profitable trade. Parameters ---------- round_trips : pd.DataFrame DataFrame with one row per round trip trade. - See full explanation in round_trips.extract_round_tr...
Plots the upper and lower bounds of an n standard deviation cone of forecasted cumulative returns. Redraws a new cone when cumulative returns fall outside of last cone drawn.
def plot_cones(name, bounds, oos_returns, num_samples=1000, ax=None, cone_std=(1., 1.5, 2.), random_seed=None, num_strikes=3): """ Plots the upper and lower bounds of an n standard deviation cone of forecasted cumulative returns. Redraws a new cone when cumulative returns fall outside of ...
Variance - covariance calculation of daily Value - at - Risk in a portfolio.
def var_cov_var_normal(P, c, mu=0, sigma=1): """ Variance-covariance calculation of daily Value-at-Risk in a portfolio. Parameters ---------- P : float Portfolio value. c : float Confidence level. mu : float, optional Mean. Returns ------- float ...
Determines the Sortino ratio of a strategy.
def sortino_ratio(returns, required_return=0, period=DAILY): """ Determines the Sortino ratio of a strategy. Parameters ---------- returns : pd.Series or pd.DataFrame Daily returns of the strategy, noncumulative. - See full explanation in :func:`~pyfolio.timeseries.cum_returns`. ...
Determines the downside deviation below a threshold
def downside_risk(returns, required_return=0, period=DAILY): """ Determines the downside deviation below a threshold Parameters ---------- returns : pd.Series or pd.DataFrame Daily returns of the strategy, noncumulative. - See full explanation in :func:`~pyfolio.timeseries.cum_retur...
Determines the Sharpe ratio of a strategy.
def sharpe_ratio(returns, risk_free=0, period=DAILY): """ Determines the Sharpe ratio of a strategy. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in :func:`~pyfolio.timeseries.cum_returns`. risk_free : int, float ...
Determines the rolling beta of a strategy.
def rolling_beta(returns, factor_returns, rolling_window=APPROX_BDAYS_PER_MONTH * 6): """ Determines the rolling beta of a strategy. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_...
Computes rolling factor betas using a multivariate linear regression ( separate linear regressions is problematic because the factors may be confounded ).
def rolling_regression(returns, factor_returns, rolling_window=APPROX_BDAYS_PER_MONTH * 6, nan_threshold=0.1): """ Computes rolling factor betas using a multivariate linear regression (separate linear regressions is problematic because the factors may be con...
Calculates the gross leverage of a strategy.
def gross_lev(positions): """ Calculates the gross leverage of a strategy. Parameters ---------- positions : pd.DataFrame Daily net position values. - See full explanation in tears.create_full_tear_sheet. Returns ------- pd.Series Gross leverage. """ e...
Get value at risk ( VaR ).
def value_at_risk(returns, period=None, sigma=2.0): """ Get value at risk (VaR). Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. period : str, optional Period over which to c...
Calculates various performance metrics of a strategy for use in plotting. show_perf_stats.
def perf_stats(returns, factor_returns=None, positions=None, transactions=None, turnover_denom='AGB'): """ Calculates various performance metrics of a strategy, for use in plotting.show_perf_stats. Parameters ---------- returns : pd.Series Daily returns of the strategy, n...
Calculates various bootstrapped performance metrics of a strategy.
def perf_stats_bootstrap(returns, factor_returns=None, return_stats=True, **kwargs): """Calculates various bootstrapped performance metrics of a strategy. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explana...
Performs a bootstrap analysis on a user - defined function returning a summary statistic.
def calc_bootstrap(func, returns, *args, **kwargs): """Performs a bootstrap analysis on a user-defined function returning a summary statistic. Parameters ---------- func : function Function that either takes a single array (commonly returns) or two arrays (commonly returns and facto...
Calculate various summary statistics of data.
def calc_distribution_stats(x): """Calculate various summary statistics of data. Parameters ---------- x : numpy.ndarray or pandas.Series Array to compute summary statistics for. Returns ------- pandas.Series Series containing mean, median, std, as well as 5, 25, 75 and ...
Determines peak valley and recovery dates given an underwater DataFrame.
def get_max_drawdown_underwater(underwater): """ Determines peak, valley, and recovery dates given an 'underwater' DataFrame. An underwater DataFrame is a DataFrame that has precomputed rolling drawdown. Parameters ---------- underwater : pd.Series Underwater returns (rolling dr...
Determines the maximum drawdown of a strategy.
def get_max_drawdown(returns): """ Determines the maximum drawdown of a strategy. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in :func:`~pyfolio.timeseries.cum_returns`. Returns ------- float Max...
Finds top drawdowns sorted by drawdown amount.
def get_top_drawdowns(returns, top=10): """ Finds top drawdowns, sorted by drawdown amount. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. top : int, optional The amount of ...
Places top drawdowns in a table.
def gen_drawdown_table(returns, top=10): """ Places top drawdowns in a table. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. top : int, optional The amount of top drawdowns ...
Determines the rolling volatility of a strategy.
def rolling_volatility(returns, rolling_vol_window): """ Determines the rolling volatility of a strategy. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. rolling_vol_window : int ...
Determines the rolling Sharpe ratio of a strategy.
def rolling_sharpe(returns, rolling_sharpe_window): """ Determines the rolling Sharpe ratio of a strategy. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. rolling_sharpe_window : int...
Gnerate alternate paths using available values from in - sample returns.
def simulate_paths(is_returns, num_days, starting_value=1, num_samples=1000, random_seed=None): """ Gnerate alternate paths using available values from in-sample returns. Parameters ---------- is_returns : pandas.core.frame.DataFrame Non-cumulative in-sample returns. ...
Gnerate the upper and lower bounds of an n standard deviation cone of forecasted cumulative returns.
def summarize_paths(samples, cone_std=(1., 1.5, 2.), starting_value=1.): """ Gnerate the upper and lower bounds of an n standard deviation cone of forecasted cumulative returns. Parameters ---------- samples : numpy.ndarray Alternative paths, or series of possible outcomes. cone_std...
Determines the upper and lower bounds of an n standard deviation cone of forecasted cumulative returns. Future cumulative mean and standard devation are computed by repeatedly sampling from the in - sample daily returns ( i. e. bootstrap ). This cone is non - parametric meaning it does not assume that returns are norma...
def forecast_cone_bootstrap(is_returns, num_days, cone_std=(1., 1.5, 2.), starting_value=1, num_samples=1000, random_seed=None): """ Determines the upper and lower bounds of an n standard deviation cone of forecasted cumulative returns. Future cumulati...
Extracts returns based on interesting events. See gen_date_range_interesting.
def extract_interesting_date_ranges(returns): """ Extracts returns based on interesting events. See gen_date_range_interesting. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. R...
Run Bayesian alpha - beta - model with T distributed returns.
def model_returns_t_alpha_beta(data, bmark, samples=2000, progressbar=True): """ Run Bayesian alpha-beta-model with T distributed returns. This model estimates intercept (alpha) and slope (beta) of two return sets. Usually, these will be algorithm returns and benchmark returns (e.g. S&P500). The da...
Run Bayesian model assuming returns are normally distributed.
def model_returns_normal(data, samples=500, progressbar=True): """ Run Bayesian model assuming returns are normally distributed. Parameters ---------- returns : pandas.Series Series of simple returns of an algorithm or stock. samples : int (optional) Number of posterior samples ...
Bayesian Estimation Supersedes the T - Test
def model_best(y1, y2, samples=1000, progressbar=True): """ Bayesian Estimation Supersedes the T-Test This model runs a Bayesian hypothesis comparing if y1 and y2 come from the same distribution. Returns are assumed to be T-distributed. In addition, computes annual volatility and Sharpe of in and ...
Plot BEST significance analysis.
def plot_best(trace=None, data_train=None, data_test=None, samples=1000, burn=200, axs=None): """ Plot BEST significance analysis. Parameters ---------- trace : pymc3.sampling.BaseTrace, optional trace object as returned by model_best() If not passed, will run model_be...
Run stochastic volatility model.
def model_stoch_vol(data, samples=2000, progressbar=True): """ Run stochastic volatility model. This model estimates the volatility of a returns series over time. Returns are assumed to be T-distributed. lambda (width of T-distributed) is assumed to follow a random-walk. Parameters -------...
Generate plot for stochastic volatility model.
def plot_stoch_vol(data, trace=None, ax=None): """ Generate plot for stochastic volatility model. Parameters ---------- data : pandas.Series Returns to model. trace : pymc3.sampling.BaseTrace object, optional trace as returned by model_stoch_vol If not passed, sample fro...
Compute 5 25 75 and 95 percentiles of cumulative returns used for the Bayesian cone.
def compute_bayes_cone(preds, starting_value=1.): """ Compute 5, 25, 75 and 95 percentiles of cumulative returns, used for the Bayesian cone. Parameters ---------- preds : numpy.array Multiple (simulated) cumulative returns. starting_value : int (optional) Have cumulative re...
Compute Bayesian consistency score.
def compute_consistency_score(returns_test, preds): """ Compute Bayesian consistency score. Parameters ---------- returns_test : pd.Series Observed cumulative returns. preds : numpy.array Multiple (simulated) cumulative returns. Returns ------- Consistency score ...
Run one of the Bayesian models.
def run_model(model, returns_train, returns_test=None, bmark=None, samples=500, ppc=False, progressbar=True): """ Run one of the Bayesian models. Parameters ---------- model : {'alpha_beta', 't', 'normal', 'best'} Which model to run returns_train : pd.Series Timese...
Generate cumulative returns plot with Bayesian cone.
def plot_bayes_cone(returns_train, returns_test, ppc, plot_train_len=50, ax=None): """ Generate cumulative returns plot with Bayesian cone. Parameters ---------- returns_train : pd.Series Timeseries of simple returns returns_test : pd.Series Out-of-sample ret...
Pascal VOC 2007/ 2012 Dataset.
def load_voc_dataset(path='data', dataset='2012', contain_classes_in_person=False): """Pascal VOC 2007/2012 Dataset. It has 20 objects: aeroplane, bicycle, bird, boat, bottle, bus, car, cat, chair, cow, diningtable, dog, horse, motorbike, person, pottedplant, sheep, sofa, train, tvmonitor and additiona...
The core of the model consists of an LSTM cell that processes one word at a time and computes probabilities of the possible continuations of the sentence. The memory state of the network is initialized with a vector of zeros and gets updated after reading each word. Also for computational reasons we will process data i...
def main(_): """ The core of the model consists of an LSTM cell that processes one word at a time and computes probabilities of the possible continuations of the sentence. The memory state of the network is initialized with a vector of zeros and gets updated after reading each word. Also, for comput...
Decorator for making an instance method private.
def private_method(func): """Decorator for making an instance method private.""" def func_wrapper(*args, **kwargs): """Decorator wrapper function.""" outer_frame = inspect.stack()[1][0] if 'self' not in outer_frame.f_locals or outer_frame.f_locals['self'] is not args[0]: rai...
Decorator for making an instance method private.
def protected_method(func): """Decorator for making an instance method private.""" def func_wrapper(*args, **kwargs): """Decorator wrapper function.""" outer_frame = inspect.stack()[1][0] caller = inspect.getmro(outer_frame.f_locals['self'].__class__)[:-1] target = inspect.getm...
Simplified version of: class: AtrousConv1dLayer.
def atrous_conv1d( prev_layer, n_filter=32, filter_size=2, stride=1, dilation=1, act=None, padding='SAME', data_format='NWC', W_init=tf.truncated_normal_initializer(stddev=0.02), b_init=tf.constant_initializer(value=0.0), W_init_arg...
Wrapper for _log_counter_per_token.
def _GetNextLogCountPerToken(token): """Wrapper for _log_counter_per_token. Args: token: The token for which to look up the count. Returns: The number of times this function has been called with *token* as an argument (starting at 0) """ global _log_counter_per_token # pylint: disable...
Log msg % args at level level once per n times.
def log_every_n(level, msg, n, *args): """Log 'msg % args' at level 'level' once per 'n' times. Logs the 1st call, (N+1)st call, (2N+1)st call, etc. Not threadsafe. Args: level: The level at which to log. msg: The message to be logged. n: The number of times this should be called before i...
Log msg % args at level level only if condition is fulfilled.
def log_if(level, msg, condition, *args): """Log 'msg % args' at level 'level' only if condition is fulfilled.""" if condition: vlog(level, msg, *args)
Returns ( filename linenumber ) for the stack frame.
def _GetFileAndLine(): """Returns (filename, linenumber) for the stack frame.""" # Use sys._getframe(). This avoids creating a traceback object. # pylint: disable=protected-access f = _sys._getframe() # pylint: enable=protected-access our_file = f.f_code.co_filename f = f.f_back while f...
Assemble a logline prefix using the google2 format.
def google2_log_prefix(level, timestamp=None, file_and_line=None): """Assemble a logline prefix using the google2 format.""" # pylint: disable=global-variable-not-assigned global _level_names # pylint: enable=global-variable-not-assigned # Record current time now = timestamp or _time.time() ...
Load MPII Human Pose Dataset.
def load_mpii_pose_dataset(path='data', is_16_pos_only=False): """Load MPII Human Pose Dataset. Parameters ----------- path : str The path that the data is downloaded to. is_16_pos_only : boolean If True, only return the peoples contain 16 pose keypoints. (Usually be used for single...
Spatial Transformer Layer for 2D Affine Transformation <https:// en. wikipedia. org/ wiki/ Affine_transformation > __ see: class: SpatialTransformer2dAffineLayer class.
def transformer(U, theta, out_size, name='SpatialTransformer2dAffine'): """Spatial Transformer Layer for `2D Affine Transformation <https://en.wikipedia.org/wiki/Affine_transformation>`__ , see :class:`SpatialTransformer2dAffineLayer` class. Parameters ---------- U : list of float The outpu...
Batch Spatial Transformer function for 2D Affine Transformation <https:// en. wikipedia. org/ wiki/ Affine_transformation > __.
def batch_transformer(U, thetas, out_size, name='BatchSpatialTransformer2dAffine'): """Batch Spatial Transformer function for `2D Affine Transformation <https://en.wikipedia.org/wiki/Affine_transformation>`__. Parameters ---------- U : list of float tensor of inputs [batch, height, width, num_c...
Returns the a: class: TaskSpecDef based on the environment variables for distributed training.
def create_task_spec_def(): """Returns the a :class:`TaskSpecDef` based on the environment variables for distributed training. References ---------- - `ML-engine trainer considerations <https://cloud.google.com/ml-engine/docs/trainer-considerations#use_tf_config>`__ - `TensorPort Distributed Comput...
Creates a distributed session.
def create_distributed_session( task_spec=None, checkpoint_dir=None, scaffold=None, hooks=None, chief_only_hooks=None, save_checkpoint_secs=600, save_summaries_steps=object(), save_summaries_secs=object(), config=None, stop_grace_period_secs=120, log_step_count_steps=100 ): """Creates a dist...
A helper function to compute validation related metrics
def validation_metrics(self): """A helper function to compute validation related metrics""" if (self._validation_iterator is None) or (self._validation_metrics is None): raise AttributeError('Validation is not setup.') n = 0.0 metric_sums = [0.0] * len(self._validation_metr...
A helper function that shows how to train and validate a model at the same time.
def train_and_validate_to_end(self, validate_step_size=50): """A helper function that shows how to train and validate a model at the same time. Parameters ---------- validate_step_size : int Validate the training network every N steps. """ while not self._se...
A generic function to load mnist - like dataset.
def _load_mnist_dataset(shape, path, name='mnist', url='http://yann.lecun.com/exdb/mnist/'): """A generic function to load mnist-like dataset. Parameters: ---------- shape : tuple The shape of digit images. path : str The path that the data is downloaded to. name : str T...
Load CIFAR - 10 dataset.
def load_cifar10_dataset(shape=(-1, 32, 32, 3), path='data', plotable=False): """Load CIFAR-10 dataset. It consists of 60000 32x32 colour images in 10 classes, with 6000 images per class. There are 50000 training images and 10000 test images. The dataset is divided into five training batches and one t...
Load Cropped SVHN.
def load_cropped_svhn(path='data', include_extra=True): """Load Cropped SVHN. The Cropped Street View House Numbers (SVHN) Dataset contains 32x32x3 RGB images. Digit '1' has label 1, '9' has label 9 and '0' has label 0 (the original dataset uses 10 to represent '0'), see `ufldl website <http://ufldl.stanfo...
Load Penn TreeBank ( PTB ) dataset.
def load_ptb_dataset(path='data'): """Load Penn TreeBank (PTB) dataset. It is used in many LANGUAGE MODELING papers, including "Empirical Evaluation and Combination of Advanced Language Modeling Techniques", "Recurrent Neural Network Regularization". It consists of 929k training words, 73k validati...
Load Matt Mahoney s dataset.
def load_matt_mahoney_text8_dataset(path='data'): """Load Matt Mahoney's dataset. Download a text file from Matt Mahoney's website if not present, and make sure it's the right size. Extract the first file enclosed in a zip file as a list of words. This dataset can be used for Word Embedding. P...
Load IMDB dataset.
def load_imdb_dataset( path='data', nb_words=None, skip_top=0, maxlen=None, test_split=0.2, seed=113, start_char=1, oov_char=2, index_from=3 ): """Load IMDB dataset. Parameters ---------- path : str The path that the data is downloaded to, defaults is ``data/imdb/``. nb_word...
Load Nietzsche dataset.
def load_nietzsche_dataset(path='data'): """Load Nietzsche dataset. Parameters ---------- path : str The path that the data is downloaded to, defaults is ``data/nietzsche/``. Returns -------- str The content. Examples -------- >>> see tutorial_generate_text.py ...
Load WMT 15 English - to - French translation dataset.
def load_wmt_en_fr_dataset(path='data'): """Load WMT'15 English-to-French translation dataset. It will download the data from the WMT'15 Website (10^9-French-English corpus), and the 2013 news test from the same site as development set. Returns the directories of training data and test data. Parameter...
Load Flickr25K dataset.
def load_flickr25k_dataset(tag='sky', path="data", n_threads=50, printable=False): """Load Flickr25K dataset. Returns a list of images by a given tag from Flick25k dataset, it will download Flickr25k from `the official website <http://press.liacs.nl/mirflickr/mirdownload.html>`__ at the first time you ...
Load Flick1M dataset.
def load_flickr1M_dataset(tag='sky', size=10, path="data", n_threads=50, printable=False): """Load Flick1M dataset. Returns a list of images by a given tag from Flickr1M dataset, it will download Flickr1M from `the official website <http://press.liacs.nl/mirflickr/mirdownload.html>`__ at the first time...
Load images from CycleGAN s database see this link <https:// people. eecs. berkeley. edu/ ~taesung_park/ CycleGAN/ datasets/ > __.
def load_cyclegan_dataset(filename='summer2winter_yosemite', path='data'): """Load images from CycleGAN's database, see `this link <https://people.eecs.berkeley.edu/~taesung_park/CycleGAN/datasets/>`__. Parameters ------------ filename : str The dataset you want, see `this link <https://people....
Download file from Google Drive.
def download_file_from_google_drive(ID, destination): """Download file from Google Drive. See ``tl.files.load_celebA_dataset`` for example. Parameters -------------- ID : str The driver ID. destination : str The destination for save file. """ def save_response_content...
Load CelebA dataset
def load_celebA_dataset(path='data'): """Load CelebA dataset Return a list of image path. Parameters ----------- path : str The path that the data is downloaded to, defaults is ``data/celebA/``. """ data_dir = 'celebA' filename, drive_id = "img_align_celeba.zip", "0B7EVK8r0v71...
Input parameters and the file name save parameters into. npz file. Use tl. utils. load_npz () to restore.
def save_npz(save_list=None, name='model.npz', sess=None): """Input parameters and the file name, save parameters into .npz file. Use tl.utils.load_npz() to restore. Parameters ---------- save_list : list of tensor A list of parameters (tensor) to be saved. name : str The name of th...
Load the parameters of a Model saved by tl. files. save_npz ().
def load_npz(path='', name='model.npz'): """Load the parameters of a Model saved by tl.files.save_npz(). Parameters ---------- path : str Folder path to `.npz` file. name : str The name of the `.npz` file. Returns -------- list of array A list of parameters in o...
Assign the given parameters to the TensorLayer network.
def assign_params(sess, params, network): """Assign the given parameters to the TensorLayer network. Parameters ---------- sess : Session TensorFlow Session. params : list of array A list of parameters (array) in order. network : :class:`Layer` The network to be assigned...
Load model from npz and assign to a network.
def load_and_assign_npz(sess=None, name=None, network=None): """Load model from npz and assign to a network. Parameters ------------- sess : Session TensorFlow Session. name : str The name of the `.npz` file. network : :class:`Layer` The network to be assigned. Retu...
Input parameters and the file name save parameters as a dictionary into. npz file.
def save_npz_dict(save_list=None, name='model.npz', sess=None): """Input parameters and the file name, save parameters as a dictionary into .npz file. Use ``tl.files.load_and_assign_npz_dict()`` to restore. Parameters ---------- save_list : list of parameters A list of parameters (tensor) ...
Restore the parameters saved by tl. files. save_npz_dict ().
def load_and_assign_npz_dict(name='model.npz', sess=None): """Restore the parameters saved by ``tl.files.save_npz_dict()``. Parameters ---------- name : str The name of the `.npz` file. sess : Session TensorFlow Session. """ if sess is None: raise ValueError("sessio...
Save parameters into ckpt file.
def save_ckpt( sess=None, mode_name='model.ckpt', save_dir='checkpoint', var_list=None, global_step=None, printable=False ): """Save parameters into `ckpt` file. Parameters ------------ sess : Session TensorFlow Session. mode_name : str The name of the model, default is ``mo...
Load parameters from ckpt file.
def load_ckpt(sess=None, mode_name='model.ckpt', save_dir='checkpoint', var_list=None, is_latest=True, printable=False): """Load parameters from `ckpt` file. Parameters ------------ sess : Session TensorFlow Session. mode_name : str The name of the model, default is ``model.ckpt``. ...
Load. npy file.
def load_npy_to_any(path='', name='file.npy'): """Load `.npy` file. Parameters ------------ path : str Path to the file (optional). name : str File name. Examples --------- - see tl.files.save_any_to_npy() """ file_path = os.path.join(path, name) try: ...
r Return a file list in a folder by given a path and regular expression.
def load_file_list(path=None, regx='\.jpg', printable=True, keep_prefix=False): r"""Return a file list in a folder by given a path and regular expression. Parameters ---------- path : str or None A folder path, if `None`, use the current directory. regx : str The regx of file name. ...
Return a folder list in a folder by given a folder path.
def load_folder_list(path=""): """Return a folder list in a folder by given a folder path. Parameters ---------- path : str A folder path. """ return [os.path.join(path, o) for o in os.listdir(path) if os.path.isdir(os.path.join(path, o))]
Check a folder by given name if not exist create the folder and return False if directory exists return True.
def exists_or_mkdir(path, verbose=True): """Check a folder by given name, if not exist, create the folder and return False, if directory exists, return True. Parameters ---------- path : str A folder path. verbose : boolean If True (default), prints results. Returns ---...
Checks if file exists in working_directory otherwise tries to dowload the file and optionally also tries to extract the file if format is. zip or. tar
def maybe_download_and_extract(filename, working_directory, url_source, extract=False, expected_bytes=None): """Checks if file exists in working_directory otherwise tries to dowload the file, and optionally also tries to extract the file if format is ".zip" or ".tar" Parameters ----------- filename...
Sort list of string with number in human order.
def natural_keys(text): """Sort list of string with number in human order. Examples ---------- >>> l = ['im1.jpg', 'im31.jpg', 'im11.jpg', 'im21.jpg', 'im03.jpg', 'im05.jpg'] >>> l.sort(key=tl.files.natural_keys) ['im1.jpg', 'im03.jpg', 'im05', 'im11.jpg', 'im21.jpg', 'im31.jpg'] >>> l.sort...
r Convert the first weight matrix of. npz file to. pdf by using tl. visualize. W ().
def npz_to_W_pdf(path=None, regx='w1pre_[0-9]+\.(npz)'): r"""Convert the first weight matrix of `.npz` file to `.pdf` by using `tl.visualize.W()`. Parameters ---------- path : str A folder path to `npz` files. regx : str Regx for the file name. Examples --------- Conver...
Process a batch of data by given function by threading.
def threading_data(data=None, fn=None, thread_count=None, **kwargs): """Process a batch of data by given function by threading. Usually be used for data augmentation. Parameters ----------- data : numpy.array or others The data to be processed. thread_count : int The number of ...
Create an affine transform matrix for image rotation. NOTE: In OpenCV x is width and y is height.
def affine_rotation_matrix(angle=(-20, 20)): """Create an affine transform matrix for image rotation. NOTE: In OpenCV, x is width and y is height. Parameters ----------- angle : int/float or tuple of two int/float Degree to rotate, usually -180 ~ 180. - int/float, a fixed angle....
Create an affine transformation matrix for image horizontal flipping. NOTE: In OpenCV x is width and y is height.
def affine_horizontal_flip_matrix(prob=0.5): """Create an affine transformation matrix for image horizontal flipping. NOTE: In OpenCV, x is width and y is height. Parameters ---------- prob : float Probability to flip the image. 1.0 means always flip. Returns ------- numpy.arra...
Create an affine transformation for image vertical flipping. NOTE: In OpenCV x is width and y is height.
def affine_vertical_flip_matrix(prob=0.5): """Create an affine transformation for image vertical flipping. NOTE: In OpenCV, x is width and y is height. Parameters ---------- prob : float Probability to flip the image. 1.0 means always flip. Returns ------- numpy.array A...
Create an affine transform matrix for image shifting. NOTE: In OpenCV x is width and y is height.
def affine_shift_matrix(wrg=(-0.1, 0.1), hrg=(-0.1, 0.1), w=200, h=200): """Create an affine transform matrix for image shifting. NOTE: In OpenCV, x is width and y is height. Parameters ----------- wrg : float or tuple of floats Range to shift on width axis, -1 ~ 1. - float, a f...
Create affine transform matrix for image shearing. NOTE: In OpenCV x is width and y is height.
def affine_shear_matrix(x_shear=(-0.1, 0.1), y_shear=(-0.1, 0.1)): """Create affine transform matrix for image shearing. NOTE: In OpenCV, x is width and y is height. Parameters ----------- shear : tuple of two floats Percentage of shears for width and height directions. Returns ---...
Create an affine transform matrix for zooming/ scaling an image s height and width. OpenCV format x is width.
def affine_zoom_matrix(zoom_range=(0.8, 1.1)): """Create an affine transform matrix for zooming/scaling an image's height and width. OpenCV format, x is width. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). zoom_range : float or tuple of...