Search is not available for this dataset
text stringlengths 75 104k |
|---|
def action(self):
"""
This class overrides this method
"""
self.return_value = self.function(*self.args, **self.kwargs) |
def action(self):
"""
This class overrides this method
"""
commandline = "{0} {1}".format(self.command, " ".join(self.arguments))
try:
completed_process = subprocess.run(commandline, shell=True)
self.exit_status = completed_process.returncode
excep... |
def parse_old_menu(menu_data):
"""
Take an old-style menuData dictionary and return a CursesMenu
:param dict menu_data:
:return: A new CursesMenu
:rtype: CursesMenu
"""
menu_title = menu_data['title']
menu = CursesMenu(menu_title)
for item in menu_data["options"]:
item_type ... |
def set_up(self):
"""
This class overrides this method
"""
self.menu.pause()
curses.def_prog_mode()
self.menu.clear_screen() |
def clean_up(self):
"""
This class overrides this method
"""
self.submenu.join()
self.menu.clear_screen()
curses.reset_prog_mode()
curses.curs_set(1) # reset doesn't do this right
curses.curs_set(0)
self.menu.resume() |
def add_aggregation_columns(
df, *,
group_cols: Union[str, List[str]],
aggregations: Dict[str, Agg]
):
"""
Add new columns containing aggregations values on existing columns
---
### Parameters
*mandatory :*
- `group_cols` (*str* or *list*): columns used to aggregate th... |
def top(
df,
value: str,
limit: int,
order: str = 'asc',
group: Union[str, List[str]] = None
):
"""
Get the top or flop N results based on a column value for each specified group columns
---
### Parameters
*mandatory :*
- `value` (*str*): column name on... |
def top_group(
df,
aggregate_by: List[str],
value: str,
limit: int,
order: str = 'asc',
function: str = 'sum',
group: Union[str, List[str]] = None
):
"""
Get the top or flop N results based on a function and a column value that agregates the input.
The... |
def convert_str_to_datetime(df, *, column: str, format: str):
"""
Convert string column into datetime column
---
### Parameters
*mandatory :*
- `column` (*str*): name of the column to format
- `format` (*str*): current format of the values (see [available formats](
https://docs.python... |
def convert_datetime_to_str(df, *, column: str, format: str, new_column: str = None):
"""
Convert datetime column into string column
---
### Parameters
*mandatory :*
- column (*str*): name of the column to format
- format (*str*): format of the result values (see [available formats](
... |
def change_date_format(
df, *,
column: str,
output_format: str,
input_format: str = None,
new_column: str = None,
new_time_zone=None
):
"""
Convert the format of a date
---
### Parameters
*mandatory :*
- `column` (*str*): name of the column to c... |
def cast(df, column: str, type: str, new_column=None):
"""
Convert column's type into type
---
### Parameters
*mandatory :*
- `column` (*str*): name of the column to convert
- `type` (*str*): output type. It can be :
- `"int"` : integer type
- `"float"` : general number ty... |
def compute_evolution_by_frequency(
df,
id_cols: List[str],
date_col: Union[str, Dict[str, str]],
value_col: str,
freq=1,
method: str = 'abs',
format: str = 'column',
offseted_suffix: str = '_offseted',
evolution_col_name: str = 'evolution_computed',
missing_date_as_zero: bool = ... |
def compute_evolution_by_criteria(
df,
id_cols: List[str],
value_col: str,
compare_to: str,
method: str = 'abs',
format: str = 'column',
offseted_suffix: str = '_offseted',
evolution_col_name: str = 'evolution_computed',
raise_duplicate_error: bool = True
):
"""
This function... |
def __compute_evolution(
df,
id_cols,
value_col,
date_col=None,
freq=1,
compare_to=None,
method='abs',
format='column',
offseted_suffix='_offseted',
evolution_col_name='evolution_computed',
how='left',
fillna=None,
raise_duplicate_error=True
):
"""
Compute an ... |
def rank(
df,
value_cols: Union[str, List[str]],
group_cols: List[str] = None,
rank_cols_names: List[str] = None,
method='min',
ascending: bool = True
):
"""
This function creates rank columns based on numeric values to be ranked.
---
### Parameters
... |
def waterfall(
df,
date: str,
value: str,
start: Dict[str, str],
end: Dict[str, str],
upperGroup: Dict[str, str],
insideGroup: Dict[str, str] = None,
filters: List[str] = None
):
"""
Return a line for each bars of a waterfall chart, totals, groups,... |
def _compute_start_end(df, start, end):
"""
Compute two dataframes with value for start and end
Args:
totals(dataframe):
Returns: Dataframe, Dataframe
"""
result = {}
time_dict = {'start': start, 'end': end}
totals = df.groupby('date').agg({'value': sum}).reset_index()
for ... |
def _compute_value_diff(df, start, end, groups):
"""
Compute diff value between start and end
Args:
df(dataframe):
Returns: Dataframe
"""
start_values = df[df['date'] == start['id']].copy()
end_values = df[df['date'] == end['id']].copy()
merge_on = []
for key, group in gro... |
def _compute_inside_group(df):
"""
Compute inside Group
Args:
df(dataframe):
Returns: Dataframe
"""
inside_group = df.copy()
inside_group['type'] = 'child'
inside_group['variation'] = inside_group['value'] / inside_group[
'value_start']
inside_group.drop(['upperGrou... |
def _compute_upper_group(df):
"""
Compute upperGroup
Args:
df (Dataframe):
Returns: Dataframe
"""
upper_group = df.groupby(['groups']).agg({
'value': sum,
'value_start': sum,
'upperGroup_label': 'first',
'upperGroup_order': 'first'
}).reset_index()
... |
def _basic_math_operation(df, new_column, column_1, column_2, op):
"""
Basic mathematical operation to apply operator on `column_1` and `column_2`
Both can be either a number or the name of a column of `df`
Will create a new column named `new_column`
"""
if not isinstance(column_1, (str, int, fl... |
def add(df, new_column, column_1, column_2):
"""
DEPRECATED - use `formula` instead
"""
return _basic_math_operation(df, new_column, column_1, column_2, op='add') |
def subtract(df, new_column, column_1, column_2):
"""
DEPRECATED - use `formula` instead
"""
return _basic_math_operation(df, new_column, column_1, column_2, op='sub') |
def multiply(df, new_column, column_1, column_2):
"""
DEPRECATED - use `formula` instead
"""
return _basic_math_operation(df, new_column, column_1, column_2, op='mul') |
def divide(df, new_column, column_1, column_2):
"""
DEPRECATED - use `formula` instead
"""
return _basic_math_operation(df, new_column, column_1, column_2, op='truediv') |
def formula(df, *, new_column: str, formula: str):
"""
Do mathematic operations on columns (add, subtract, multiply or divide)
---
### Parameters
*mandatory:*
- `new_column` (*str*): name of the output column
- `formula` (*str*): Operation on column. Use name of column and special charact... |
def round_values(df, *, column: str, decimals: int, new_column: str = None):
"""
Round each value of a column
---
### Parameters
*mandatory :*
- `column` (*str*): name of the column to round
- `decimals` (*int*): number of decimal to keeep
*optional :*
- `new_column` (*str*): nam... |
def absolute_values(df, *, column: str, new_column: str = None):
"""
Get the absolute numeric value of each element of a column
---
### Parameters
*mandatory :*
- `column` (*str*): name of the column
*optional :*
- `new_column` (*str*): name of the column containing the result.
... |
def pivot(df, index: List[str], column: str, value: str, agg_function: str = 'mean'):
"""
Pivot the data. Reverse operation of melting
---
### Parameters
*mandatory :*
- `index` (*list*): names of index columns.
- `column` (*str*): column name to pivot on
- `value` (*str*): column nam... |
def pivot_by_group(
df,
variable,
value,
new_columns,
groups,
id_cols=None
):
"""
Pivot a dataframe by group of variables
---
### Parameters
*mandatory :*
* `variable` (*str*): name of the column used to create the groups.
* `value` (*str*):... |
def groupby(df, *, group_cols: Union[str, List[str]],
aggregations: Dict[str, Union[str, List[str]]]):
"""
Aggregate values by groups.
---
### Parameters
*mandatory :*
- `group_cols` (*list*): list of columns used to group data
- `aggregations` (*dict*): dictionnary of values ... |
def cumsum(df, new_column: str, column: str, index: list, date_column: str, date_format: str):
"""
DEPRECATED - please use `compute_cumsum` instead
"""
logging.getLogger(__name__).warning(f"DEPRECATED: use compute_cumsum")
date_temp = '__date_temp__'
if isinstance(index, str):
index = [i... |
def add_missing_row(
df: pd.DataFrame,
id_cols: List[str],
reference_col: str,
complete_index: Union[Dict[str, str], List[str]] = None,
method: str = None,
cols_to_keep: List[str] = None
) -> pd.DataFrame:
"""
Add missing row to a df base on a reference column
---
### Parameter... |
def extract_zip(zip_file_path):
"""
Returns:
dict: Dict[str, DataFrame]
"""
dfs = {}
with zipfile.ZipFile(zip_file_path, mode='r') as z_file:
names = z_file.namelist()
for name in names:
content = z_file.read(name)
_, tmp_file_path = tempfile.mkstemp()... |
def extract(data):
"""
Args:
data (str | byte):
Returns:
dict: Dict[str, DataFrame]
"""
_, tmp_file_path = tempfile.mkstemp()
try:
with open(tmp_file_path, 'wb') as tmp_file:
tmp_file.write(data)
if zipfile.is_zipfile(tmp_file_path):
ret... |
def read_from_cache(self, domains=None):
"""
Returns:
dict: Dict[str, DataFrame]
"""
logger.info(f'Reading data from cache ({self.EXTRACTION_CACHE_PATH})')
if domains is not None and isinstance(domains, list):
dfs = {domain: self.read_entry(domain) for dom... |
def read_entry(self, file_name):
"""
Args:
file_name (str):
Returns:
pd.DataFrame:
"""
file_path = os.path.join(self.EXTRACTION_CACHE_PATH, file_name)
logger.info(f'Reading cache entry: {file_path}')
return joblib.load(file_path) |
def write(self, dfs):
"""
Args:
data (str | byte):
Returns:
dict: Dict[str, DataFrame]
"""
if not os.path.exists(self.EXTRACTION_CACHE_PATH):
os.makedirs(self.EXTRACTION_CACHE_PATH)
for name, df in dfs.items():
file_path =... |
def clean_dataframe(df, is_slugify=True, threshold=50, rename_cols=None):
"""
This method is used to:
- slugify the column names (if slugify is set to True)
- convert columns to 'category' (if len(unique) < threshold) or 'int'
- clean the dataframe and rename if necessary
"""
if is_slugify:
... |
def compute_ffill_by_group(
df,
id_cols: List[str],
reference_cols: List[str],
value_col: str
):
"""
Compute `ffill` with `groupby`
Dedicated method as there is a performance issue with a simple groupby/fillna (2017/07)
The method `ffill` propagates last valid value forwa... |
def fake_data_generator(conf: List[dict]) -> pd.DataFrame:
"""
`conf` is a list of dictionaries like
{'type': 'label', 'values': ['Paris', 'Marseille', 'Lyons'], 'name': 'Cities'}
and each dictionary will add a column.
There are two different behaviours:
- type: 'label' -> the new column will... |
def two_values_melt(
df,
first_value_vars: List[str],
second_value_vars: List[str],
var_name: str,
value_name: str
):
"""
Transforms one or multiple columns into rows.
Unlike melt function, two value columns can be returned by
the function (e.g. an evolution column and a price column... |
def concat(
df,
*,
columns: List[str],
new_column: str,
sep: str = None
):
"""
Concatenate `columns` element-wise
See [pandas doc](
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.cat.html) for more information
---
### Parame... |
def contains(
df,
column: str,
*,
pat: str,
new_column: str = None,
case: bool = True,
na: Any = None,
regex: bool = True
):
"""
Test if pattern or regex is contained within strings of `column`
See [pandas doc](
https://pandas.pydata.org/pa... |
def repeat(
df,
column: str,
*,
times: int,
new_column: str = None
):
"""
Duplicate each string in `column` by indicated number of time
See [pandas doc](
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.repeat.html) for more information... |
def replace_pattern(
df,
column: str,
*,
pat: str,
repl: str,
new_column: str = None,
case: bool = True,
regex: bool = True
):
"""
Replace occurrences of pattern/regex in `column` with some other string
See [pandas doc](
https://pandas.pyda... |
def catch(logger):
"""
Decorator to catch an exception and don't raise it.
Logs information if a decorator failed.
Note:
We don't want possible exceptions during logging to be raised.
This is used to decorate any function that gets executed
before or after the execution of the d... |
def log_message(logger, message=""):
"""
Decorator to log a message before executing a function
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
_log_message(logger, func.__name__, message)
result = func(*args, **kwargs)
return resul... |
def log_time(logger):
"""
Decorator to log the execution time of a function
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
_log_time(logger, func.__na... |
def log_shapes(logger):
"""
Decorator to log the shapes of input and output dataframes
It considers all the dataframes passed either as arguments or keyword arguments as inputs
and all the dataframes returned as outputs.
"""
def decorator(func):
@wraps(func)
def wrapper(*args, *... |
def log(logger=None, start_message='Starting...', end_message='Done...'):
"""
Basic log decorator
Can be used as :
- @log (with default logger)
- @log(mylogger)
- @log(start_message='Hello !", logger=mylogger, end_message='Bye !')
"""
def actual_log(f, real_logger=logger):
logger... |
def domain(domain_name):
"""
Allow to apply a function f(df: DataFrame) -> DataFrame) on dfs by specifying the key
E.g instead of writing:
def process_domain1(dfs):
df = dfs['domain1']
# actual process
dfs['domain1'] = df
return dfs
You can write:... |
def cache( # noqa: C901
requires=None,
disabled=False,
applied_on_method=False,
check_param=True,
limit=None
):
""" Avoid to recompute a function if its parameters and its source code doesnt have changed.
Args:
requires: list of dependencies (functions or function names)
... |
def setup_cachedir(cachedir, mmap_mode=None, bytes_limit=None):
""" This function injects a joblib.Memory object in the cache() function
(in a thread-specific slot of its 'memories' attribute). """
if not hasattr(cache, 'memories'):
cache.memories = {}
memory = joblib.Memory(
locati... |
def melt(
df,
id: List[str],
value: List[str],
dropna=False
):
"""
A melt will transform a dataset by creating a column "variable" and a column "value".
This function is useful to transform a dataset into a format where one or more columns
are identifier variables, while ... |
def rename(
df,
values: Dict[str, Dict[str, str]] = None,
columns: Dict[str, Dict[str, str]] = None,
locale: str = None
):
"""
Replaces data values and column names according to the locale
---
### Parameters
- `values` (optional: dict):
- key: term to be re... |
def compute_cumsum(
df,
id_cols: List[str],
reference_cols: List[str],
value_cols: List[str],
new_value_cols: List[str] = None,
cols_to_keep: List[str] = None
):
"""
Compute cumsum for a group of columns.
---
### Parameters
*mandatory :*
- `id_cols` (*list*): the colum... |
def combine_columns_aggregation(
df,
id_cols: List[str],
cols_for_combination: Dict[str, str],
agg_func: Union[str, List[str], Dict[str, str]] = 'sum'
):
"""
Aggregates data to reproduce "All" category for requester
---
### Parameters
*mandatory :*
- `id_cols` ... |
def get_param_value_from_func_call(param_name, func, call_args, call_kwargs):
"""
Get the value of a function's parameter based on its signature
and the call's args and kwargs.
Example:
>>> def foo(a, b, c=3, d=4):
... pass
...
>>> # what would be the value of "c" whe... |
def get_func_sourcecode(func):
"""
Try to get sourcecode using standard inspect.getsource().
If the function comes from a module which has been created dynamically
(not from the filesystem), then it tries to read the sourcecode on the
filesystem anyway.
WARNING: can do weird things if the filesy... |
def slugify(name, separator='-'):
"""Returns a slugified name (we allow _ to be used)"""
return _slugify(name, regex_pattern=re.compile('[^-_a-z0-9]+'), separator=separator) |
def resolve_dependencies(func_name, dependencies):
""" Given a function name and a mapping of function dependencies,
returns a list of *all* the dependencies for this function. """
def _resolve_deps(func_name, func_deps):
""" Append dependencies recursively to func_deps (accumulator) """
... |
def clean_cachedir_old_entries(cachedir: StoreBackendBase, func_name: str, limit: int) -> int:
"""Remove old entries from the cache"""
if limit < 1:
raise ValueError("'limit' must be greater or equal to 1")
cache_entries = get_cachedir_entries(cachedir, func_name)
cache_entries = sorted(cache_e... |
def roll_up(
df,
levels: List[str],
groupby_vars: List[str],
extra_groupby_cols: List[str] = None,
var_name: str = 'type',
value_name: str = 'value',
agg_func: str = 'sum',
drop_levels: List[str] = None
):
"""
Creates aggregates following a given h... |
def argmax(df, column: str, groups: Union[str, List[str]] = None):
"""
Keep the row of the data corresponding to the maximal value in a column
---
### Parameters
*mandatory :*
- `column` (*str*): name of the column containing the value you want to keep the maximum
*optional :*
- `gro... |
def argmin(df, column: str, groups: Union[str, List[str]] = None):
"""
Keep the row of the data corresponding to the minimal value in a column
---
### Parameters
*mandatory :*
- `column` (str): name of the column containing the value you want to keep the minimum
*optional :*
- `group... |
def fillna(df, column: str, value=None, column_value=None):
"""
Can fill NaN values from a column with a given value or a column
---
### Parameters
- `column` (*str*): name of column you want to fill
- `value`: NaN will be replaced by this value
- `column_value`: NaN will be replaced by ... |
def date_requester_generator(
df: pd.DataFrame,
date_column: str,
frequency: str,
date_column_format: str = None,
format: str = '%Y-%m-%d',
granularities: Dict[str, str] = None,
others_format: Dict[str, str] = None,
times_delta: Dict[str, str] = None
) -> ... |
def _norm_date(datestr: str, date_fmt: str) -> date:
"""normalize symbolic date values (e.g. 'TODAY')
Convert a symbolic value in a valid date.
Currenlty known symbolic values are 'TODAY', 'YESTERDAY' and 'TOMORROW'.
NOTE: This function will return `date` (not `datetime`) instances.
Parameters:
... |
def add_offset(dateobj, hr_offset: str, sign: str):
"""add a human readable offset to `dateobj` and return corresponding date.
rely on `pandas.Timedelta` and add the following extra shortcuts:
- "w", "week" and "weeks" for a week (i.e. 7days)
- "month', "months" for a month (i.e. no day computation, ju... |
def add_months(dateobj, nb_months: int):
"""return `dateobj` + `nb_months`
If landing date doesn't exist (e.g. february, 30th), return the last
day of the landing month.
>>> add_months(date(2018, 1, 1), 1)
datetime.date(2018, 1, 1)
>>> add_months(date(2018, 1, 1), -1)
datetime.date(2017, 1... |
def add_years(dateobj, nb_years):
"""return `dateobj` + `nb_years`
If landing date doesn't exist (e.g. february, 30th), return the last
day of the landing month.
>>> add_years(date(2018, 1, 1), 1)
datetime.date(2019, 1, 1)
>>> add_years(date(2018, 1, 1), -1)
datetime.date(2017, 1, 1)
>... |
def parse_date(datestr: str, date_fmt: str) -> date:
"""parse `datestr` and return corresponding date object.
`datestr` should be a string matching `date_fmt` and parseable by `strptime`
but some offset can also be added using `(datestr) + OFFSET` or `(datestr) -
OFFSET` syntax. When using this syntax,... |
def filter_by_date(
df,
date_col: str,
date_format: str = '%Y-%m-%d',
start: str = None,
stop: str = None,
atdate: str = None
):
"""
Filter dataframe your data by date.
This function will interpret `start`, `stop` and `atdate` and build
the corresponding date range. The caller m... |
def replace(df, column: str, new_column: str = None, **kwargs):
"""
Change the label of a value or a columns within your data source.
(Similar to `rename` but does not have the notion of locale)
---
### Parameters
*mandatory :*
- `column` (*str*): name of the column to modify.
- `to_r... |
def percentage(
df,
column: str,
group_cols: Union[str, List[str]] = None,
new_column: str = None
):
"""
Add a column to the dataframe according to the groupby logic on group_cols
---
### Parameters
*mandatory :*
- `column` (*str*): name of the desired column y... |
def ada_family_core(params, gparams, learning_rate = 0.01, eps= 1e-6, rho=0.95, method="ADADELTA",
beta=0.0, gsum_regularization = 0.0001):
"""
Optimize by SGD, AdaGrad, or AdaDelta.
"""
_, _, _, args = inspect.getargvalues(inspect.currentframe())
logging.info("ada_family_co... |
def optimize_updates(params, gradients, config=None, shapes=None):
"""
General optimization function for Theano.
Parameters:
params - parameters
gradients - gradients
config - training config
Returns:
Theano updates
:type config: deepy.TrainerConfig or dict
"""
... |
def optimize_function(params, config=None):
"""
Create a optimizing function receives gradients.
Parameters:
params - parameters
config - training configuration
Returns:
updating function receives gradients
"""
gs = [dim_to_var(p.ndim) for p in params]
updates, _ = op... |
def _learning_updates(self):
"""
Return updates in the training.
"""
params = self.training_params()
gradients = self.get_gradients(params)
return self.optimization_updates(params, gradients) |
def training_params(self):
"""
Get parameters to be optimized.
"""
params = self.network.parameters
# Freeze parameters
if self.config.fixed_parameters:
logging.info("fixed parameters: %s" % ", ".join(map(str, self.config.fixed_parameters)))
params... |
def optimization_updates(self, params, gradients):
"""
Return updates from optimization.
"""
updates, free_parameters = optimize_updates(params, gradients, self.config)
self.network.free_parameters.extend(free_parameters)
logging.info("Added %d free parameters for optimiz... |
def learning_function(self):
"""
Get the learning function.
:param func:
:return:
"""
network_updates = list(self.network.updates) + list(self.network.training_updates)
learning_updates = list(self._learning_updates())
update_list = network_updates + learn... |
def _glimpse_sensor(self, x_t, l_p):
"""
Parameters:
x_t - 28x28 image
l_p - 2x1 focus vector
Returns:
4x12 matrix
"""
# Turn l_p to the left-top point of rectangle
l_p = l_p * 14 + 14 - 2
l_p = T.cast(T.round(l_p), "int32")
... |
def _refined_glimpse_sensor(self, x_t, l_p):
"""
Parameters:
x_t - 28x28 image
l_p - 2x1 focus vector
Returns:
7*14 matrix
"""
# Turn l_p to the left-top point of rectangle
l_p = l_p * 14 + 14 - 4
l_p = T.cast(T.round(l_p), "int... |
def _glimpse_network(self, x_t, l_p):
"""
Parameters:
x_t - 28x28 image
l_p - 2x1 focus vector
Returns:
4x12 matrix
"""
sensor_output = self._refined_glimpse_sensor(x_t, l_p)
sensor_output = T.flatten(sensor_output)
h_g = self._... |
def _action_network(self, h_t):
"""
Parameters:
h_t - 256x1 vector
Returns:
10x1 vector
"""
z = self._relu(T.dot(h_t, self.W_a) + self.B_a)
return self._softmax(z) |
def get_network(model=None, std=0.005, disable_reinforce=False, random_glimpse=False):
"""
Get baseline model.
Parameters:
model - model path
Returns:
network
"""
network = NeuralClassifier(input_dim=28 * 28)
network.stack_layer(FirstGlimpseLayer(std=std, disable_reinforce=di... |
def _first_glimpse_sensor(self, x_t):
"""
Compute first glimpse position using down-sampled image.
"""
downsampled_img = theano.tensor.signal.downsample.max_pool_2d(x_t, (4,4))
downsampled_img = downsampled_img.flatten()
first_l = T.dot(downsampled_img, self.W_f)
... |
def _core_network(self, l_p, h_p, x_t):
"""
Parameters:
x_t - 28x28 image
l_p - 2x1 focus vector
h_p - 256x1 vector
Returns:
h_t, 256x1 vector
"""
g_t = self._glimpse_network(x_t, l_p)
h_t = self._tanh(T.dot(g_t, self.W_h_g)... |
def prepare(self):
"""
All codes that create parameters should be put into 'setup' function.
"""
self.output_dim = 10
self.encoder = Chain(self.input_dim).stack(Dense(self.internal_layer_size, 'tanh'))
self.decoder = Chain(self.internal_layer_size).stack(Dense(self.input_... |
def compute_tensor(self, x):
"""
Build the computation graph here.
"""
internal_variable = self.encoder.compute_tensor(x)
decoding_output = self.decoder.compute_tensor(internal_variable)
classification_output = self.classifier.compute_tensor(internal_variable)
... |
def map(self, func):
"""
Process all data with given function.
The scheme of function should be x,y -> x,y.
"""
if self._train_set:
self._train_set = map(func, self._train_set)
if self._valid_set:
self._valid_set = map(func, self._valid_set)
... |
def vectorize_target(self, size):
"""
Make targets be one-hot vectors.
"""
if self._train_set:
self._train_set = self._vectorize_set(self._train_set, size)
if self._valid_set:
self._valid_set = self._vectorize_set(self._valid_set, size)
if self._te... |
def report(self):
"""
Print dataset statistics.
"""
logging.info("%s train=%d valid=%d test=%d" % (self.__class__.__name__,
len(list(self._train_set)) if self._train_set else 0,
... |
def train(self, train_set, valid_set=None, test_set=None, train_size=None):
'''We train over mini-batches and evaluate periodically.'''
iteration = 0
while True:
if not iteration % self.config.test_frequency and test_set:
try:
self.test(iteration, ... |
def sample(self, input, steps):
"""
Sample outputs from LM.
"""
inputs = [[onehot(self.input_dim, x) for x in input]]
for _ in range(steps):
target = self.compute(inputs)[0,-1].argmax()
input.append(target)
inputs[0].append(onehot(self.input_di... |
def compute_tensor(self, x):
"""
:param x: (batch, time, vec)
"""
# Target class
class_matrix = self.target_tensor // self.output_size
class_vector = class_matrix.reshape((-1,))
# Target index
target_matrix = self.target_tensor % self.output_size
t... |
def compute_alignments(self, prev_state, precomputed_values, mask=None):
"""
Compute the alignment weights based on the previous state.
"""
WaSp = T.dot(prev_state, self.Wa)
UaH = precomputed_values
# For test time the UaH will be (time, output_dim)
if UaH.ndim =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.