_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q252100
plot_annual_returns
validation
def plot_annual_returns(returns, ax=None, **kwargs): """ Plots a bar graph of returns by year. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. ax : matplotlib.Axes, optional ...
python
{ "resource": "" }
q252101
plot_monthly_returns_dist
validation
def plot_monthly_returns_dist(returns, ax=None, **kwargs): """ Plots a distribution of monthly returns. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. ax : matplotlib.Axes, optional...
python
{ "resource": "" }
q252102
plot_holdings
validation
def plot_holdings(returns, positions, legend_loc='best', ax=None, **kwargs): """ Plots total amount of stocks with an active position, either short or long. Displays daily total, daily average per month, and all-time daily average. Parameters ---------- returns : pd.Series Daily ret...
python
{ "resource": "" }
q252103
plot_long_short_holdings
validation
def plot_long_short_holdings(returns, positions, legend_loc='upper left', ax=None, **kwargs): """ Plots total amount of stocks with an active position, breaking out short and long into transparent filled regions. Parameters ---------- returns : pd.Series Dai...
python
{ "resource": "" }
q252104
plot_drawdown_periods
validation
def plot_drawdown_periods(returns, top=10, ax=None, **kwargs): """ Plots cumulative returns highlighting top drawdown periods. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. top : i...
python
{ "resource": "" }
q252105
plot_drawdown_underwater
validation
def plot_drawdown_underwater(returns, ax=None, **kwargs): """ Plots how far underwaterr returns are over time, or plots current drawdown vs. date. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full...
python
{ "resource": "" }
q252106
plot_perf_stats
validation
def plot_perf_stats(returns, factor_returns, ax=None): """ Create box plot of some performance metrics of the strategy. The width of the box whiskers is determined by a bootstrap. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full...
python
{ "resource": "" }
q252107
show_perf_stats
validation
def show_perf_stats(returns, factor_returns=None, positions=None, transactions=None, turnover_denom='AGB', live_start_date=None, bootstrap=False, header_rows=None): """ Prints some performance metrics of the strategy. - Shows amount of time the st...
python
{ "resource": "" }
q252108
plot_returns
validation
def plot_returns(returns, live_start_date=None, ax=None): """ Plots raw returns over time. Backtest returns are in green, and out-of-sample (live trading) returns are in red. Parameters ---------- returns : pd.Series Daily returns of the strategy, ...
python
{ "resource": "" }
q252109
plot_rolling_returns
validation
def plot_rolling_returns(returns, factor_returns=None, live_start_date=None, logy=False, cone_std=None, legend_loc='best', volatility_match=False, ...
python
{ "resource": "" }
q252110
plot_rolling_beta
validation
def plot_rolling_beta(returns, factor_returns, legend_loc='best', ax=None, **kwargs): """ Plots the rolling 6-month and 12-month beta versus date. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in...
python
{ "resource": "" }
q252111
plot_rolling_volatility
validation
def plot_rolling_volatility(returns, factor_returns=None, rolling_window=APPROX_BDAYS_PER_MONTH * 6, legend_loc='best', ax=None, **kwargs): """ Plots the rolling volatility versus date. Parameters ---------- returns : pd.Series Daily r...
python
{ "resource": "" }
q252112
plot_rolling_sharpe
validation
def plot_rolling_sharpe(returns, factor_returns=None, rolling_window=APPROX_BDAYS_PER_MONTH * 6, legend_loc='best', ax=None, **kwargs): """ Plots the rolling Sharpe ratio versus date. Parameters ---------- returns : pd.Series Daily returns of ...
python
{ "resource": "" }
q252113
plot_gross_leverage
validation
def plot_gross_leverage(returns, positions, ax=None, **kwargs): """ Plots gross leverage versus date. Gross leverage is the sum of long and short exposure per share divided by net asset value. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. ...
python
{ "resource": "" }
q252114
plot_exposures
validation
def plot_exposures(returns, positions, ax=None, **kwargs): """ Plots a cake chart of the long and short exposure. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. positions_alloc : pd...
python
{ "resource": "" }
q252115
plot_max_median_position_concentration
validation
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...
python
{ "resource": "" }
q252116
plot_sector_allocations
validation
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...
python
{ "resource": "" }
q252117
plot_return_quantiles
validation
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...
python
{ "resource": "" }
q252118
plot_turnover
validation
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...
python
{ "resource": "" }
q252119
plot_slippage_sweep
validation
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...
python
{ "resource": "" }
q252120
plot_slippage_sensitivity
validation
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 ...
python
{ "resource": "" }
q252121
plot_daily_turnover_hist
validation
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...
python
{ "resource": "" }
q252122
plot_daily_volume
validation
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...
python
{ "resource": "" }
q252123
plot_txn_time_hist
validation
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...
python
{ "resource": "" }
q252124
show_worst_drawdown_periods
validation
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 ...
python
{ "resource": "" }
q252125
plot_monthly_returns_timeseries
validation
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...
python
{ "resource": "" }
q252126
plot_round_trip_lifetimes
validation
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...
python
{ "resource": "" }
q252127
show_profit_attribution
validation
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...
python
{ "resource": "" }
q252128
plot_prob_profit_trade
validation
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...
python
{ "resource": "" }
q252129
plot_cones
validation
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 ...
python
{ "resource": "" }
q252130
var_cov_var_normal
validation
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
python
{ "resource": "" }
q252131
sortino_ratio
validation
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`.
python
{ "resource": "" }
q252132
downside_risk
validation
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...
python
{ "resource": "" }
q252133
sharpe_ratio
validation
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 ...
python
{ "resource": "" }
q252134
rolling_beta
validation
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_...
python
{ "resource": "" }
q252135
gross_lev
validation
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
python
{ "resource": "" }
q252136
perf_stats
validation
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...
python
{ "resource": "" }
q252137
perf_stats_bootstrap
validation
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...
python
{ "resource": "" }
q252138
calc_bootstrap
validation
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...
python
{ "resource": "" }
q252139
calc_distribution_stats
validation
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 ...
python
{ "resource": "" }
q252140
get_max_drawdown_underwater
validation
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...
python
{ "resource": "" }
q252141
get_max_drawdown
validation
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...
python
{ "resource": "" }
q252142
get_top_drawdowns
validation
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 ...
python
{ "resource": "" }
q252143
gen_drawdown_table
validation
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 ...
python
{ "resource": "" }
q252144
rolling_volatility
validation
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 ...
python
{ "resource": "" }
q252145
rolling_sharpe
validation
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.
python
{ "resource": "" }
q252146
simulate_paths
validation
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. ...
python
{ "resource": "" }
q252147
summarize_paths
validation
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...
python
{ "resource": "" }
q252148
extract_interesting_date_ranges
validation
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...
python
{ "resource": "" }
q252149
model_returns_t_alpha_beta
validation
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...
python
{ "resource": "" }
q252150
model_returns_normal
validation
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 ...
python
{ "resource": "" }
q252151
model_best
validation
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 ...
python
{ "resource": "" }
q252152
model_stoch_vol
validation
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 -------...
python
{ "resource": "" }
q252153
plot_stoch_vol
validation
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...
python
{ "resource": "" }
q252154
compute_bayes_cone
validation
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...
python
{ "resource": "" }
q252155
compute_consistency_score
validation
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 ...
python
{ "resource": "" }
q252156
run_model
validation
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...
python
{ "resource": "" }
q252157
plot_bayes_cone
validation
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...
python
{ "resource": "" }
q252158
_GetNextLogCountPerToken
validation
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)
python
{ "resource": "" }
q252159
log_every_n
validation
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...
python
{ "resource": "" }
q252160
log_if
validation
def log_if(level, msg, condition, *args): """Log 'msg % args' at level 'level' only if
python
{ "resource": "" }
q252161
google2_log_prefix
validation
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() ...
python
{ "resource": "" }
q252162
create_distributed_session
validation
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...
python
{ "resource": "" }
q252163
Trainer.validation_metrics
validation
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...
python
{ "resource": "" }
q252164
Trainer.train_and_validate_to_end
validation
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...
python
{ "resource": "" }
q252165
_load_mnist_dataset
validation
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...
python
{ "resource": "" }
q252166
load_matt_mahoney_text8_dataset
validation
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...
python
{ "resource": "" }
q252167
load_imdb_dataset
validation
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...
python
{ "resource": "" }
q252168
load_nietzsche_dataset
validation
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 ...
python
{ "resource": "" }
q252169
load_wmt_en_fr_dataset
validation
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...
python
{ "resource": "" }
q252170
load_flickr25k_dataset
validation
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 ...
python
{ "resource": "" }
q252171
download_file_from_google_drive
validation
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...
python
{ "resource": "" }
q252172
load_celebA_dataset
validation
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...
python
{ "resource": "" }
q252173
assign_params
validation
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...
python
{ "resource": "" }
q252174
load_and_assign_npz
validation
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...
python
{ "resource": "" }
q252175
save_npz_dict
validation
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) ...
python
{ "resource": "" }
q252176
save_ckpt
validation
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...
python
{ "resource": "" }
q252177
load_ckpt
validation
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``. ...
python
{ "resource": "" }
q252178
load_npy_to_any
validation
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)
python
{ "resource": "" }
q252179
load_file_list
validation
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. ...
python
{ "resource": "" }
q252180
load_folder_list
validation
def load_folder_list(path=""): """Return a folder list in a folder by given a folder path. Parameters
python
{ "resource": "" }
q252181
exists_or_mkdir
validation
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 ---...
python
{ "resource": "" }
q252182
maybe_download_and_extract
validation
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...
python
{ "resource": "" }
q252183
natural_keys
validation
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...
python
{ "resource": "" }
q252184
threading_data
validation
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 ...
python
{ "resource": "" }
q252185
affine_transform_keypoints
validation
def affine_transform_keypoints(coords_list, transform_matrix): """Transform keypoint coordinates according to a given affine transform matrix. OpenCV format, x is width. Note that, for pose estimation task, flipping requires maintaining the left and right body information. We should not flip the left a...
python
{ "resource": "" }
q252186
projective_transform_by_points
validation
def projective_transform_by_points( x, src, dst, map_args=None, output_shape=None, order=1, mode='constant', cval=0.0, clip=True, preserve_range=False ): """Projective transform by given coordinates, usually 4 coordinates. see `scikit-image <http://scikit-image.org/docs/dev/auto_examples/applic...
python
{ "resource": "" }
q252187
rotation
validation
def rotation( x, rg=20, is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0., order=1 ): """Rotate an image randomly or non-randomly. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). rg : int or floa...
python
{ "resource": "" }
q252188
crop
validation
def crop(x, wrg, hrg, is_random=False, row_index=0, col_index=1): """Randomly or centrally crop an image. Parameters ---------- x : numpy.array An image with dimension of [row, col, channel] (default). wrg : int Size of width. hrg : int Size of height. is_random : bo...
python
{ "resource": "" }
q252189
crop_multi
validation
def crop_multi(x, wrg, hrg, is_random=False, row_index=0, col_index=1): """Randomly or centrally crop multiple images. Parameters ---------- x : list of numpy.array List of images with dimension of [n_images, row, col, channel] (default). others : args See ``tl.prepro.crop``. R...
python
{ "resource": "" }
q252190
flip_axis
validation
def flip_axis(x, axis=1, is_random=False): """Flip the axis of an image, such as flip left and right, up and down, randomly or non-randomly, Parameters ---------- x : numpy.array An image with dimension of [row, col, channel] (default). axis : int Which axis to flip. - 0...
python
{ "resource": "" }
q252191
flip_axis_multi
validation
def flip_axis_multi(x, axis, is_random=False): """Flip the axises of multiple images together, such as flip left and right, up and down, randomly or non-randomly, Parameters ----------- x : list of numpy.array List of images with dimension of [n_images, row, col, channel] (default). others ...
python
{ "resource": "" }
q252192
shift
validation
def shift( x, wrg=0.1, hrg=0.1, is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0., order=1 ): """Shift an image randomly or non-randomly. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). w...
python
{ "resource": "" }
q252193
brightness
validation
def brightness(x, gamma=1, gain=1, is_random=False): """Change the brightness of a single image, randomly or non-randomly. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). gamma : float Non negative real number. Default value is 1. ...
python
{ "resource": "" }
q252194
illumination
validation
def illumination(x, gamma=1., contrast=1., saturation=1., is_random=False): """Perform illumination augmentation for a single image, randomly or non-randomly. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). gamma : float Change bright...
python
{ "resource": "" }
q252195
adjust_hue
validation
def adjust_hue(im, hout=0.66, is_offset=True, is_clip=True, is_random=False): """Adjust hue of an RGB image. This is a convenience method that converts an RGB image to float representation, converts it to HSV, add an offset to the hue channel, converts back to RGB and then back to the original data type. F...
python
{ "resource": "" }
q252196
imresize
validation
def imresize(x, size=None, interp='bicubic', mode=None): """Resize an image by given output size and method. Warning, this function will rescale the value to [0, 255]. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). size : list of 2 int ...
python
{ "resource": "" }
q252197
pixel_value_scale
validation
def pixel_value_scale(im, val=0.9, clip=None, is_random=False): """Scales each value in the pixels of the image. Parameters ----------- im : numpy.array An image. val : float The scale value for changing pixel value. - If is_random=False, multiply this value with all pix...
python
{ "resource": "" }
q252198
samplewise_norm
validation
def samplewise_norm( x, rescale=None, samplewise_center=False, samplewise_std_normalization=False, channel_index=2, epsilon=1e-7 ): """Normalize an image by rescale, samplewise centering and samplewise centering in order. Parameters ----------- x : numpy.array An image with dimension of...
python
{ "resource": "" }
q252199
featurewise_norm
validation
def featurewise_norm(x, mean=None, std=None, epsilon=1e-7): """Normalize every pixels by the same given mean and std, which are usually compute from all examples. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). mean : float Value ...
python
{ "resource": "" }