id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
236,300 | ncclient/ncclient | ncclient/operations/edit.py | CopyConfig.request | def request(self, source, target):
"""Create or replace an entire configuration datastore with the contents of another complete
configuration datastore.
*source* is the name of the configuration datastore to use as the source of the copy operation or `config` element containing the configuration subtree to copy
*target* is the name of the configuration datastore to use as the destination of the copy operation
:seealso: :ref:`srctarget_params`"""
node = new_ele("copy-config")
node.append(util.datastore_or_url("target", target, self._assert))
try:
# datastore name or URL
node.append(util.datastore_or_url("source", source, self._assert))
except Exception:
# `source` with `config` element containing the configuration subtree to copy
node.append(validated_element(source, ("source", qualify("source"))))
return self._request(node) | python | def request(self, source, target):
node = new_ele("copy-config")
node.append(util.datastore_or_url("target", target, self._assert))
try:
# datastore name or URL
node.append(util.datastore_or_url("source", source, self._assert))
except Exception:
# `source` with `config` element containing the configuration subtree to copy
node.append(validated_element(source, ("source", qualify("source"))))
return self._request(node) | [
"def",
"request",
"(",
"self",
",",
"source",
",",
"target",
")",
":",
"node",
"=",
"new_ele",
"(",
"\"copy-config\"",
")",
"node",
".",
"append",
"(",
"util",
".",
"datastore_or_url",
"(",
"\"target\"",
",",
"target",
",",
"self",
".",
"_assert",
")",
... | Create or replace an entire configuration datastore with the contents of another complete
configuration datastore.
*source* is the name of the configuration datastore to use as the source of the copy operation or `config` element containing the configuration subtree to copy
*target* is the name of the configuration datastore to use as the destination of the copy operation
:seealso: :ref:`srctarget_params` | [
"Create",
"or",
"replace",
"an",
"entire",
"configuration",
"datastore",
"with",
"the",
"contents",
"of",
"another",
"complete",
"configuration",
"datastore",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/operations/edit.py#L87-L106 |
236,301 | ncclient/ncclient | ncclient/operations/edit.py | Validate.request | def request(self, source="candidate"):
"""Validate the contents of the specified configuration.
*source* is the name of the configuration datastore being validated or `config` element containing the configuration subtree to be validated
:seealso: :ref:`srctarget_params`"""
node = new_ele("validate")
if type(source) is str:
src = util.datastore_or_url("source", source, self._assert)
else:
validated_element(source, ("config", qualify("config")))
src = new_ele("source")
src.append(source)
node.append(src)
return self._request(node) | python | def request(self, source="candidate"):
node = new_ele("validate")
if type(source) is str:
src = util.datastore_or_url("source", source, self._assert)
else:
validated_element(source, ("config", qualify("config")))
src = new_ele("source")
src.append(source)
node.append(src)
return self._request(node) | [
"def",
"request",
"(",
"self",
",",
"source",
"=",
"\"candidate\"",
")",
":",
"node",
"=",
"new_ele",
"(",
"\"validate\"",
")",
"if",
"type",
"(",
"source",
")",
"is",
"str",
":",
"src",
"=",
"util",
".",
"datastore_or_url",
"(",
"\"source\"",
",",
"so... | Validate the contents of the specified configuration.
*source* is the name of the configuration datastore being validated or `config` element containing the configuration subtree to be validated
:seealso: :ref:`srctarget_params` | [
"Validate",
"the",
"contents",
"of",
"the",
"specified",
"configuration",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/operations/edit.py#L114-L128 |
236,302 | ncclient/ncclient | ncclient/operations/lock.py | Lock.request | def request(self, target="candidate"):
"""Allows the client to lock the configuration system of a device.
*target* is the name of the configuration datastore to lock
"""
node = new_ele("lock")
sub_ele(sub_ele(node, "target"), target)
return self._request(node) | python | def request(self, target="candidate"):
node = new_ele("lock")
sub_ele(sub_ele(node, "target"), target)
return self._request(node) | [
"def",
"request",
"(",
"self",
",",
"target",
"=",
"\"candidate\"",
")",
":",
"node",
"=",
"new_ele",
"(",
"\"lock\"",
")",
"sub_ele",
"(",
"sub_ele",
"(",
"node",
",",
"\"target\"",
")",
",",
"target",
")",
"return",
"self",
".",
"_request",
"(",
"nod... | Allows the client to lock the configuration system of a device.
*target* is the name of the configuration datastore to lock | [
"Allows",
"the",
"client",
"to",
"lock",
"the",
"configuration",
"system",
"of",
"a",
"device",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/operations/lock.py#L28-L35 |
236,303 | ncclient/ncclient | ncclient/transport/ssh.py | SSHSession._parse10 | def _parse10(self):
"""Messages are delimited by MSG_DELIM. The buffer could have grown by
a maximum of BUF_SIZE bytes everytime this method is called. Retains
state across method calls and if a chunk has been read it will not be
considered again."""
self.logger.debug("parsing netconf v1.0")
buf = self._buffer
buf.seek(self._parsing_pos10)
if MSG_DELIM in buf.read().decode('UTF-8'):
buf.seek(0)
msg, _, remaining = buf.read().decode('UTF-8').partition(MSG_DELIM)
msg = msg.strip()
if sys.version < '3':
self._dispatch_message(msg.encode())
else:
self._dispatch_message(msg)
# create new buffer which contains remaining of old buffer
self._buffer = StringIO()
self._buffer.write(remaining.encode())
self._parsing_pos10 = 0
if len(remaining) > 0:
# There could be another entire message in the
# buffer, so we should try to parse again.
self.logger.debug('Trying another round of parsing since there is still data')
self._parse10()
else:
# handle case that MSG_DELIM is split over two chunks
self._parsing_pos10 = buf.tell() - MSG_DELIM_LEN
if self._parsing_pos10 < 0:
self._parsing_pos10 = 0 | python | def _parse10(self):
self.logger.debug("parsing netconf v1.0")
buf = self._buffer
buf.seek(self._parsing_pos10)
if MSG_DELIM in buf.read().decode('UTF-8'):
buf.seek(0)
msg, _, remaining = buf.read().decode('UTF-8').partition(MSG_DELIM)
msg = msg.strip()
if sys.version < '3':
self._dispatch_message(msg.encode())
else:
self._dispatch_message(msg)
# create new buffer which contains remaining of old buffer
self._buffer = StringIO()
self._buffer.write(remaining.encode())
self._parsing_pos10 = 0
if len(remaining) > 0:
# There could be another entire message in the
# buffer, so we should try to parse again.
self.logger.debug('Trying another round of parsing since there is still data')
self._parse10()
else:
# handle case that MSG_DELIM is split over two chunks
self._parsing_pos10 = buf.tell() - MSG_DELIM_LEN
if self._parsing_pos10 < 0:
self._parsing_pos10 = 0 | [
"def",
"_parse10",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"parsing netconf v1.0\"",
")",
"buf",
"=",
"self",
".",
"_buffer",
"buf",
".",
"seek",
"(",
"self",
".",
"_parsing_pos10",
")",
"if",
"MSG_DELIM",
"in",
"buf",
".",
"... | Messages are delimited by MSG_DELIM. The buffer could have grown by
a maximum of BUF_SIZE bytes everytime this method is called. Retains
state across method calls and if a chunk has been read it will not be
considered again. | [
"Messages",
"are",
"delimited",
"by",
"MSG_DELIM",
".",
"The",
"buffer",
"could",
"have",
"grown",
"by",
"a",
"maximum",
"of",
"BUF_SIZE",
"bytes",
"everytime",
"this",
"method",
"is",
"called",
".",
"Retains",
"state",
"across",
"method",
"calls",
"and",
"i... | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/transport/ssh.py#L139-L170 |
236,304 | ncclient/ncclient | ncclient/operations/util.py | one_of | def one_of(*args):
"Verifies that only one of the arguments is not None"
for i, arg in enumerate(args):
if arg is not None:
for argh in args[i+1:]:
if argh is not None:
raise OperationError("Too many parameters")
else:
return
raise OperationError("Insufficient parameters") | python | def one_of(*args):
"Verifies that only one of the arguments is not None"
for i, arg in enumerate(args):
if arg is not None:
for argh in args[i+1:]:
if argh is not None:
raise OperationError("Too many parameters")
else:
return
raise OperationError("Insufficient parameters") | [
"def",
"one_of",
"(",
"*",
"args",
")",
":",
"for",
"i",
",",
"arg",
"in",
"enumerate",
"(",
"args",
")",
":",
"if",
"arg",
"is",
"not",
"None",
":",
"for",
"argh",
"in",
"args",
"[",
"i",
"+",
"1",
":",
"]",
":",
"if",
"argh",
"is",
"not",
... | Verifies that only one of the arguments is not None | [
"Verifies",
"that",
"only",
"one",
"of",
"the",
"arguments",
"is",
"not",
"None"
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/operations/util.py#L21-L30 |
236,305 | RJT1990/pyflux | pyflux/arma/arimax.py | ARIMAX._get_scale_and_shape | def _get_scale_and_shape(self, transformed_lvs):
""" Obtains model scale, shape and skewness latent variables
Parameters
----------
transformed_lvs : np.array
Transformed latent variable vector
Returns
----------
- Tuple of model scale, model shape, model skewness
"""
if self.scale is True:
if self.shape is True:
model_shape = transformed_lvs[-1]
model_scale = transformed_lvs[-2]
else:
model_shape = 0
model_scale = transformed_lvs[-1]
else:
model_scale = 0
model_shape = 0
if self.skewness is True:
model_skewness = transformed_lvs[-3]
else:
model_skewness = 0
return model_scale, model_shape, model_skewness | python | def _get_scale_and_shape(self, transformed_lvs):
if self.scale is True:
if self.shape is True:
model_shape = transformed_lvs[-1]
model_scale = transformed_lvs[-2]
else:
model_shape = 0
model_scale = transformed_lvs[-1]
else:
model_scale = 0
model_shape = 0
if self.skewness is True:
model_skewness = transformed_lvs[-3]
else:
model_skewness = 0
return model_scale, model_shape, model_skewness | [
"def",
"_get_scale_and_shape",
"(",
"self",
",",
"transformed_lvs",
")",
":",
"if",
"self",
".",
"scale",
"is",
"True",
":",
"if",
"self",
".",
"shape",
"is",
"True",
":",
"model_shape",
"=",
"transformed_lvs",
"[",
"-",
"1",
"]",
"model_scale",
"=",
"tr... | Obtains model scale, shape and skewness latent variables
Parameters
----------
transformed_lvs : np.array
Transformed latent variable vector
Returns
----------
- Tuple of model scale, model shape, model skewness | [
"Obtains",
"model",
"scale",
"shape",
"and",
"skewness",
"latent",
"variables"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/arma/arimax.py#L152-L181 |
236,306 | RJT1990/pyflux | pyflux/arma/arimax.py | ARIMAX._get_scale_and_shape_sim | def _get_scale_and_shape_sim(self, transformed_lvs):
""" Obtains model scale, shape, skewness latent variables for
a 2d array of simulations.
Parameters
----------
transformed_lvs : np.array
Transformed latent variable vector (2d - with draws of each variable)
Returns
----------
- Tuple of np.arrays (each being scale, shape and skewness draws)
"""
if self.scale is True:
if self.shape is True:
model_shape = self.latent_variables.z_list[-1].prior.transform(transformed_lvs[-1, :])
model_scale = self.latent_variables.z_list[-2].prior.transform(transformed_lvs[-2, :])
else:
model_shape = np.zeros(transformed_lvs.shape[1])
model_scale = self.latent_variables.z_list[-1].prior.transform(transformed_lvs[-1, :])
else:
model_scale = np.zeros(transformed_lvs.shape[1])
model_shape = np.zeros(transformed_lvs.shape[1])
if self.skewness is True:
model_skewness = self.latent_variables.z_list[-3].prior.transform(transformed_lvs[-3, :])
else:
model_skewness = np.zeros(transformed_lvs.shape[1])
return model_scale, model_shape, model_skewness | python | def _get_scale_and_shape_sim(self, transformed_lvs):
if self.scale is True:
if self.shape is True:
model_shape = self.latent_variables.z_list[-1].prior.transform(transformed_lvs[-1, :])
model_scale = self.latent_variables.z_list[-2].prior.transform(transformed_lvs[-2, :])
else:
model_shape = np.zeros(transformed_lvs.shape[1])
model_scale = self.latent_variables.z_list[-1].prior.transform(transformed_lvs[-1, :])
else:
model_scale = np.zeros(transformed_lvs.shape[1])
model_shape = np.zeros(transformed_lvs.shape[1])
if self.skewness is True:
model_skewness = self.latent_variables.z_list[-3].prior.transform(transformed_lvs[-3, :])
else:
model_skewness = np.zeros(transformed_lvs.shape[1])
return model_scale, model_shape, model_skewness | [
"def",
"_get_scale_and_shape_sim",
"(",
"self",
",",
"transformed_lvs",
")",
":",
"if",
"self",
".",
"scale",
"is",
"True",
":",
"if",
"self",
".",
"shape",
"is",
"True",
":",
"model_shape",
"=",
"self",
".",
"latent_variables",
".",
"z_list",
"[",
"-",
... | Obtains model scale, shape, skewness latent variables for
a 2d array of simulations.
Parameters
----------
transformed_lvs : np.array
Transformed latent variable vector (2d - with draws of each variable)
Returns
----------
- Tuple of np.arrays (each being scale, shape and skewness draws) | [
"Obtains",
"model",
"scale",
"shape",
"skewness",
"latent",
"variables",
"for",
"a",
"2d",
"array",
"of",
"simulations",
"."
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/arma/arimax.py#L183-L213 |
236,307 | RJT1990/pyflux | pyflux/arma/arimax.py | ARIMAX._summarize_simulations | def _summarize_simulations(self, mean_values, sim_vector, date_index, h, past_values):
""" Produces forecasted values to plot, along with prediction intervals
This is a utility function that constructs the prediction intervals and other quantities
used for plot_predict() in particular.
Parameters
----------
mean_values : np.ndarray
Mean predictions for h-step ahead forecasts
sim_vector : np.ndarray
N simulation predictions for h-step ahead forecasts
date_index : pd.DateIndex or np.ndarray
Dates for the simulations
h : int
How many steps ahead are forecast
past_values : int
How many past observations to include in the forecast plot
"""
error_bars = []
for pre in range(5,100,5):
error_bars.append(np.insert([np.percentile(i,pre) for i in sim_vector], 0, mean_values[-h-1]))
if self.latent_variables.estimation_method in ['M-H']:
forecasted_values = np.insert([np.mean(i) for i in sim_vector], 0, mean_values[-h-1])
else:
forecasted_values = mean_values[-h-1:]
plot_values = mean_values[-h-past_values:]
plot_index = date_index[-h-past_values:]
return error_bars, forecasted_values, plot_values, plot_index | python | def _summarize_simulations(self, mean_values, sim_vector, date_index, h, past_values):
error_bars = []
for pre in range(5,100,5):
error_bars.append(np.insert([np.percentile(i,pre) for i in sim_vector], 0, mean_values[-h-1]))
if self.latent_variables.estimation_method in ['M-H']:
forecasted_values = np.insert([np.mean(i) for i in sim_vector], 0, mean_values[-h-1])
else:
forecasted_values = mean_values[-h-1:]
plot_values = mean_values[-h-past_values:]
plot_index = date_index[-h-past_values:]
return error_bars, forecasted_values, plot_values, plot_index | [
"def",
"_summarize_simulations",
"(",
"self",
",",
"mean_values",
",",
"sim_vector",
",",
"date_index",
",",
"h",
",",
"past_values",
")",
":",
"error_bars",
"=",
"[",
"]",
"for",
"pre",
"in",
"range",
"(",
"5",
",",
"100",
",",
"5",
")",
":",
"error_b... | Produces forecasted values to plot, along with prediction intervals
This is a utility function that constructs the prediction intervals and other quantities
used for plot_predict() in particular.
Parameters
----------
mean_values : np.ndarray
Mean predictions for h-step ahead forecasts
sim_vector : np.ndarray
N simulation predictions for h-step ahead forecasts
date_index : pd.DateIndex or np.ndarray
Dates for the simulations
h : int
How many steps ahead are forecast
past_values : int
How many past observations to include in the forecast plot | [
"Produces",
"forecasted",
"values",
"to",
"plot",
"along",
"with",
"prediction",
"intervals"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/arma/arimax.py#L606-L639 |
236,308 | RJT1990/pyflux | pyflux/arma/arimax.py | ARIMAX.normal_neg_loglik | def normal_neg_loglik(self, beta):
""" Calculates the negative log-likelihood of the model for Normal family
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for latent variables
Returns
----------
The negative logliklihood of the model
"""
mu, Y = self._model(beta)
return -np.sum(ss.norm.logpdf(Y, loc=mu, scale=self.latent_variables.z_list[-1].prior.transform(beta[-1]))) | python | def normal_neg_loglik(self, beta):
mu, Y = self._model(beta)
return -np.sum(ss.norm.logpdf(Y, loc=mu, scale=self.latent_variables.z_list[-1].prior.transform(beta[-1]))) | [
"def",
"normal_neg_loglik",
"(",
"self",
",",
"beta",
")",
":",
"mu",
",",
"Y",
"=",
"self",
".",
"_model",
"(",
"beta",
")",
"return",
"-",
"np",
".",
"sum",
"(",
"ss",
".",
"norm",
".",
"logpdf",
"(",
"Y",
",",
"loc",
"=",
"mu",
",",
"scale",... | Calculates the negative log-likelihood of the model for Normal family
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for latent variables
Returns
----------
The negative logliklihood of the model | [
"Calculates",
"the",
"negative",
"log",
"-",
"likelihood",
"of",
"the",
"model",
"for",
"Normal",
"family"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/arma/arimax.py#L641-L654 |
236,309 | RJT1990/pyflux | pyflux/arma/arimax.py | ARIMAX.normal_mb_neg_loglik | def normal_mb_neg_loglik(self, beta, mini_batch):
""" Calculates the negative log-likelihood of the Normal model for a minibatch
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for latent variables
mini_batch : int
Size of each mini batch of data
Returns
----------
The negative logliklihood of the model
"""
mu, Y = self._mb_model(beta, mini_batch)
return -np.sum(ss.norm.logpdf(Y, loc=mu, scale=self.latent_variables.z_list[-1].prior.transform(beta[-1]))) | python | def normal_mb_neg_loglik(self, beta, mini_batch):
mu, Y = self._mb_model(beta, mini_batch)
return -np.sum(ss.norm.logpdf(Y, loc=mu, scale=self.latent_variables.z_list[-1].prior.transform(beta[-1]))) | [
"def",
"normal_mb_neg_loglik",
"(",
"self",
",",
"beta",
",",
"mini_batch",
")",
":",
"mu",
",",
"Y",
"=",
"self",
".",
"_mb_model",
"(",
"beta",
",",
"mini_batch",
")",
"return",
"-",
"np",
".",
"sum",
"(",
"ss",
".",
"norm",
".",
"logpdf",
"(",
"... | Calculates the negative log-likelihood of the Normal model for a minibatch
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for latent variables
mini_batch : int
Size of each mini batch of data
Returns
----------
The negative logliklihood of the model | [
"Calculates",
"the",
"negative",
"log",
"-",
"likelihood",
"of",
"the",
"Normal",
"model",
"for",
"a",
"minibatch"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/arma/arimax.py#L656-L673 |
236,310 | RJT1990/pyflux | pyflux/families/skewt.py | Skewt.draw_variable | def draw_variable(loc, scale, shape, skewness, nsims):
""" Draws random variables from Skew t distribution
Parameters
----------
loc : float
location parameter for the distribution
scale : float
scale parameter for the distribution
shape : float
tail thickness parameter for the distribution
skewness : float
skewness parameter for the distribution
nsims : int or list
number of draws to take from the distribution
Returns
----------
- Random draws from the distribution
"""
return loc + scale*Skewt.rvs(shape, skewness, nsims) | python | def draw_variable(loc, scale, shape, skewness, nsims):
return loc + scale*Skewt.rvs(shape, skewness, nsims) | [
"def",
"draw_variable",
"(",
"loc",
",",
"scale",
",",
"shape",
",",
"skewness",
",",
"nsims",
")",
":",
"return",
"loc",
"+",
"scale",
"*",
"Skewt",
".",
"rvs",
"(",
"shape",
",",
"skewness",
",",
"nsims",
")"
] | Draws random variables from Skew t distribution
Parameters
----------
loc : float
location parameter for the distribution
scale : float
scale parameter for the distribution
shape : float
tail thickness parameter for the distribution
skewness : float
skewness parameter for the distribution
nsims : int or list
number of draws to take from the distribution
Returns
----------
- Random draws from the distribution | [
"Draws",
"random",
"variables",
"from",
"Skew",
"t",
"distribution"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/skewt.py#L138-L162 |
236,311 | RJT1990/pyflux | pyflux/families/skewt.py | Skewt.first_order_score | def first_order_score(y, mean, scale, shape, skewness):
""" GAS Skew t Update term using gradient only - native Python function
Parameters
----------
y : float
datapoint for the time series
mean : float
location parameter for the Skew t distribution
scale : float
scale parameter for the Skew t distribution
shape : float
tail thickness parameter for the Skew t distribution
skewness : float
skewness parameter for the Skew t distribution
Returns
----------
- Score of the Skew t family
"""
m1 = (np.sqrt(shape)*sp.gamma((shape-1.0)/2.0))/(np.sqrt(np.pi)*sp.gamma(shape/2.0))
mean = mean + (skewness - (1.0/skewness))*scale*m1
if (y-mean)>=0:
return ((shape+1)/shape)*(y-mean)/(np.power(skewness*scale,2) + (np.power(y-mean,2)/shape))
else:
return ((shape+1)/shape)*(y-mean)/(np.power(scale,2) + (np.power(skewness*(y-mean),2)/shape)) | python | def first_order_score(y, mean, scale, shape, skewness):
m1 = (np.sqrt(shape)*sp.gamma((shape-1.0)/2.0))/(np.sqrt(np.pi)*sp.gamma(shape/2.0))
mean = mean + (skewness - (1.0/skewness))*scale*m1
if (y-mean)>=0:
return ((shape+1)/shape)*(y-mean)/(np.power(skewness*scale,2) + (np.power(y-mean,2)/shape))
else:
return ((shape+1)/shape)*(y-mean)/(np.power(scale,2) + (np.power(skewness*(y-mean),2)/shape)) | [
"def",
"first_order_score",
"(",
"y",
",",
"mean",
",",
"scale",
",",
"shape",
",",
"skewness",
")",
":",
"m1",
"=",
"(",
"np",
".",
"sqrt",
"(",
"shape",
")",
"*",
"sp",
".",
"gamma",
"(",
"(",
"shape",
"-",
"1.0",
")",
"/",
"2.0",
")",
")",
... | GAS Skew t Update term using gradient only - native Python function
Parameters
----------
y : float
datapoint for the time series
mean : float
location parameter for the Skew t distribution
scale : float
scale parameter for the Skew t distribution
shape : float
tail thickness parameter for the Skew t distribution
skewness : float
skewness parameter for the Skew t distribution
Returns
----------
- Score of the Skew t family | [
"GAS",
"Skew",
"t",
"Update",
"term",
"using",
"gradient",
"only",
"-",
"native",
"Python",
"function"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/skewt.py#L165-L194 |
236,312 | RJT1990/pyflux | pyflux/families/skewt.py | Skewt.rvs | def rvs(df, gamma, n):
""" Generates random variables from a Skew t distribution
Parameters
----------
df : float
degrees of freedom parameter
gamma : float
skewness parameter
n : int or list
Number of simulations to perform; if list input, produces array
"""
if type(n) == list:
u = np.random.uniform(size=n[0]*n[1])
result = Skewt.ppf(q=u, df=df, gamma=gamma)
result = np.split(result,n[0])
return np.array(result)
else:
u = np.random.uniform(size=n)
if isinstance(df, np.ndarray) or isinstance(gamma, np.ndarray):
return np.array([Skewt.ppf(q=np.array([u[i]]), df=df[i], gamma=gamma[i])[0] for i in range(n)])
else:
return Skewt.ppf(q=u, df=df, gamma=gamma) | python | def rvs(df, gamma, n):
if type(n) == list:
u = np.random.uniform(size=n[0]*n[1])
result = Skewt.ppf(q=u, df=df, gamma=gamma)
result = np.split(result,n[0])
return np.array(result)
else:
u = np.random.uniform(size=n)
if isinstance(df, np.ndarray) or isinstance(gamma, np.ndarray):
return np.array([Skewt.ppf(q=np.array([u[i]]), df=df[i], gamma=gamma[i])[0] for i in range(n)])
else:
return Skewt.ppf(q=u, df=df, gamma=gamma) | [
"def",
"rvs",
"(",
"df",
",",
"gamma",
",",
"n",
")",
":",
"if",
"type",
"(",
"n",
")",
"==",
"list",
":",
"u",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"size",
"=",
"n",
"[",
"0",
"]",
"*",
"n",
"[",
"1",
"]",
")",
"result",
"=",
... | Generates random variables from a Skew t distribution
Parameters
----------
df : float
degrees of freedom parameter
gamma : float
skewness parameter
n : int or list
Number of simulations to perform; if list input, produces array | [
"Generates",
"random",
"variables",
"from",
"a",
"Skew",
"t",
"distribution"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/skewt.py#L197-L223 |
236,313 | RJT1990/pyflux | pyflux/families/skewt.py | Skewt.logpdf | def logpdf(self, mu):
"""
Log PDF for Skew t prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu))
"""
if self.transform is not None:
mu = self.transform(mu)
return self.logpdf_internal_prior(mu, df=self.df0, loc=self.loc0, scale=self.scale0, gamma=self.gamma0) | python | def logpdf(self, mu):
if self.transform is not None:
mu = self.transform(mu)
return self.logpdf_internal_prior(mu, df=self.df0, loc=self.loc0, scale=self.scale0, gamma=self.gamma0) | [
"def",
"logpdf",
"(",
"self",
",",
"mu",
")",
":",
"if",
"self",
".",
"transform",
"is",
"not",
"None",
":",
"mu",
"=",
"self",
".",
"transform",
"(",
"mu",
")",
"return",
"self",
".",
"logpdf_internal_prior",
"(",
"mu",
",",
"df",
"=",
"self",
"."... | Log PDF for Skew t prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu)) | [
"Log",
"PDF",
"for",
"Skew",
"t",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/skewt.py#L239-L254 |
236,314 | RJT1990/pyflux | pyflux/families/skewt.py | Skewt.markov_blanket | def markov_blanket(y, mean, scale, shape, skewness):
""" Markov blanket for each likelihood term
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Skew t distribution
scale : float
scale parameter for the Skew t distribution
shape : float
tail thickness parameter for the Skew t distribution
skewness : float
skewness parameter for the Skew t distribution
Returns
----------
- Markov blanket of the Skew t family
"""
m1 = (np.sqrt(shape)*sp.gamma((shape-1.0)/2.0))/(np.sqrt(np.pi)*sp.gamma(shape/2.0))
mean = mean + (skewness - (1.0/skewness))*scale*m1
return Skewt.logpdf_internal(x=y, df=shape, loc=mean, gamma=skewness, scale=scale) | python | def markov_blanket(y, mean, scale, shape, skewness):
m1 = (np.sqrt(shape)*sp.gamma((shape-1.0)/2.0))/(np.sqrt(np.pi)*sp.gamma(shape/2.0))
mean = mean + (skewness - (1.0/skewness))*scale*m1
return Skewt.logpdf_internal(x=y, df=shape, loc=mean, gamma=skewness, scale=scale) | [
"def",
"markov_blanket",
"(",
"y",
",",
"mean",
",",
"scale",
",",
"shape",
",",
"skewness",
")",
":",
"m1",
"=",
"(",
"np",
".",
"sqrt",
"(",
"shape",
")",
"*",
"sp",
".",
"gamma",
"(",
"(",
"shape",
"-",
"1.0",
")",
"/",
"2.0",
")",
")",
"/... | Markov blanket for each likelihood term
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Skew t distribution
scale : float
scale parameter for the Skew t distribution
shape : float
tail thickness parameter for the Skew t distribution
skewness : float
skewness parameter for the Skew t distribution
Returns
----------
- Markov blanket of the Skew t family | [
"Markov",
"blanket",
"for",
"each",
"likelihood",
"term"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/skewt.py#L257-L283 |
236,315 | RJT1990/pyflux | pyflux/families/skewt.py | Skewt.pdf_internal | def pdf_internal(x, df, loc=0.0, scale=1.0, gamma = 1.0):
"""
Raw PDF function for the Skew t distribution
"""
result = np.zeros(x.shape[0])
result[x<0] = 2.0/(gamma + 1.0/gamma)*stats.t.pdf(x=gamma*x[(x-loc) < 0], loc=loc[(x-loc) < 0]*gamma,df=df, scale=scale)
result[x>=0] = 2.0/(gamma + 1.0/gamma)*stats.t.pdf(x=x[(x-loc) >= 0]/gamma, loc=loc[(x-loc) >= 0]/gamma,df=df, scale=scale)
return result | python | def pdf_internal(x, df, loc=0.0, scale=1.0, gamma = 1.0):
result = np.zeros(x.shape[0])
result[x<0] = 2.0/(gamma + 1.0/gamma)*stats.t.pdf(x=gamma*x[(x-loc) < 0], loc=loc[(x-loc) < 0]*gamma,df=df, scale=scale)
result[x>=0] = 2.0/(gamma + 1.0/gamma)*stats.t.pdf(x=x[(x-loc) >= 0]/gamma, loc=loc[(x-loc) >= 0]/gamma,df=df, scale=scale)
return result | [
"def",
"pdf_internal",
"(",
"x",
",",
"df",
",",
"loc",
"=",
"0.0",
",",
"scale",
"=",
"1.0",
",",
"gamma",
"=",
"1.0",
")",
":",
"result",
"=",
"np",
".",
"zeros",
"(",
"x",
".",
"shape",
"[",
"0",
"]",
")",
"result",
"[",
"x",
"<",
"0",
"... | Raw PDF function for the Skew t distribution | [
"Raw",
"PDF",
"function",
"for",
"the",
"Skew",
"t",
"distribution"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/skewt.py#L340-L347 |
236,316 | RJT1990/pyflux | pyflux/families/skewt.py | Skewt.pdf | def pdf(self, mu):
"""
PDF for Skew t prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- p(mu)
"""
if self.transform is not None:
mu = self.transform(mu)
return self.pdf_internal(mu, df=self.df0, loc=self.loc0, scale=self.scale0, gamma=self.gamma0) | python | def pdf(self, mu):
if self.transform is not None:
mu = self.transform(mu)
return self.pdf_internal(mu, df=self.df0, loc=self.loc0, scale=self.scale0, gamma=self.gamma0) | [
"def",
"pdf",
"(",
"self",
",",
"mu",
")",
":",
"if",
"self",
".",
"transform",
"is",
"not",
"None",
":",
"mu",
"=",
"self",
".",
"transform",
"(",
"mu",
")",
"return",
"self",
".",
"pdf_internal",
"(",
"mu",
",",
"df",
"=",
"self",
".",
"df0",
... | PDF for Skew t prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- p(mu) | [
"PDF",
"for",
"Skew",
"t",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/skewt.py#L349-L364 |
236,317 | RJT1990/pyflux | pyflux/families/skewt.py | Skewt.cdf | def cdf(x, df, loc=0.0, scale=1.0, gamma = 1.0):
"""
CDF function for Skew t distribution
"""
result = np.zeros(x.shape[0])
result[x<0] = 2.0/(np.power(gamma,2) + 1.0)*ss.t.cdf(gamma*(x[x-loc < 0]-loc[x-loc < 0])/scale, df=df)
result[x>=0] = 1.0/(np.power(gamma,2) + 1.0) + 2.0/((1.0/np.power(gamma,2)) + 1.0)*(ss.t.cdf((x[x-loc >= 0]-loc[x-loc >= 0])/(gamma*scale), df=df)-0.5)
return result | python | def cdf(x, df, loc=0.0, scale=1.0, gamma = 1.0):
result = np.zeros(x.shape[0])
result[x<0] = 2.0/(np.power(gamma,2) + 1.0)*ss.t.cdf(gamma*(x[x-loc < 0]-loc[x-loc < 0])/scale, df=df)
result[x>=0] = 1.0/(np.power(gamma,2) + 1.0) + 2.0/((1.0/np.power(gamma,2)) + 1.0)*(ss.t.cdf((x[x-loc >= 0]-loc[x-loc >= 0])/(gamma*scale), df=df)-0.5)
return result | [
"def",
"cdf",
"(",
"x",
",",
"df",
",",
"loc",
"=",
"0.0",
",",
"scale",
"=",
"1.0",
",",
"gamma",
"=",
"1.0",
")",
":",
"result",
"=",
"np",
".",
"zeros",
"(",
"x",
".",
"shape",
"[",
"0",
"]",
")",
"result",
"[",
"x",
"<",
"0",
"]",
"="... | CDF function for Skew t distribution | [
"CDF",
"function",
"for",
"Skew",
"t",
"distribution"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/skewt.py#L434-L441 |
236,318 | RJT1990/pyflux | pyflux/families/skewt.py | Skewt.ppf | def ppf(q, df, loc=0.0, scale=1.0, gamma = 1.0):
"""
PPF function for Skew t distribution
"""
result = np.zeros(q.shape[0])
probzero = Skewt.cdf(x=np.zeros(1),loc=np.zeros(1),df=df,gamma=gamma)
result[q<probzero] = 1.0/gamma*ss.t.ppf(((np.power(gamma,2) + 1.0) * q[q<probzero])/2.0,df)
result[q>=probzero] = gamma*ss.t.ppf((1.0 + 1.0/np.power(gamma,2))/2.0*(q[q >= probzero] - probzero) + 0.5, df)
return result | python | def ppf(q, df, loc=0.0, scale=1.0, gamma = 1.0):
result = np.zeros(q.shape[0])
probzero = Skewt.cdf(x=np.zeros(1),loc=np.zeros(1),df=df,gamma=gamma)
result[q<probzero] = 1.0/gamma*ss.t.ppf(((np.power(gamma,2) + 1.0) * q[q<probzero])/2.0,df)
result[q>=probzero] = gamma*ss.t.ppf((1.0 + 1.0/np.power(gamma,2))/2.0*(q[q >= probzero] - probzero) + 0.5, df)
return result | [
"def",
"ppf",
"(",
"q",
",",
"df",
",",
"loc",
"=",
"0.0",
",",
"scale",
"=",
"1.0",
",",
"gamma",
"=",
"1.0",
")",
":",
"result",
"=",
"np",
".",
"zeros",
"(",
"q",
".",
"shape",
"[",
"0",
"]",
")",
"probzero",
"=",
"Skewt",
".",
"cdf",
"(... | PPF function for Skew t distribution | [
"PPF",
"function",
"for",
"Skew",
"t",
"distribution"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/skewt.py#L444-L452 |
236,319 | RJT1990/pyflux | pyflux/families/family.py | Family.transform_define | def transform_define(transform):
"""
This function links the user's choice of transformation with the associated numpy function
"""
if transform == 'tanh':
return np.tanh
elif transform == 'exp':
return np.exp
elif transform == 'logit':
return Family.ilogit
elif transform is None:
return np.array
else:
return None | python | def transform_define(transform):
if transform == 'tanh':
return np.tanh
elif transform == 'exp':
return np.exp
elif transform == 'logit':
return Family.ilogit
elif transform is None:
return np.array
else:
return None | [
"def",
"transform_define",
"(",
"transform",
")",
":",
"if",
"transform",
"==",
"'tanh'",
":",
"return",
"np",
".",
"tanh",
"elif",
"transform",
"==",
"'exp'",
":",
"return",
"np",
".",
"exp",
"elif",
"transform",
"==",
"'logit'",
":",
"return",
"Family",
... | This function links the user's choice of transformation with the associated numpy function | [
"This",
"function",
"links",
"the",
"user",
"s",
"choice",
"of",
"transformation",
"with",
"the",
"associated",
"numpy",
"function"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/family.py#L26-L39 |
236,320 | RJT1990/pyflux | pyflux/families/family.py | Family.itransform_define | def itransform_define(transform):
"""
This function links the user's choice of transformation with its inverse
"""
if transform == 'tanh':
return np.arctanh
elif transform == 'exp':
return np.log
elif transform == 'logit':
return Family.logit
elif transform is None:
return np.array
else:
return None | python | def itransform_define(transform):
if transform == 'tanh':
return np.arctanh
elif transform == 'exp':
return np.log
elif transform == 'logit':
return Family.logit
elif transform is None:
return np.array
else:
return None | [
"def",
"itransform_define",
"(",
"transform",
")",
":",
"if",
"transform",
"==",
"'tanh'",
":",
"return",
"np",
".",
"arctanh",
"elif",
"transform",
"==",
"'exp'",
":",
"return",
"np",
".",
"log",
"elif",
"transform",
"==",
"'logit'",
":",
"return",
"Famil... | This function links the user's choice of transformation with its inverse | [
"This",
"function",
"links",
"the",
"user",
"s",
"choice",
"of",
"transformation",
"with",
"its",
"inverse"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/family.py#L42-L55 |
236,321 | RJT1990/pyflux | pyflux/gpnarx/gpnarx.py | GPNARX._L | def _L(self, parm):
""" Creates cholesky decomposition of covariance matrix
Parameters
----------
parm : np.array
Contains transformed latent variables
Returns
----------
The cholesky decomposition (L) of K
"""
return np.linalg.cholesky(self.kernel.K(parm) + np.identity(self.X().shape[1])*parm[0]) | python | def _L(self, parm):
return np.linalg.cholesky(self.kernel.K(parm) + np.identity(self.X().shape[1])*parm[0]) | [
"def",
"_L",
"(",
"self",
",",
"parm",
")",
":",
"return",
"np",
".",
"linalg",
".",
"cholesky",
"(",
"self",
".",
"kernel",
".",
"K",
"(",
"parm",
")",
"+",
"np",
".",
"identity",
"(",
"self",
".",
"X",
"(",
")",
".",
"shape",
"[",
"1",
"]",... | Creates cholesky decomposition of covariance matrix
Parameters
----------
parm : np.array
Contains transformed latent variables
Returns
----------
The cholesky decomposition (L) of K | [
"Creates",
"cholesky",
"decomposition",
"of",
"covariance",
"matrix"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/gpnarx/gpnarx.py#L176-L189 |
236,322 | RJT1990/pyflux | pyflux/gpnarx/gpnarx.py | GPNARX.plot_fit | def plot_fit(self, intervals=True, **kwargs):
""" Plots the fit of the Gaussian process model to the data
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
intervals : Boolean
Whether to plot uncertainty intervals or not
Returns
----------
None (plots the fit of the function)
"""
import matplotlib.pyplot as plt
import seaborn as sns
figsize = kwargs.get('figsize',(10,7))
date_index = self.index[self.max_lag:]
expectation = self.expected_values(self.latent_variables.get_z_values())
variance = self.variance_values(self.latent_variables.get_z_values())
upper = expectation + 1.98*np.power(np.diag(variance),0.5)
lower = expectation - 1.98*np.power(np.diag(variance),0.5)
plt.figure(figsize=figsize)
plt.subplot(2, 2, 1)
plt.title(self.data_name + " Raw")
plt.plot(date_index,self.data*self._norm_std + self._norm_mean,'k')
plt.subplot(2, 2, 2)
plt.title(self.data_name + " Raw and Expected")
plt.plot(date_index,self.data*self._norm_std + self._norm_mean,'k',alpha=0.2)
plt.plot(date_index,self.expected_values(self.latent_variables.get_z_values())*self._norm_std + self._norm_mean,'b')
plt.subplot(2, 2, 3)
plt.title(self.data_name + " Raw and Expected (with intervals)")
if intervals == True:
plt.fill_between(date_index, lower*self._norm_std + self._norm_mean, upper*self._norm_std + self._norm_mean, alpha=0.2)
plt.plot(date_index,self.data*self._norm_std + self._norm_mean,'k',alpha=0.2)
plt.plot(date_index,self.expected_values(self.latent_variables.get_z_values())*self._norm_std + self._norm_mean,'b')
plt.subplot(2, 2, 4)
plt.title("Expected " + self.data_name + " (with intervals)")
if intervals == True:
plt.fill_between(date_index, lower*self._norm_std + self._norm_mean, upper*self._norm_std + self._norm_mean, alpha=0.2)
plt.plot(date_index,self.expected_values(self.latent_variables.get_z_values())*self._norm_std + self._norm_mean,'b')
plt.show() | python | def plot_fit(self, intervals=True, **kwargs):
import matplotlib.pyplot as plt
import seaborn as sns
figsize = kwargs.get('figsize',(10,7))
date_index = self.index[self.max_lag:]
expectation = self.expected_values(self.latent_variables.get_z_values())
variance = self.variance_values(self.latent_variables.get_z_values())
upper = expectation + 1.98*np.power(np.diag(variance),0.5)
lower = expectation - 1.98*np.power(np.diag(variance),0.5)
plt.figure(figsize=figsize)
plt.subplot(2, 2, 1)
plt.title(self.data_name + " Raw")
plt.plot(date_index,self.data*self._norm_std + self._norm_mean,'k')
plt.subplot(2, 2, 2)
plt.title(self.data_name + " Raw and Expected")
plt.plot(date_index,self.data*self._norm_std + self._norm_mean,'k',alpha=0.2)
plt.plot(date_index,self.expected_values(self.latent_variables.get_z_values())*self._norm_std + self._norm_mean,'b')
plt.subplot(2, 2, 3)
plt.title(self.data_name + " Raw and Expected (with intervals)")
if intervals == True:
plt.fill_between(date_index, lower*self._norm_std + self._norm_mean, upper*self._norm_std + self._norm_mean, alpha=0.2)
plt.plot(date_index,self.data*self._norm_std + self._norm_mean,'k',alpha=0.2)
plt.plot(date_index,self.expected_values(self.latent_variables.get_z_values())*self._norm_std + self._norm_mean,'b')
plt.subplot(2, 2, 4)
plt.title("Expected " + self.data_name + " (with intervals)")
if intervals == True:
plt.fill_between(date_index, lower*self._norm_std + self._norm_mean, upper*self._norm_std + self._norm_mean, alpha=0.2)
plt.plot(date_index,self.expected_values(self.latent_variables.get_z_values())*self._norm_std + self._norm_mean,'b')
plt.show() | [
"def",
"plot_fit",
"(",
"self",
",",
"intervals",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"import",
"seaborn",
"as",
"sns",
"figsize",
"=",
"kwargs",
".",
"get",
"(",
"'figsize'",
",",
"(",
... | Plots the fit of the Gaussian process model to the data
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
intervals : Boolean
Whether to plot uncertainty intervals or not
Returns
----------
None (plots the fit of the function) | [
"Plots",
"the",
"fit",
"of",
"the",
"Gaussian",
"process",
"model",
"to",
"the",
"data"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/gpnarx/gpnarx.py#L260-L315 |
236,323 | RJT1990/pyflux | pyflux/gas/gas.py | GAS._get_scale_and_shape | def _get_scale_and_shape(self,parm):
""" Obtains appropriate model scale and shape latent variables
Parameters
----------
parm : np.array
Transformed latent variable vector
Returns
----------
None (changes model attributes)
"""
if self.scale is True:
if self.shape is True:
model_shape = parm[-1]
model_scale = parm[-2]
else:
model_shape = 0
model_scale = parm[-1]
else:
model_scale = 0
model_shape = 0
if self.skewness is True:
model_skewness = parm[-3]
else:
model_skewness = 0
return model_scale, model_shape, model_skewness | python | def _get_scale_and_shape(self,parm):
if self.scale is True:
if self.shape is True:
model_shape = parm[-1]
model_scale = parm[-2]
else:
model_shape = 0
model_scale = parm[-1]
else:
model_scale = 0
model_shape = 0
if self.skewness is True:
model_skewness = parm[-3]
else:
model_skewness = 0
return model_scale, model_shape, model_skewness | [
"def",
"_get_scale_and_shape",
"(",
"self",
",",
"parm",
")",
":",
"if",
"self",
".",
"scale",
"is",
"True",
":",
"if",
"self",
".",
"shape",
"is",
"True",
":",
"model_shape",
"=",
"parm",
"[",
"-",
"1",
"]",
"model_scale",
"=",
"parm",
"[",
"-",
"... | Obtains appropriate model scale and shape latent variables
Parameters
----------
parm : np.array
Transformed latent variable vector
Returns
----------
None (changes model attributes) | [
"Obtains",
"appropriate",
"model",
"scale",
"and",
"shape",
"latent",
"variables"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/gas/gas.py#L127-L156 |
236,324 | RJT1990/pyflux | pyflux/gas/gas.py | GAS.plot_sample | def plot_sample(self, nsims=10, plot_data=True, **kwargs):
"""
Plots draws from the posterior predictive density against the data
Parameters
----------
nsims : int (default : 1000)
How many draws from the posterior predictive distribution
plot_data boolean
Whether to plot the data or not
"""
if self.latent_variables.estimation_method not in ['BBVI', 'M-H']:
raise Exception("No latent variables estimated!")
else:
import matplotlib.pyplot as plt
import seaborn as sns
figsize = kwargs.get('figsize',(10,7))
plt.figure(figsize=figsize)
date_index = self.index[max(self.ar, self.sc):self.data_length]
mu, Y, scores = self._model(self.latent_variables.get_z_values())
draws = self.sample(nsims).T
plt.plot(date_index, draws, label='Posterior Draws', alpha=1.0)
if plot_data is True:
plt.plot(date_index, Y, label='Data', c='black', alpha=0.5, linestyle='', marker='s')
plt.title(self.data_name)
plt.show() | python | def plot_sample(self, nsims=10, plot_data=True, **kwargs):
if self.latent_variables.estimation_method not in ['BBVI', 'M-H']:
raise Exception("No latent variables estimated!")
else:
import matplotlib.pyplot as plt
import seaborn as sns
figsize = kwargs.get('figsize',(10,7))
plt.figure(figsize=figsize)
date_index = self.index[max(self.ar, self.sc):self.data_length]
mu, Y, scores = self._model(self.latent_variables.get_z_values())
draws = self.sample(nsims).T
plt.plot(date_index, draws, label='Posterior Draws', alpha=1.0)
if plot_data is True:
plt.plot(date_index, Y, label='Data', c='black', alpha=0.5, linestyle='', marker='s')
plt.title(self.data_name)
plt.show() | [
"def",
"plot_sample",
"(",
"self",
",",
"nsims",
"=",
"10",
",",
"plot_data",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"latent_variables",
".",
"estimation_method",
"not",
"in",
"[",
"'BBVI'",
",",
"'M-H'",
"]",
":",
"raise",
... | Plots draws from the posterior predictive density against the data
Parameters
----------
nsims : int (default : 1000)
How many draws from the posterior predictive distribution
plot_data boolean
Whether to plot the data or not | [
"Plots",
"draws",
"from",
"the",
"posterior",
"predictive",
"density",
"against",
"the",
"data"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/gas/gas.py#L939-L967 |
236,325 | RJT1990/pyflux | pyflux/arma/arma.py | ARIMA._ar_matrix | def _ar_matrix(self):
""" Creates the Autoregressive matrix for the model
Returns
----------
X : np.ndarray
Autoregressive Matrix
"""
X = np.ones(self.data_length-self.max_lag)
if self.ar != 0:
for i in range(0, self.ar):
X = np.vstack((X,self.data[(self.max_lag-i-1):-i-1]))
return X | python | def _ar_matrix(self):
X = np.ones(self.data_length-self.max_lag)
if self.ar != 0:
for i in range(0, self.ar):
X = np.vstack((X,self.data[(self.max_lag-i-1):-i-1]))
return X | [
"def",
"_ar_matrix",
"(",
"self",
")",
":",
"X",
"=",
"np",
".",
"ones",
"(",
"self",
".",
"data_length",
"-",
"self",
".",
"max_lag",
")",
"if",
"self",
".",
"ar",
"!=",
"0",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"self",
".",
"ar",
... | Creates the Autoregressive matrix for the model
Returns
----------
X : np.ndarray
Autoregressive Matrix | [
"Creates",
"the",
"Autoregressive",
"matrix",
"for",
"the",
"model"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/arma/arma.py#L109-L124 |
236,326 | RJT1990/pyflux | pyflux/families/inverse_wishart.py | InverseWishart.logpdf | def logpdf(self, X):
"""
Log PDF for Inverse Wishart prior
Parameters
----------
X : float
Covariance matrix for which the prior is being formed over
Returns
----------
- log(p(X))
"""
return invwishart.logpdf(X, df=self.v, scale=self.Psi) | python | def logpdf(self, X):
return invwishart.logpdf(X, df=self.v, scale=self.Psi) | [
"def",
"logpdf",
"(",
"self",
",",
"X",
")",
":",
"return",
"invwishart",
".",
"logpdf",
"(",
"X",
",",
"df",
"=",
"self",
".",
"v",
",",
"scale",
"=",
"self",
".",
"Psi",
")"
] | Log PDF for Inverse Wishart prior
Parameters
----------
X : float
Covariance matrix for which the prior is being formed over
Returns
----------
- log(p(X)) | [
"Log",
"PDF",
"for",
"Inverse",
"Wishart",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/inverse_wishart.py#L38-L51 |
236,327 | RJT1990/pyflux | pyflux/families/inverse_wishart.py | InverseWishart.pdf | def pdf(self, X):
"""
PDF for Inverse Wishart prior
Parameters
----------
x : float
Covariance matrix for which the prior is being formed over
Returns
----------
- p(x)
"""
return invwishart.pdf(X, df=self.v, scale=self.Psi) | python | def pdf(self, X):
return invwishart.pdf(X, df=self.v, scale=self.Psi) | [
"def",
"pdf",
"(",
"self",
",",
"X",
")",
":",
"return",
"invwishart",
".",
"pdf",
"(",
"X",
",",
"df",
"=",
"self",
".",
"v",
",",
"scale",
"=",
"self",
".",
"Psi",
")"
] | PDF for Inverse Wishart prior
Parameters
----------
x : float
Covariance matrix for which the prior is being formed over
Returns
----------
- p(x) | [
"PDF",
"for",
"Inverse",
"Wishart",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/inverse_wishart.py#L53-L66 |
236,328 | RJT1990/pyflux | pyflux/ssm/nllt.py | NLLT.neg_loglik | def neg_loglik(self, beta):
""" Creates negative loglikelihood of the model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
- Negative loglikelihood
"""
Z = np.zeros(2)
Z[0] = 1
states = np.zeros([self.state_no, self.data.shape[0]])
states[0,:] = beta[self.z_no:self.z_no+self.data.shape[0]]
states[1,:] = beta[self.z_no+self.data.shape[0]:]
parm = np.array([self.latent_variables.z_list[k].prior.transform(beta[k]) for k in range(self.z_no)]) # transformed distribution parameters
scale, shape, skewness = self._get_scale_and_shape(parm)
return self.state_likelihood(beta, states) + self.family.neg_loglikelihood(self.data, self.link(np.dot(Z, states)), scale, shape, skewness) | python | def neg_loglik(self, beta):
Z = np.zeros(2)
Z[0] = 1
states = np.zeros([self.state_no, self.data.shape[0]])
states[0,:] = beta[self.z_no:self.z_no+self.data.shape[0]]
states[1,:] = beta[self.z_no+self.data.shape[0]:]
parm = np.array([self.latent_variables.z_list[k].prior.transform(beta[k]) for k in range(self.z_no)]) # transformed distribution parameters
scale, shape, skewness = self._get_scale_and_shape(parm)
return self.state_likelihood(beta, states) + self.family.neg_loglikelihood(self.data, self.link(np.dot(Z, states)), scale, shape, skewness) | [
"def",
"neg_loglik",
"(",
"self",
",",
"beta",
")",
":",
"Z",
"=",
"np",
".",
"zeros",
"(",
"2",
")",
"Z",
"[",
"0",
"]",
"=",
"1",
"states",
"=",
"np",
".",
"zeros",
"(",
"[",
"self",
".",
"state_no",
",",
"self",
".",
"data",
".",
"shape",
... | Creates negative loglikelihood of the model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
- Negative loglikelihood | [
"Creates",
"negative",
"loglikelihood",
"of",
"the",
"model"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/nllt.py#L117-L136 |
236,329 | RJT1990/pyflux | pyflux/ssm/nllt.py | NLLT.state_likelihood_markov_blanket | def state_likelihood_markov_blanket(self, beta, alpha, col_no):
""" Returns Markov blanket of the states given the variance latent variables
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
alpha : np.array
State matrix
Returns
----------
State likelihood
"""
_, _, _, Q = self._ss_matrices(beta)
blanket = np.append(0,ss.norm.logpdf(alpha[col_no][1:]-alpha[col_no][:-1],loc=0,scale=np.sqrt(Q[col_no][col_no])))
blanket[:-1] = blanket[:-1] + blanket[1:]
return blanket | python | def state_likelihood_markov_blanket(self, beta, alpha, col_no):
_, _, _, Q = self._ss_matrices(beta)
blanket = np.append(0,ss.norm.logpdf(alpha[col_no][1:]-alpha[col_no][:-1],loc=0,scale=np.sqrt(Q[col_no][col_no])))
blanket[:-1] = blanket[:-1] + blanket[1:]
return blanket | [
"def",
"state_likelihood_markov_blanket",
"(",
"self",
",",
"beta",
",",
"alpha",
",",
"col_no",
")",
":",
"_",
",",
"_",
",",
"_",
",",
"Q",
"=",
"self",
".",
"_ss_matrices",
"(",
"beta",
")",
"blanket",
"=",
"np",
".",
"append",
"(",
"0",
",",
"s... | Returns Markov blanket of the states given the variance latent variables
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
alpha : np.array
State matrix
Returns
----------
State likelihood | [
"Returns",
"Markov",
"blanket",
"of",
"the",
"states",
"given",
"the",
"variance",
"latent",
"variables"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/nllt.py#L181-L199 |
236,330 | RJT1990/pyflux | pyflux/ssm/nllt.py | NLLT.markov_blanket | def markov_blanket(self, beta, alpha):
""" Creates total Markov blanket for states
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
alpha : np.array
A vector of states
Returns
----------
Markov blanket for states
"""
likelihood_blanket = self.likelihood_markov_blanket(beta)
state_blanket = self.state_likelihood_markov_blanket(beta,alpha,0)
for i in range(self.state_no-1):
likelihood_blanket = np.append(likelihood_blanket,self.likelihood_markov_blanket(beta))
state_blanket = np.append(state_blanket,self.state_likelihood_markov_blanket(beta,alpha,i+1))
return likelihood_blanket + state_blanket | python | def markov_blanket(self, beta, alpha):
likelihood_blanket = self.likelihood_markov_blanket(beta)
state_blanket = self.state_likelihood_markov_blanket(beta,alpha,0)
for i in range(self.state_no-1):
likelihood_blanket = np.append(likelihood_blanket,self.likelihood_markov_blanket(beta))
state_blanket = np.append(state_blanket,self.state_likelihood_markov_blanket(beta,alpha,i+1))
return likelihood_blanket + state_blanket | [
"def",
"markov_blanket",
"(",
"self",
",",
"beta",
",",
"alpha",
")",
":",
"likelihood_blanket",
"=",
"self",
".",
"likelihood_markov_blanket",
"(",
"beta",
")",
"state_blanket",
"=",
"self",
".",
"state_likelihood_markov_blanket",
"(",
"beta",
",",
"alpha",
","... | Creates total Markov blanket for states
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
alpha : np.array
A vector of states
Returns
----------
Markov blanket for states | [
"Creates",
"total",
"Markov",
"blanket",
"for",
"states"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/nllt.py#L221-L241 |
236,331 | RJT1990/pyflux | pyflux/ssm/nllt.py | NLLT._general_approximating_model | def _general_approximating_model(self, beta, T, Z, R, Q, h_approx):
""" Creates simplest kind of approximating Gaussian model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
T, Z, R, Q : np.array
State space matrices used in KFS algorithm
h_approx : float
Value to use for the H matrix
Returns
----------
H : np.array
Approximating measurement variance matrix
mu : np.array
Approximating measurement constants
"""
H = np.ones(self.data_length)*h_approx
mu = np.zeros(self.data_length)
return H, mu | python | def _general_approximating_model(self, beta, T, Z, R, Q, h_approx):
H = np.ones(self.data_length)*h_approx
mu = np.zeros(self.data_length)
return H, mu | [
"def",
"_general_approximating_model",
"(",
"self",
",",
"beta",
",",
"T",
",",
"Z",
",",
"R",
",",
"Q",
",",
"h_approx",
")",
":",
"H",
"=",
"np",
".",
"ones",
"(",
"self",
".",
"data_length",
")",
"*",
"h_approx",
"mu",
"=",
"np",
".",
"zeros",
... | Creates simplest kind of approximating Gaussian model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
T, Z, R, Q : np.array
State space matrices used in KFS algorithm
h_approx : float
Value to use for the H matrix
Returns
----------
H : np.array
Approximating measurement variance matrix
mu : np.array
Approximating measurement constants | [
"Creates",
"simplest",
"kind",
"of",
"approximating",
"Gaussian",
"model"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/nllt.py#L403-L430 |
236,332 | RJT1990/pyflux | pyflux/ssm/nllt.py | NLLT.fit | def fit(self, optimizer='RMSProp', iterations=1000, print_progress=True, start_diffuse=False, **kwargs):
""" Fits the model
Parameters
----------
optimizer : string
Stochastic optimizer: either RMSProp or ADAM.
iterations: int
How many iterations to run
print_progress : bool
Whether tp print the ELBO progress or not
start_diffuse : bool
Whether to start from diffuse values (if not: use approx Gaussian)
Returns
----------
BBVI fit object
"""
return self._bbvi_fit(optimizer=optimizer, print_progress=print_progress,
start_diffuse=start_diffuse, iterations=iterations, **kwargs) | python | def fit(self, optimizer='RMSProp', iterations=1000, print_progress=True, start_diffuse=False, **kwargs):
return self._bbvi_fit(optimizer=optimizer, print_progress=print_progress,
start_diffuse=start_diffuse, iterations=iterations, **kwargs) | [
"def",
"fit",
"(",
"self",
",",
"optimizer",
"=",
"'RMSProp'",
",",
"iterations",
"=",
"1000",
",",
"print_progress",
"=",
"True",
",",
"start_diffuse",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_bbvi_fit",
"(",
"optimizer"... | Fits the model
Parameters
----------
optimizer : string
Stochastic optimizer: either RMSProp or ADAM.
iterations: int
How many iterations to run
print_progress : bool
Whether tp print the ELBO progress or not
start_diffuse : bool
Whether to start from diffuse values (if not: use approx Gaussian)
Returns
----------
BBVI fit object | [
"Fits",
"the",
"model"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/nllt.py#L432-L455 |
236,333 | RJT1990/pyflux | pyflux/var/var.py | create_design_matrix_2 | def create_design_matrix_2(Z, data, Y_len, lag_no):
"""
For Python 2.7 - cythonized version only works for 3.5
"""
row_count = 1
for lag in range(1, lag_no+1):
for reg in range(Y_len):
Z[row_count, :] = data[reg][(lag_no-lag):-lag]
row_count += 1
return Z | python | def create_design_matrix_2(Z, data, Y_len, lag_no):
row_count = 1
for lag in range(1, lag_no+1):
for reg in range(Y_len):
Z[row_count, :] = data[reg][(lag_no-lag):-lag]
row_count += 1
return Z | [
"def",
"create_design_matrix_2",
"(",
"Z",
",",
"data",
",",
"Y_len",
",",
"lag_no",
")",
":",
"row_count",
"=",
"1",
"for",
"lag",
"in",
"range",
"(",
"1",
",",
"lag_no",
"+",
"1",
")",
":",
"for",
"reg",
"in",
"range",
"(",
"Y_len",
")",
":",
"... | For Python 2.7 - cythonized version only works for 3.5 | [
"For",
"Python",
"2",
".",
"7",
"-",
"cythonized",
"version",
"only",
"works",
"for",
"3",
".",
"5"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/var/var.py#L18-L29 |
236,334 | RJT1990/pyflux | pyflux/var/var.py | VAR._create_B | def _create_B(self,Y):
""" Creates OLS coefficient matrix
Parameters
----------
Y : np.array
The dependent variables Y
Returns
----------
The coefficient matrix B
"""
Z = self._create_Z(Y)
return np.dot(np.dot(Y,np.transpose(Z)),np.linalg.inv(np.dot(Z,np.transpose(Z)))) | python | def _create_B(self,Y):
Z = self._create_Z(Y)
return np.dot(np.dot(Y,np.transpose(Z)),np.linalg.inv(np.dot(Z,np.transpose(Z)))) | [
"def",
"_create_B",
"(",
"self",
",",
"Y",
")",
":",
"Z",
"=",
"self",
".",
"_create_Z",
"(",
"Y",
")",
"return",
"np",
".",
"dot",
"(",
"np",
".",
"dot",
"(",
"Y",
",",
"np",
".",
"transpose",
"(",
"Z",
")",
")",
",",
"np",
".",
"linalg",
... | Creates OLS coefficient matrix
Parameters
----------
Y : np.array
The dependent variables Y
Returns
----------
The coefficient matrix B | [
"Creates",
"OLS",
"coefficient",
"matrix"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/var/var.py#L97-L111 |
236,335 | RJT1990/pyflux | pyflux/var/var.py | VAR._create_Z | def _create_Z(self,Y):
""" Creates design matrix holding the lagged variables
Parameters
----------
Y : np.array
The dependent variables Y
Returns
----------
The design matrix Z
"""
Z = np.ones(((self.ylen*self.lags +1),Y[0].shape[0]))
return self.create_design_matrix(Z, self.data, Y.shape[0], self.lags) | python | def _create_Z(self,Y):
Z = np.ones(((self.ylen*self.lags +1),Y[0].shape[0]))
return self.create_design_matrix(Z, self.data, Y.shape[0], self.lags) | [
"def",
"_create_Z",
"(",
"self",
",",
"Y",
")",
":",
"Z",
"=",
"np",
".",
"ones",
"(",
"(",
"(",
"self",
".",
"ylen",
"*",
"self",
".",
"lags",
"+",
"1",
")",
",",
"Y",
"[",
"0",
"]",
".",
"shape",
"[",
"0",
"]",
")",
")",
"return",
"self... | Creates design matrix holding the lagged variables
Parameters
----------
Y : np.array
The dependent variables Y
Returns
----------
The design matrix Z | [
"Creates",
"design",
"matrix",
"holding",
"the",
"lagged",
"variables"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/var/var.py#L163-L177 |
236,336 | RJT1990/pyflux | pyflux/var/var.py | VAR._forecast_mean | def _forecast_mean(self,h,t_params,Y,shock_type=None,shock_index=0,shock_value=None,shock_dir='positive',irf_intervals=False):
""" Function allows for mean prediction; also allows shock specification for simulations or impulse response effects
Parameters
----------
h : int
How many steps ahead to forecast
t_params : np.array
Transformed latent variables vector
Y : np.array
Data for series that is being forecast
shock_type : None or str
Type of shock; options include None, 'Cov' (simulate from covariance matrix), 'IRF' (impulse response shock)
shock_index : int
Which latent variable to apply the shock to if using an IRF.
shock_value : None or float
If specified, applies a custom-sized impulse response shock.
shock_dir : str
Direction of the IRF shock. One of 'positive' or 'negative'.
irf_intervals : Boolean
Whether to have intervals for the IRF plot or not
Returns
----------
A vector of forecasted data
"""
random = self._shock_create(h, shock_type, shock_index, shock_value, shock_dir,irf_intervals)
exp = [Y[variable] for variable in range(0,self.ylen)]
# Each forward projection
for t in range(0,h):
new_values = np.zeros(self.ylen)
# Each variable
for variable in range(0,self.ylen):
index_ref = variable*(1+self.ylen*self.lags)
new_values[variable] = t_params[index_ref] # constant
# VAR(p) terms
for lag in range(0,self.lags):
for lagged_var in range(0,self.ylen):
new_values[variable] += t_params[index_ref+lagged_var+(lag*self.ylen)+1]*exp[lagged_var][-1-lag]
# Random shock
new_values[variable] += random[t][variable]
# Add new values
for variable in range(0,self.ylen):
exp[variable] = np.append(exp[variable],new_values[variable])
return np.array(exp) | python | def _forecast_mean(self,h,t_params,Y,shock_type=None,shock_index=0,shock_value=None,shock_dir='positive',irf_intervals=False):
random = self._shock_create(h, shock_type, shock_index, shock_value, shock_dir,irf_intervals)
exp = [Y[variable] for variable in range(0,self.ylen)]
# Each forward projection
for t in range(0,h):
new_values = np.zeros(self.ylen)
# Each variable
for variable in range(0,self.ylen):
index_ref = variable*(1+self.ylen*self.lags)
new_values[variable] = t_params[index_ref] # constant
# VAR(p) terms
for lag in range(0,self.lags):
for lagged_var in range(0,self.ylen):
new_values[variable] += t_params[index_ref+lagged_var+(lag*self.ylen)+1]*exp[lagged_var][-1-lag]
# Random shock
new_values[variable] += random[t][variable]
# Add new values
for variable in range(0,self.ylen):
exp[variable] = np.append(exp[variable],new_values[variable])
return np.array(exp) | [
"def",
"_forecast_mean",
"(",
"self",
",",
"h",
",",
"t_params",
",",
"Y",
",",
"shock_type",
"=",
"None",
",",
"shock_index",
"=",
"0",
",",
"shock_value",
"=",
"None",
",",
"shock_dir",
"=",
"'positive'",
",",
"irf_intervals",
"=",
"False",
")",
":",
... | Function allows for mean prediction; also allows shock specification for simulations or impulse response effects
Parameters
----------
h : int
How many steps ahead to forecast
t_params : np.array
Transformed latent variables vector
Y : np.array
Data for series that is being forecast
shock_type : None or str
Type of shock; options include None, 'Cov' (simulate from covariance matrix), 'IRF' (impulse response shock)
shock_index : int
Which latent variable to apply the shock to if using an IRF.
shock_value : None or float
If specified, applies a custom-sized impulse response shock.
shock_dir : str
Direction of the IRF shock. One of 'positive' or 'negative'.
irf_intervals : Boolean
Whether to have intervals for the IRF plot or not
Returns
----------
A vector of forecasted data | [
"Function",
"allows",
"for",
"mean",
"prediction",
";",
"also",
"allows",
"shock",
"specification",
"for",
"simulations",
"or",
"impulse",
"response",
"effects"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/var/var.py#L179-L237 |
236,337 | RJT1990/pyflux | pyflux/var/var.py | VAR._shock_create | def _shock_create(self, h, shock_type, shock_index, shock_value, shock_dir, irf_intervals):
""" Function creates shocks based on desired specification
Parameters
----------
h : int
How many steps ahead to forecast
shock_type : None or str
Type of shock; options include None, 'Cov' (simulate from covariance matrix), 'IRF' (impulse response shock)
shock_index : int
Which latent variables to apply the shock to if using an IRF.
shock_value : None or float
If specified, applies a custom-sized impulse response shock.
shock_dir : str
Direction of the IRF shock. One of 'positive' or 'negative'.
irf_intervals : Boolean
Whether to have intervals for the IRF plot or not
Returns
----------
A h-length list which contains np.arrays containing shocks for each variable
"""
if shock_type is None:
random = [np.zeros(self.ylen) for i in range(0,h)]
elif shock_type == 'IRF':
if self.use_ols_covariance is False:
cov = self.custom_covariance(self.latent_variables.get_z_values())
else:
cov = self.ols_covariance()
post = ss.multivariate_normal(np.zeros(self.ylen),cov)
if irf_intervals is False:
random = [np.zeros(self.ylen) for i in range(0,h)]
else:
random = [post.rvs() for i in range(0,h)]
random[0] = np.zeros(self.ylen)
if shock_value is None:
if shock_dir=='positive':
random[0][shock_index] = cov[shock_index,shock_index]**0.5
elif shock_dir=='negative':
random[0][shock_index] = -cov[shock_index,shock_index]**0.5
else:
raise ValueError("Unknown shock direction!")
else:
random[0][shock_index] = shock_value
elif shock_type == 'Cov':
if self.use_ols_covariance is False:
cov = self.custom_covariance(self.latent_variables.get_z_values())
else:
cov = self.ols_covariance()
post = ss.multivariate_normal(np.zeros(self.ylen),cov)
random = [post.rvs() for i in range(0,h)]
return random | python | def _shock_create(self, h, shock_type, shock_index, shock_value, shock_dir, irf_intervals):
if shock_type is None:
random = [np.zeros(self.ylen) for i in range(0,h)]
elif shock_type == 'IRF':
if self.use_ols_covariance is False:
cov = self.custom_covariance(self.latent_variables.get_z_values())
else:
cov = self.ols_covariance()
post = ss.multivariate_normal(np.zeros(self.ylen),cov)
if irf_intervals is False:
random = [np.zeros(self.ylen) for i in range(0,h)]
else:
random = [post.rvs() for i in range(0,h)]
random[0] = np.zeros(self.ylen)
if shock_value is None:
if shock_dir=='positive':
random[0][shock_index] = cov[shock_index,shock_index]**0.5
elif shock_dir=='negative':
random[0][shock_index] = -cov[shock_index,shock_index]**0.5
else:
raise ValueError("Unknown shock direction!")
else:
random[0][shock_index] = shock_value
elif shock_type == 'Cov':
if self.use_ols_covariance is False:
cov = self.custom_covariance(self.latent_variables.get_z_values())
else:
cov = self.ols_covariance()
post = ss.multivariate_normal(np.zeros(self.ylen),cov)
random = [post.rvs() for i in range(0,h)]
return random | [
"def",
"_shock_create",
"(",
"self",
",",
"h",
",",
"shock_type",
",",
"shock_index",
",",
"shock_value",
",",
"shock_dir",
",",
"irf_intervals",
")",
":",
"if",
"shock_type",
"is",
"None",
":",
"random",
"=",
"[",
"np",
".",
"zeros",
"(",
"self",
".",
... | Function creates shocks based on desired specification
Parameters
----------
h : int
How many steps ahead to forecast
shock_type : None or str
Type of shock; options include None, 'Cov' (simulate from covariance matrix), 'IRF' (impulse response shock)
shock_index : int
Which latent variables to apply the shock to if using an IRF.
shock_value : None or float
If specified, applies a custom-sized impulse response shock.
shock_dir : str
Direction of the IRF shock. One of 'positive' or 'negative'.
irf_intervals : Boolean
Whether to have intervals for the IRF plot or not
Returns
----------
A h-length list which contains np.arrays containing shocks for each variable | [
"Function",
"creates",
"shocks",
"based",
"on",
"desired",
"specification"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/var/var.py#L269-L336 |
236,338 | RJT1990/pyflux | pyflux/var/var.py | VAR.estimator_cov | def estimator_cov(self,method):
""" Creates covariance matrix for the estimators
Parameters
----------
method : str
Estimation method
Returns
----------
A Covariance Matrix
"""
Y = np.array([reg[self.lags:] for reg in self.data])
Z = self._create_Z(Y)
if method == 'OLS':
sigma = self.ols_covariance()
else:
sigma = self.custom_covariance(self.latent_variables.get_z_values())
return np.kron(np.linalg.inv(np.dot(Z,np.transpose(Z))), sigma) | python | def estimator_cov(self,method):
Y = np.array([reg[self.lags:] for reg in self.data])
Z = self._create_Z(Y)
if method == 'OLS':
sigma = self.ols_covariance()
else:
sigma = self.custom_covariance(self.latent_variables.get_z_values())
return np.kron(np.linalg.inv(np.dot(Z,np.transpose(Z))), sigma) | [
"def",
"estimator_cov",
"(",
"self",
",",
"method",
")",
":",
"Y",
"=",
"np",
".",
"array",
"(",
"[",
"reg",
"[",
"self",
".",
"lags",
":",
"]",
"for",
"reg",
"in",
"self",
".",
"data",
"]",
")",
"Z",
"=",
"self",
".",
"_create_Z",
"(",
"Y",
... | Creates covariance matrix for the estimators
Parameters
----------
method : str
Estimation method
Returns
----------
A Covariance Matrix | [
"Creates",
"covariance",
"matrix",
"for",
"the",
"estimators"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/var/var.py#L388-L407 |
236,339 | RJT1990/pyflux | pyflux/var/var.py | VAR.ols_covariance | def ols_covariance(self):
""" Creates OLS estimate of the covariance matrix
Returns
----------
The OLS estimate of the covariance matrix
"""
Y = np.array([reg[self.lags:reg.shape[0]] for reg in self.data])
return (1.0/(Y[0].shape[0]))*np.dot(self.residuals(Y),np.transpose(self.residuals(Y))) | python | def ols_covariance(self):
Y = np.array([reg[self.lags:reg.shape[0]] for reg in self.data])
return (1.0/(Y[0].shape[0]))*np.dot(self.residuals(Y),np.transpose(self.residuals(Y))) | [
"def",
"ols_covariance",
"(",
"self",
")",
":",
"Y",
"=",
"np",
".",
"array",
"(",
"[",
"reg",
"[",
"self",
".",
"lags",
":",
"reg",
".",
"shape",
"[",
"0",
"]",
"]",
"for",
"reg",
"in",
"self",
".",
"data",
"]",
")",
"return",
"(",
"1.0",
"/... | Creates OLS estimate of the covariance matrix
Returns
----------
The OLS estimate of the covariance matrix | [
"Creates",
"OLS",
"estimate",
"of",
"the",
"covariance",
"matrix"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/var/var.py#L435-L444 |
236,340 | RJT1990/pyflux | pyflux/var/var.py | VAR.residuals | def residuals(self,Y):
""" Creates the model residuals
Parameters
----------
Y : np.array
The dependent variables Y
Returns
----------
The model residuals
"""
return (Y-np.dot(self._create_B(Y),self._create_Z(Y))) | python | def residuals(self,Y):
return (Y-np.dot(self._create_B(Y),self._create_Z(Y))) | [
"def",
"residuals",
"(",
"self",
",",
"Y",
")",
":",
"return",
"(",
"Y",
"-",
"np",
".",
"dot",
"(",
"self",
".",
"_create_B",
"(",
"Y",
")",
",",
"self",
".",
"_create_Z",
"(",
"Y",
")",
")",
")"
] | Creates the model residuals
Parameters
----------
Y : np.array
The dependent variables Y
Returns
----------
The model residuals | [
"Creates",
"the",
"model",
"residuals"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/var/var.py#L648-L661 |
236,341 | RJT1990/pyflux | pyflux/var/var.py | VAR.construct_wishart | def construct_wishart(self,v,X):
"""
Constructs a Wishart prior for the covariance matrix
"""
self.adjust_prior(list(range(int((len(self.latent_variables.z_list)-self.ylen-(self.ylen**2-self.ylen)/2)),
int(len(self.latent_variables.z_list)))), fam.InverseWishart(v,X)) | python | def construct_wishart(self,v,X):
self.adjust_prior(list(range(int((len(self.latent_variables.z_list)-self.ylen-(self.ylen**2-self.ylen)/2)),
int(len(self.latent_variables.z_list)))), fam.InverseWishart(v,X)) | [
"def",
"construct_wishart",
"(",
"self",
",",
"v",
",",
"X",
")",
":",
"self",
".",
"adjust_prior",
"(",
"list",
"(",
"range",
"(",
"int",
"(",
"(",
"len",
"(",
"self",
".",
"latent_variables",
".",
"z_list",
")",
"-",
"self",
".",
"ylen",
"-",
"("... | Constructs a Wishart prior for the covariance matrix | [
"Constructs",
"a",
"Wishart",
"prior",
"for",
"the",
"covariance",
"matrix"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/var/var.py#L663-L668 |
236,342 | RJT1990/pyflux | pyflux/ssm/llm.py | LLEV.simulation_smoother | def simulation_smoother(self,beta):
""" Koopman's simulation smoother - simulates from states given
model latent variables and observations
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
- A simulated state evolution
"""
T, Z, R, Q, H = self._ss_matrices(beta)
# Generate e_t+ and n_t+
rnd_h = np.random.normal(0,np.sqrt(H),self.data.shape[0]+1)
q_dist = ss.multivariate_normal([0.0], Q)
rnd_q = q_dist.rvs(self.data.shape[0]+1)
# Generate a_t+ and y_t+
a_plus = np.zeros((T.shape[0],self.data.shape[0]+1))
a_plus[0,0] = np.mean(self.data[0:5])
y_plus = np.zeros(self.data.shape[0])
for t in range(0,self.data.shape[0]+1):
if t == 0:
a_plus[:,t] = np.dot(T,a_plus[:,t]) + rnd_q[t]
y_plus[t] = np.dot(Z,a_plus[:,t]) + rnd_h[t]
else:
if t != self.data.shape[0]:
a_plus[:,t] = np.dot(T,a_plus[:,t-1]) + rnd_q[t]
y_plus[t] = np.dot(Z,a_plus[:,t]) + rnd_h[t]
alpha_hat,_ = self.smoothed_state(self.data,beta)
alpha_hat_plus,_ = self.smoothed_state(y_plus,beta)
alpha_tilde = alpha_hat - alpha_hat_plus + a_plus
return alpha_tilde | python | def simulation_smoother(self,beta):
T, Z, R, Q, H = self._ss_matrices(beta)
# Generate e_t+ and n_t+
rnd_h = np.random.normal(0,np.sqrt(H),self.data.shape[0]+1)
q_dist = ss.multivariate_normal([0.0], Q)
rnd_q = q_dist.rvs(self.data.shape[0]+1)
# Generate a_t+ and y_t+
a_plus = np.zeros((T.shape[0],self.data.shape[0]+1))
a_plus[0,0] = np.mean(self.data[0:5])
y_plus = np.zeros(self.data.shape[0])
for t in range(0,self.data.shape[0]+1):
if t == 0:
a_plus[:,t] = np.dot(T,a_plus[:,t]) + rnd_q[t]
y_plus[t] = np.dot(Z,a_plus[:,t]) + rnd_h[t]
else:
if t != self.data.shape[0]:
a_plus[:,t] = np.dot(T,a_plus[:,t-1]) + rnd_q[t]
y_plus[t] = np.dot(Z,a_plus[:,t]) + rnd_h[t]
alpha_hat,_ = self.smoothed_state(self.data,beta)
alpha_hat_plus,_ = self.smoothed_state(y_plus,beta)
alpha_tilde = alpha_hat - alpha_hat_plus + a_plus
return alpha_tilde | [
"def",
"simulation_smoother",
"(",
"self",
",",
"beta",
")",
":",
"T",
",",
"Z",
",",
"R",
",",
"Q",
",",
"H",
"=",
"self",
".",
"_ss_matrices",
"(",
"beta",
")",
"# Generate e_t+ and n_t+",
"rnd_h",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"0",... | Koopman's simulation smoother - simulates from states given
model latent variables and observations
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
- A simulated state evolution | [
"Koopman",
"s",
"simulation",
"smoother",
"-",
"simulates",
"from",
"states",
"given",
"model",
"latent",
"variables",
"and",
"observations"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/llm.py#L496-L536 |
236,343 | RJT1990/pyflux | pyflux/ssm/llm.py | LLEV.smoothed_state | def smoothed_state(self,data,beta):
""" Creates the negative log marginal likelihood of the model
Parameters
----------
data : np.array
Data to be smoothed
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
- Smoothed states
"""
T, Z, R, Q, H = self._ss_matrices(beta)
alpha, V = univariate_KFS(data,Z,H,T,Q,R,0.0)
return alpha, V | python | def smoothed_state(self,data,beta):
T, Z, R, Q, H = self._ss_matrices(beta)
alpha, V = univariate_KFS(data,Z,H,T,Q,R,0.0)
return alpha, V | [
"def",
"smoothed_state",
"(",
"self",
",",
"data",
",",
"beta",
")",
":",
"T",
",",
"Z",
",",
"R",
",",
"Q",
",",
"H",
"=",
"self",
".",
"_ss_matrices",
"(",
"beta",
")",
"alpha",
",",
"V",
"=",
"univariate_KFS",
"(",
"data",
",",
"Z",
",",
"H"... | Creates the negative log marginal likelihood of the model
Parameters
----------
data : np.array
Data to be smoothed
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
- Smoothed states | [
"Creates",
"the",
"negative",
"log",
"marginal",
"likelihood",
"of",
"the",
"model"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/llm.py#L538-L557 |
236,344 | RJT1990/pyflux | pyflux/tsm.py | TSM._laplace_fit | def _laplace_fit(self,obj_type):
""" Performs a Laplace approximation to the posterior
Parameters
----------
obj_type : method
Whether a likelihood or a posterior
Returns
----------
None (plots posterior)
"""
# Get Mode and Inverse Hessian information
y = self.fit(method='PML',printer=False)
if y.ihessian is None:
raise Exception("No Hessian information - Laplace approximation cannot be performed")
else:
self.latent_variables.estimation_method = 'Laplace'
theta, Y, scores, states, states_var, X_names = self._categorize_model_output(self.latent_variables.get_z_values())
# Change this in future
try:
latent_variables_store = self.latent_variables.copy()
except:
latent_variables_store = self.latent_variables
return LaplaceResults(data_name=self.data_name,X_names=X_names,model_name=self.model_name,
model_type=self.model_type, latent_variables=latent_variables_store,data=Y,index=self.index,
multivariate_model=self.multivariate_model,objective_object=obj_type,
method='Laplace',ihessian=y.ihessian,signal=theta,scores=scores,
z_hide=self._z_hide,max_lag=self.max_lag,states=states,states_var=states_var) | python | def _laplace_fit(self,obj_type):
# Get Mode and Inverse Hessian information
y = self.fit(method='PML',printer=False)
if y.ihessian is None:
raise Exception("No Hessian information - Laplace approximation cannot be performed")
else:
self.latent_variables.estimation_method = 'Laplace'
theta, Y, scores, states, states_var, X_names = self._categorize_model_output(self.latent_variables.get_z_values())
# Change this in future
try:
latent_variables_store = self.latent_variables.copy()
except:
latent_variables_store = self.latent_variables
return LaplaceResults(data_name=self.data_name,X_names=X_names,model_name=self.model_name,
model_type=self.model_type, latent_variables=latent_variables_store,data=Y,index=self.index,
multivariate_model=self.multivariate_model,objective_object=obj_type,
method='Laplace',ihessian=y.ihessian,signal=theta,scores=scores,
z_hide=self._z_hide,max_lag=self.max_lag,states=states,states_var=states_var) | [
"def",
"_laplace_fit",
"(",
"self",
",",
"obj_type",
")",
":",
"# Get Mode and Inverse Hessian information",
"y",
"=",
"self",
".",
"fit",
"(",
"method",
"=",
"'PML'",
",",
"printer",
"=",
"False",
")",
"if",
"y",
".",
"ihessian",
"is",
"None",
":",
"raise... | Performs a Laplace approximation to the posterior
Parameters
----------
obj_type : method
Whether a likelihood or a posterior
Returns
----------
None (plots posterior) | [
"Performs",
"a",
"Laplace",
"approximation",
"to",
"the",
"posterior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/tsm.py#L187-L221 |
236,345 | RJT1990/pyflux | pyflux/tsm.py | TSM._optimize_fit | def _optimize_fit(self, obj_type=None, **kwargs):
"""
This function fits models using Maximum Likelihood or Penalized Maximum Likelihood
"""
preopt_search = kwargs.get('preopt_search', True) # If user supplied
if obj_type == self.neg_loglik:
method = 'MLE'
else:
method = 'PML'
# Starting values - check to see if model has preoptimize method, if not, simply use default starting values
if preopt_search is True:
try:
phi = self._preoptimize_model(self.latent_variables.get_z_starting_values(), method)
preoptimized = True
except:
phi = self.latent_variables.get_z_starting_values()
preoptimized = False
else:
preoptimized = False
phi = self.latent_variables.get_z_starting_values()
phi = kwargs.get('start',phi).copy() # If user supplied
# Optimize using L-BFGS-B
p = optimize.minimize(obj_type, phi, method='L-BFGS-B', options={'gtol': 1e-8})
if preoptimized is True:
p2 = optimize.minimize(obj_type, self.latent_variables.get_z_starting_values(), method='L-BFGS-B',
options={'gtol': 1e-8})
if self.neg_loglik(p2.x) < self.neg_loglik(p.x):
p = p2
theta, Y, scores, states, states_var, X_names = self._categorize_model_output(p.x)
# Check that matrix is non-singular; act accordingly
try:
ihessian = np.linalg.inv(nd.Hessian(obj_type)(p.x))
ses = np.power(np.abs(np.diag(ihessian)),0.5)
self.latent_variables.set_z_values(p.x,method,ses,None)
except:
ihessian = None
ses = None
self.latent_variables.set_z_values(p.x,method,None,None)
self.latent_variables.estimation_method = method
# Change this in future
try:
latent_variables_store = self.latent_variables.copy()
except:
latent_variables_store = self.latent_variables
return MLEResults(data_name=self.data_name,X_names=X_names,model_name=self.model_name,
model_type=self.model_type, latent_variables=latent_variables_store,results=p,data=Y, index=self.index,
multivariate_model=self.multivariate_model,objective_object=obj_type,
method=method,ihessian=ihessian,signal=theta,scores=scores,
z_hide=self._z_hide,max_lag=self.max_lag,states=states,states_var=states_var) | python | def _optimize_fit(self, obj_type=None, **kwargs):
preopt_search = kwargs.get('preopt_search', True) # If user supplied
if obj_type == self.neg_loglik:
method = 'MLE'
else:
method = 'PML'
# Starting values - check to see if model has preoptimize method, if not, simply use default starting values
if preopt_search is True:
try:
phi = self._preoptimize_model(self.latent_variables.get_z_starting_values(), method)
preoptimized = True
except:
phi = self.latent_variables.get_z_starting_values()
preoptimized = False
else:
preoptimized = False
phi = self.latent_variables.get_z_starting_values()
phi = kwargs.get('start',phi).copy() # If user supplied
# Optimize using L-BFGS-B
p = optimize.minimize(obj_type, phi, method='L-BFGS-B', options={'gtol': 1e-8})
if preoptimized is True:
p2 = optimize.minimize(obj_type, self.latent_variables.get_z_starting_values(), method='L-BFGS-B',
options={'gtol': 1e-8})
if self.neg_loglik(p2.x) < self.neg_loglik(p.x):
p = p2
theta, Y, scores, states, states_var, X_names = self._categorize_model_output(p.x)
# Check that matrix is non-singular; act accordingly
try:
ihessian = np.linalg.inv(nd.Hessian(obj_type)(p.x))
ses = np.power(np.abs(np.diag(ihessian)),0.5)
self.latent_variables.set_z_values(p.x,method,ses,None)
except:
ihessian = None
ses = None
self.latent_variables.set_z_values(p.x,method,None,None)
self.latent_variables.estimation_method = method
# Change this in future
try:
latent_variables_store = self.latent_variables.copy()
except:
latent_variables_store = self.latent_variables
return MLEResults(data_name=self.data_name,X_names=X_names,model_name=self.model_name,
model_type=self.model_type, latent_variables=latent_variables_store,results=p,data=Y, index=self.index,
multivariate_model=self.multivariate_model,objective_object=obj_type,
method=method,ihessian=ihessian,signal=theta,scores=scores,
z_hide=self._z_hide,max_lag=self.max_lag,states=states,states_var=states_var) | [
"def",
"_optimize_fit",
"(",
"self",
",",
"obj_type",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"preopt_search",
"=",
"kwargs",
".",
"get",
"(",
"'preopt_search'",
",",
"True",
")",
"# If user supplied",
"if",
"obj_type",
"==",
"self",
".",
"neg_logl... | This function fits models using Maximum Likelihood or Penalized Maximum Likelihood | [
"This",
"function",
"fits",
"models",
"using",
"Maximum",
"Likelihood",
"or",
"Penalized",
"Maximum",
"Likelihood"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/tsm.py#L347-L406 |
236,346 | RJT1990/pyflux | pyflux/tsm.py | TSM.multivariate_neg_logposterior | def multivariate_neg_logposterior(self,beta):
""" Returns negative log posterior, for a model with a covariance matrix
Parameters
----------
beta : np.array
Contains untransformed starting values for latent_variables
Returns
----------
Negative log posterior
"""
post = self.neg_loglik(beta)
for k in range(0,self.z_no):
if self.latent_variables.z_list[k].prior.covariance_prior is True:
post += -self.latent_variables.z_list[k].prior.logpdf(self.custom_covariance(beta))
break
else:
post += -self.latent_variables.z_list[k].prior.logpdf(beta[k])
return post | python | def multivariate_neg_logposterior(self,beta):
post = self.neg_loglik(beta)
for k in range(0,self.z_no):
if self.latent_variables.z_list[k].prior.covariance_prior is True:
post += -self.latent_variables.z_list[k].prior.logpdf(self.custom_covariance(beta))
break
else:
post += -self.latent_variables.z_list[k].prior.logpdf(beta[k])
return post | [
"def",
"multivariate_neg_logposterior",
"(",
"self",
",",
"beta",
")",
":",
"post",
"=",
"self",
".",
"neg_loglik",
"(",
"beta",
")",
"for",
"k",
"in",
"range",
"(",
"0",
",",
"self",
".",
"z_no",
")",
":",
"if",
"self",
".",
"latent_variables",
".",
... | Returns negative log posterior, for a model with a covariance matrix
Parameters
----------
beta : np.array
Contains untransformed starting values for latent_variables
Returns
----------
Negative log posterior | [
"Returns",
"negative",
"log",
"posterior",
"for",
"a",
"model",
"with",
"a",
"covariance",
"matrix"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/tsm.py#L496-L516 |
236,347 | RJT1990/pyflux | pyflux/tsm.py | TSM.shift_dates | def shift_dates(self,h):
""" Auxiliary function for creating dates for forecasts
Parameters
----------
h : int
How many steps to forecast
Returns
----------
A transformed date_index object
"""
date_index = copy.deepcopy(self.index)
date_index = date_index[self.max_lag:len(date_index)]
if self.is_pandas is True:
if isinstance(date_index, pd.core.indexes.datetimes.DatetimeIndex):
if pd.infer_freq(date_index) in ['H', 'M', 'S']:
for t in range(h):
date_index += pd.DateOffset((date_index[len(date_index)-1] - date_index[len(date_index)-2]).seconds)
else: # Assume higher frequency (configured for days)
for t in range(h):
date_index += pd.DateOffset((date_index[len(date_index)-1] - date_index[len(date_index)-2]).days)
elif isinstance(date_index, pd.core.indexes.numeric.Int64Index):
for i in range(h):
new_value = date_index.values[len(date_index.values)-1] + (date_index.values[len(date_index.values)-1] - date_index.values[len(date_index.values)-2])
date_index = pd.Int64Index(np.append(date_index.values,new_value))
else:
for t in range(h):
date_index.append(date_index[len(date_index)-1]+1)
return date_index | python | def shift_dates(self,h):
date_index = copy.deepcopy(self.index)
date_index = date_index[self.max_lag:len(date_index)]
if self.is_pandas is True:
if isinstance(date_index, pd.core.indexes.datetimes.DatetimeIndex):
if pd.infer_freq(date_index) in ['H', 'M', 'S']:
for t in range(h):
date_index += pd.DateOffset((date_index[len(date_index)-1] - date_index[len(date_index)-2]).seconds)
else: # Assume higher frequency (configured for days)
for t in range(h):
date_index += pd.DateOffset((date_index[len(date_index)-1] - date_index[len(date_index)-2]).days)
elif isinstance(date_index, pd.core.indexes.numeric.Int64Index):
for i in range(h):
new_value = date_index.values[len(date_index.values)-1] + (date_index.values[len(date_index.values)-1] - date_index.values[len(date_index.values)-2])
date_index = pd.Int64Index(np.append(date_index.values,new_value))
else:
for t in range(h):
date_index.append(date_index[len(date_index)-1]+1)
return date_index | [
"def",
"shift_dates",
"(",
"self",
",",
"h",
")",
":",
"date_index",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"index",
")",
"date_index",
"=",
"date_index",
"[",
"self",
".",
"max_lag",
":",
"len",
"(",
"date_index",
")",
"]",
"if",
"self",
".... | Auxiliary function for creating dates for forecasts
Parameters
----------
h : int
How many steps to forecast
Returns
----------
A transformed date_index object | [
"Auxiliary",
"function",
"for",
"creating",
"dates",
"for",
"forecasts"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/tsm.py#L518-L559 |
236,348 | RJT1990/pyflux | pyflux/tsm.py | TSM.plot_z | def plot_z(self, indices=None,figsize=(15,5),**kwargs):
""" Plots latent variables by calling latent parameters object
Returns
----------
Pretty plot
"""
self.latent_variables.plot_z(indices=indices,figsize=figsize,**kwargs) | python | def plot_z(self, indices=None,figsize=(15,5),**kwargs):
self.latent_variables.plot_z(indices=indices,figsize=figsize,**kwargs) | [
"def",
"plot_z",
"(",
"self",
",",
"indices",
"=",
"None",
",",
"figsize",
"=",
"(",
"15",
",",
"5",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"latent_variables",
".",
"plot_z",
"(",
"indices",
"=",
"indices",
",",
"figsize",
"=",
"figsi... | Plots latent variables by calling latent parameters object
Returns
----------
Pretty plot | [
"Plots",
"latent",
"variables",
"by",
"calling",
"latent",
"parameters",
"object"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/tsm.py#L579-L586 |
236,349 | RJT1990/pyflux | pyflux/ssm/ndynlin.py | NDynReg.evo_blanket | def evo_blanket(self, beta, alpha):
""" Creates Markov blanket for the variance latent variables
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
alpha : np.array
A vector of states
Returns
----------
Markov blanket for variance latent variables
"""
# Markov blanket for each state
evo_blanket = np.zeros(self.state_no)
for i in range(evo_blanket.shape[0]):
evo_blanket[i] = self.state_likelihood_markov_blanket(beta, alpha, i).sum()
# If the family has additional parameters, add their markov blankets
if self.family_z_no > 0:
evo_blanket = np.append([self.likelihood_markov_blanket(beta).sum()]*(self.family_z_no),evo_blanket)
return evo_blanket | python | def evo_blanket(self, beta, alpha):
# Markov blanket for each state
evo_blanket = np.zeros(self.state_no)
for i in range(evo_blanket.shape[0]):
evo_blanket[i] = self.state_likelihood_markov_blanket(beta, alpha, i).sum()
# If the family has additional parameters, add their markov blankets
if self.family_z_no > 0:
evo_blanket = np.append([self.likelihood_markov_blanket(beta).sum()]*(self.family_z_no),evo_blanket)
return evo_blanket | [
"def",
"evo_blanket",
"(",
"self",
",",
"beta",
",",
"alpha",
")",
":",
"# Markov blanket for each state",
"evo_blanket",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"state_no",
")",
"for",
"i",
"in",
"range",
"(",
"evo_blanket",
".",
"shape",
"[",
"0",
"... | Creates Markov blanket for the variance latent variables
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
alpha : np.array
A vector of states
Returns
----------
Markov blanket for variance latent variables | [
"Creates",
"Markov",
"blanket",
"for",
"the",
"variance",
"latent",
"variables"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/ndynlin.py#L233-L258 |
236,350 | RJT1990/pyflux | pyflux/ssm/ndynlin.py | NDynReg.log_p_blanket | def log_p_blanket(self, beta):
""" Creates complete Markov blanket for latent variables
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
Markov blanket for latent variables
"""
states = np.zeros([self.state_no, self.data.shape[0]])
for state_i in range(self.state_no):
states[state_i,:] = beta[(self.z_no + (self.data.shape[0]*state_i)):(self.z_no + (self.data.shape[0]*(state_i+1)))]
return np.append(self.evo_blanket(beta,states),self.markov_blanket(beta,states)) | python | def log_p_blanket(self, beta):
states = np.zeros([self.state_no, self.data.shape[0]])
for state_i in range(self.state_no):
states[state_i,:] = beta[(self.z_no + (self.data.shape[0]*state_i)):(self.z_no + (self.data.shape[0]*(state_i+1)))]
return np.append(self.evo_blanket(beta,states),self.markov_blanket(beta,states)) | [
"def",
"log_p_blanket",
"(",
"self",
",",
"beta",
")",
":",
"states",
"=",
"np",
".",
"zeros",
"(",
"[",
"self",
".",
"state_no",
",",
"self",
".",
"data",
".",
"shape",
"[",
"0",
"]",
"]",
")",
"for",
"state_i",
"in",
"range",
"(",
"self",
".",
... | Creates complete Markov blanket for latent variables
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
Markov blanket for latent variables | [
"Creates",
"complete",
"Markov",
"blanket",
"for",
"latent",
"variables"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/ndynlin.py#L260-L276 |
236,351 | RJT1990/pyflux | pyflux/families/exponential.py | Exponential.logpdf | def logpdf(self, mu):
"""
Log PDF for Exponential prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu))
"""
if self.transform is not None:
mu = self.transform(mu)
return ss.expon.logpdf(mu, self.lmd0) | python | def logpdf(self, mu):
if self.transform is not None:
mu = self.transform(mu)
return ss.expon.logpdf(mu, self.lmd0) | [
"def",
"logpdf",
"(",
"self",
",",
"mu",
")",
":",
"if",
"self",
".",
"transform",
"is",
"not",
"None",
":",
"mu",
"=",
"self",
".",
"transform",
"(",
"mu",
")",
"return",
"ss",
".",
"expon",
".",
"logpdf",
"(",
"mu",
",",
"self",
".",
"lmd0",
... | Log PDF for Exponential prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu)) | [
"Log",
"PDF",
"for",
"Exponential",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/exponential.py#L177-L192 |
236,352 | RJT1990/pyflux | pyflux/families/exponential.py | Exponential.markov_blanket | def markov_blanket(y, mean, scale, shape, skewness):
""" Markov blanket for the Exponential distribution
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Exponential distribution
scale : float
scale parameter for the Exponential distribution
shape : float
tail thickness parameter for the Exponential distribution
skewness : float
skewness parameter for the Exponential distribution
Returns
----------
- Markov blanket of the Exponential family
"""
return ss.expon.logpdf(x=y, scale=1/mean) | python | def markov_blanket(y, mean, scale, shape, skewness):
return ss.expon.logpdf(x=y, scale=1/mean) | [
"def",
"markov_blanket",
"(",
"y",
",",
"mean",
",",
"scale",
",",
"shape",
",",
"skewness",
")",
":",
"return",
"ss",
".",
"expon",
".",
"logpdf",
"(",
"x",
"=",
"y",
",",
"scale",
"=",
"1",
"/",
"mean",
")"
] | Markov blanket for the Exponential distribution
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Exponential distribution
scale : float
scale parameter for the Exponential distribution
shape : float
tail thickness parameter for the Exponential distribution
skewness : float
skewness parameter for the Exponential distribution
Returns
----------
- Markov blanket of the Exponential family | [
"Markov",
"blanket",
"for",
"the",
"Exponential",
"distribution"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/exponential.py#L195-L219 |
236,353 | RJT1990/pyflux | pyflux/families/exponential.py | Exponential.pdf | def pdf(self, mu):
"""
PDF for Exponential prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- p(mu)
"""
if self.transform is not None:
mu = self.transform(mu)
return ss.expon.pdf(mu, self.lmd0) | python | def pdf(self, mu):
if self.transform is not None:
mu = self.transform(mu)
return ss.expon.pdf(mu, self.lmd0) | [
"def",
"pdf",
"(",
"self",
",",
"mu",
")",
":",
"if",
"self",
".",
"transform",
"is",
"not",
"None",
":",
"mu",
"=",
"self",
".",
"transform",
"(",
"mu",
")",
"return",
"ss",
".",
"expon",
".",
"pdf",
"(",
"mu",
",",
"self",
".",
"lmd0",
")"
] | PDF for Exponential prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- p(mu) | [
"PDF",
"for",
"Exponential",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/exponential.py#L277-L292 |
236,354 | RJT1990/pyflux | pyflux/inference/bbvi.py | BBVI.change_parameters | def change_parameters(self,params):
"""
Utility function for changing the approximate distribution parameters
"""
no_of_params = 0
for core_param in range(len(self.q)):
for approx_param in range(self.q[core_param].param_no):
self.q[core_param].vi_change_param(approx_param, params[no_of_params])
no_of_params += 1 | python | def change_parameters(self,params):
no_of_params = 0
for core_param in range(len(self.q)):
for approx_param in range(self.q[core_param].param_no):
self.q[core_param].vi_change_param(approx_param, params[no_of_params])
no_of_params += 1 | [
"def",
"change_parameters",
"(",
"self",
",",
"params",
")",
":",
"no_of_params",
"=",
"0",
"for",
"core_param",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"q",
")",
")",
":",
"for",
"approx_param",
"in",
"range",
"(",
"self",
".",
"q",
"[",
"core_... | Utility function for changing the approximate distribution parameters | [
"Utility",
"function",
"for",
"changing",
"the",
"approximate",
"distribution",
"parameters"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/inference/bbvi.py#L54-L62 |
236,355 | RJT1990/pyflux | pyflux/inference/bbvi.py | BBVI.current_parameters | def current_parameters(self):
"""
Obtains an array with the current parameters
"""
current = []
for core_param in range(len(self.q)):
for approx_param in range(self.q[core_param].param_no):
current.append(self.q[core_param].vi_return_param(approx_param))
return np.array(current) | python | def current_parameters(self):
current = []
for core_param in range(len(self.q)):
for approx_param in range(self.q[core_param].param_no):
current.append(self.q[core_param].vi_return_param(approx_param))
return np.array(current) | [
"def",
"current_parameters",
"(",
"self",
")",
":",
"current",
"=",
"[",
"]",
"for",
"core_param",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"q",
")",
")",
":",
"for",
"approx_param",
"in",
"range",
"(",
"self",
".",
"q",
"[",
"core_param",
"]",
... | Obtains an array with the current parameters | [
"Obtains",
"an",
"array",
"with",
"the",
"current",
"parameters"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/inference/bbvi.py#L71-L79 |
236,356 | RJT1990/pyflux | pyflux/inference/bbvi.py | BBVI.cv_gradient | def cv_gradient(self,z):
"""
The control variate augmented Monte Carlo gradient estimate
"""
gradient = np.zeros(np.sum(self.approx_param_no))
z_t = z.T
log_q = self.normal_log_q(z.T)
log_p = self.log_p(z.T)
grad_log_q = self.grad_log_q(z)
gradient = grad_log_q*(log_p-log_q)
alpha0 = alpha_recursion(np.zeros(np.sum(self.approx_param_no)), grad_log_q, gradient, np.sum(self.approx_param_no))
vectorized = gradient - ((alpha0/np.var(grad_log_q,axis=1))*grad_log_q.T).T
return np.mean(vectorized,axis=1) | python | def cv_gradient(self,z):
gradient = np.zeros(np.sum(self.approx_param_no))
z_t = z.T
log_q = self.normal_log_q(z.T)
log_p = self.log_p(z.T)
grad_log_q = self.grad_log_q(z)
gradient = grad_log_q*(log_p-log_q)
alpha0 = alpha_recursion(np.zeros(np.sum(self.approx_param_no)), grad_log_q, gradient, np.sum(self.approx_param_no))
vectorized = gradient - ((alpha0/np.var(grad_log_q,axis=1))*grad_log_q.T).T
return np.mean(vectorized,axis=1) | [
"def",
"cv_gradient",
"(",
"self",
",",
"z",
")",
":",
"gradient",
"=",
"np",
".",
"zeros",
"(",
"np",
".",
"sum",
"(",
"self",
".",
"approx_param_no",
")",
")",
"z_t",
"=",
"z",
".",
"T",
"log_q",
"=",
"self",
".",
"normal_log_q",
"(",
"z",
".",... | The control variate augmented Monte Carlo gradient estimate | [
"The",
"control",
"variate",
"augmented",
"Monte",
"Carlo",
"gradient",
"estimate"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/inference/bbvi.py#L81-L96 |
236,357 | RJT1990/pyflux | pyflux/inference/bbvi.py | BBVI.draw_variables | def draw_variables(self):
"""
Draw parameters from the approximating distributions
"""
z = self.q[0].draw_variable_local(self.sims)
for i in range(1,len(self.q)):
z = np.vstack((z,self.q[i].draw_variable_local(self.sims)))
return z | python | def draw_variables(self):
z = self.q[0].draw_variable_local(self.sims)
for i in range(1,len(self.q)):
z = np.vstack((z,self.q[i].draw_variable_local(self.sims)))
return z | [
"def",
"draw_variables",
"(",
"self",
")",
":",
"z",
"=",
"self",
".",
"q",
"[",
"0",
"]",
".",
"draw_variable_local",
"(",
"self",
".",
"sims",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"self",
".",
"q",
")",
")",
":",
"z",
... | Draw parameters from the approximating distributions | [
"Draw",
"parameters",
"from",
"the",
"approximating",
"distributions"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/inference/bbvi.py#L129-L136 |
236,358 | RJT1990/pyflux | pyflux/inference/bbvi.py | BBVI.grad_log_q | def grad_log_q(self,z):
"""
The gradients of the approximating distributions
"""
param_count = 0
grad = np.zeros((np.sum(self.approx_param_no),self.sims))
for core_param in range(len(self.q)):
for approx_param in range(self.q[core_param].param_no):
grad[param_count] = self.q[core_param].vi_score(z[core_param],approx_param)
param_count += 1
return grad | python | def grad_log_q(self,z):
param_count = 0
grad = np.zeros((np.sum(self.approx_param_no),self.sims))
for core_param in range(len(self.q)):
for approx_param in range(self.q[core_param].param_no):
grad[param_count] = self.q[core_param].vi_score(z[core_param],approx_param)
param_count += 1
return grad | [
"def",
"grad_log_q",
"(",
"self",
",",
"z",
")",
":",
"param_count",
"=",
"0",
"grad",
"=",
"np",
".",
"zeros",
"(",
"(",
"np",
".",
"sum",
"(",
"self",
".",
"approx_param_no",
")",
",",
"self",
".",
"sims",
")",
")",
"for",
"core_param",
"in",
"... | The gradients of the approximating distributions | [
"The",
"gradients",
"of",
"the",
"approximating",
"distributions"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/inference/bbvi.py#L155-L165 |
236,359 | RJT1990/pyflux | pyflux/inference/bbvi.py | BBVIM.print_progress | def print_progress(self, i, current_params):
"""
Prints the current ELBO at every decile of total iterations
"""
for split in range(1,11):
if i == (round(self.iterations/10*split)-1):
post = -self.full_neg_posterior(current_params)
approx = self.create_normal_logq(current_params)
diff = post - approx
if not self.quiet_progress:
print(str(split) + "0% done : ELBO is " + str(diff) + ", p(y,z) is " + str(post) + ", q(z) is " + str(approx)) | python | def print_progress(self, i, current_params):
for split in range(1,11):
if i == (round(self.iterations/10*split)-1):
post = -self.full_neg_posterior(current_params)
approx = self.create_normal_logq(current_params)
diff = post - approx
if not self.quiet_progress:
print(str(split) + "0% done : ELBO is " + str(diff) + ", p(y,z) is " + str(post) + ", q(z) is " + str(approx)) | [
"def",
"print_progress",
"(",
"self",
",",
"i",
",",
"current_params",
")",
":",
"for",
"split",
"in",
"range",
"(",
"1",
",",
"11",
")",
":",
"if",
"i",
"==",
"(",
"round",
"(",
"self",
".",
"iterations",
"/",
"10",
"*",
"split",
")",
"-",
"1",
... | Prints the current ELBO at every decile of total iterations | [
"Prints",
"the",
"current",
"ELBO",
"at",
"every",
"decile",
"of",
"total",
"iterations"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/inference/bbvi.py#L441-L451 |
236,360 | RJT1990/pyflux | pyflux/inference/bbvi.py | BBVIM.run | def run(self):
"""
The core BBVI routine - draws Monte Carlo gradients and uses a stochastic optimizer.
"""
# Initialization assumptions
z = self.draw_normal_initial()
gradient = self.cv_gradient_initial(z)
gradient[np.isnan(gradient)] = 0
variance = np.power(gradient, 2)
final_parameters = self.current_parameters()
final_samples = 1
# Create optimizer
if self.optimizer == 'ADAM':
self.optim = ADAM(final_parameters, variance, self.learning_rate, 0.9, 0.999)
elif self.optimizer == 'RMSProp':
self.optim = RMSProp(final_parameters, variance, self.learning_rate, 0.99)
# Record elbo
if self.record_elbo is True:
elbo_records = np.zeros(self.iterations)
else:
elbo_records = None
for i in range(self.iterations):
x = self.draw_normal()
gradient = self.cv_gradient(x)
gradient[np.isnan(gradient)] = 0
self.change_parameters(self.optim.update(gradient))
if self.printer is True:
self.print_progress(i, self.optim.parameters[::2])
# Construct final parameters using final 10% of samples
if i > self.iterations-round(self.iterations/10):
final_samples += 1
final_parameters = final_parameters+self.optim.parameters
if self.record_elbo is True:
elbo_records[i] = self.get_elbo(self.optim.parameters[::2])
final_parameters = final_parameters/float(final_samples)
self.change_parameters(final_parameters)
final_means = np.array([final_parameters[el] for el in range(len(final_parameters)) if el%2==0])
final_ses = np.array([final_parameters[el] for el in range(len(final_parameters)) if el%2!=0])
if not self.quiet_progress:
print("")
print("Final model ELBO is " + str(-self.full_neg_posterior(final_means)-self.create_normal_logq(final_means)))
return self.q, final_means, final_ses, elbo_records | python | def run(self):
# Initialization assumptions
z = self.draw_normal_initial()
gradient = self.cv_gradient_initial(z)
gradient[np.isnan(gradient)] = 0
variance = np.power(gradient, 2)
final_parameters = self.current_parameters()
final_samples = 1
# Create optimizer
if self.optimizer == 'ADAM':
self.optim = ADAM(final_parameters, variance, self.learning_rate, 0.9, 0.999)
elif self.optimizer == 'RMSProp':
self.optim = RMSProp(final_parameters, variance, self.learning_rate, 0.99)
# Record elbo
if self.record_elbo is True:
elbo_records = np.zeros(self.iterations)
else:
elbo_records = None
for i in range(self.iterations):
x = self.draw_normal()
gradient = self.cv_gradient(x)
gradient[np.isnan(gradient)] = 0
self.change_parameters(self.optim.update(gradient))
if self.printer is True:
self.print_progress(i, self.optim.parameters[::2])
# Construct final parameters using final 10% of samples
if i > self.iterations-round(self.iterations/10):
final_samples += 1
final_parameters = final_parameters+self.optim.parameters
if self.record_elbo is True:
elbo_records[i] = self.get_elbo(self.optim.parameters[::2])
final_parameters = final_parameters/float(final_samples)
self.change_parameters(final_parameters)
final_means = np.array([final_parameters[el] for el in range(len(final_parameters)) if el%2==0])
final_ses = np.array([final_parameters[el] for el in range(len(final_parameters)) if el%2!=0])
if not self.quiet_progress:
print("")
print("Final model ELBO is " + str(-self.full_neg_posterior(final_means)-self.create_normal_logq(final_means)))
return self.q, final_means, final_ses, elbo_records | [
"def",
"run",
"(",
"self",
")",
":",
"# Initialization assumptions",
"z",
"=",
"self",
".",
"draw_normal_initial",
"(",
")",
"gradient",
"=",
"self",
".",
"cv_gradient_initial",
"(",
"z",
")",
"gradient",
"[",
"np",
".",
"isnan",
"(",
"gradient",
")",
"]",... | The core BBVI routine - draws Monte Carlo gradients and uses a stochastic optimizer. | [
"The",
"core",
"BBVI",
"routine",
"-",
"draws",
"Monte",
"Carlo",
"gradients",
"and",
"uses",
"a",
"stochastic",
"optimizer",
"."
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/inference/bbvi.py#L453-L502 |
236,361 | RJT1990/pyflux | pyflux/garch/segarchm.py | logpdf | def logpdf(x, shape, loc=0.0, scale=1.0, skewness=1.0):
"""
Log PDF for the Skew-t distribution
Parameters
----------
x : np.array
random variables
shape : float
The degrees of freedom for the skew-t distribution
loc : np.array
The location parameter for the skew-t distribution
scale : float
The scale of the distribution
skewness : float
Skewness parameter (if 1, no skewness, if > 1, +ve skew, if < 1, -ve skew)
"""
m1 = (np.sqrt(shape)*sp.gamma((shape-1.0)/2.0))/(np.sqrt(np.pi)*sp.gamma(shape/2.0))
loc = loc + (skewness - (1.0/skewness))*scale*m1
result = np.zeros(x.shape[0])
result[x-loc<0] = np.log(2.0) - np.log(skewness + 1.0/skewness) + ss.t.logpdf(x=skewness*x[(x-loc) < 0], loc=loc[(x-loc) < 0]*skewness,df=shape, scale=scale[(x-loc) < 0])
result[x-loc>=0] = np.log(2.0) - np.log(skewness + 1.0/skewness) + ss.t.logpdf(x=x[(x-loc) >= 0]/skewness, loc=loc[(x-loc) >= 0]/skewness,df=shape, scale=scale[(x-loc) >= 0])
return result | python | def logpdf(x, shape, loc=0.0, scale=1.0, skewness=1.0):
m1 = (np.sqrt(shape)*sp.gamma((shape-1.0)/2.0))/(np.sqrt(np.pi)*sp.gamma(shape/2.0))
loc = loc + (skewness - (1.0/skewness))*scale*m1
result = np.zeros(x.shape[0])
result[x-loc<0] = np.log(2.0) - np.log(skewness + 1.0/skewness) + ss.t.logpdf(x=skewness*x[(x-loc) < 0], loc=loc[(x-loc) < 0]*skewness,df=shape, scale=scale[(x-loc) < 0])
result[x-loc>=0] = np.log(2.0) - np.log(skewness + 1.0/skewness) + ss.t.logpdf(x=x[(x-loc) >= 0]/skewness, loc=loc[(x-loc) >= 0]/skewness,df=shape, scale=scale[(x-loc) >= 0])
return result | [
"def",
"logpdf",
"(",
"x",
",",
"shape",
",",
"loc",
"=",
"0.0",
",",
"scale",
"=",
"1.0",
",",
"skewness",
"=",
"1.0",
")",
":",
"m1",
"=",
"(",
"np",
".",
"sqrt",
"(",
"shape",
")",
"*",
"sp",
".",
"gamma",
"(",
"(",
"shape",
"-",
"1.0",
... | Log PDF for the Skew-t distribution
Parameters
----------
x : np.array
random variables
shape : float
The degrees of freedom for the skew-t distribution
loc : np.array
The location parameter for the skew-t distribution
scale : float
The scale of the distribution
skewness : float
Skewness parameter (if 1, no skewness, if > 1, +ve skew, if < 1, -ve skew) | [
"Log",
"PDF",
"for",
"the",
"Skew",
"-",
"t",
"distribution"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/garch/segarchm.py#L17-L44 |
236,362 | RJT1990/pyflux | pyflux/families/poisson.py | Poisson.approximating_model_reg | def approximating_model_reg(self, beta, T, Z, R, Q, h_approx, data, X, state_no):
""" Creates approximating Gaussian model for Poisson measurement density
- dynamic regression model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
T, Z, R, Q : np.array
State space matrices used in KFS algorithm
data: np.array
The univariate time series data
X: np.array
The regressors
state_no : int
Number of states
Returns
----------
H : np.array
Approximating measurement variance matrix
mu : np.array
Approximating measurement constants
"""
H = np.ones(data.shape[0])
mu = np.zeros(data.shape[0])
alpha = np.zeros([state_no, data.shape[0]])
tol = 100.0
it = 0
while tol > 10**-7 and it < 5:
old_alpha = np.sum(X*alpha.T,axis=1)
alpha, V = nld_univariate_KFS(data,Z,H,T,Q,R,mu)
H = np.exp(-np.sum(X*alpha.T,axis=1))
mu = data - np.sum(X*alpha.T,axis=1) - np.exp(-np.sum(X*alpha.T,axis=1))*(data - np.exp(np.sum(X*alpha.T,axis=1)))
tol = np.mean(np.abs(np.sum(X*alpha.T,axis=1)-old_alpha))
it += 1
return H, mu | python | def approximating_model_reg(self, beta, T, Z, R, Q, h_approx, data, X, state_no):
H = np.ones(data.shape[0])
mu = np.zeros(data.shape[0])
alpha = np.zeros([state_no, data.shape[0]])
tol = 100.0
it = 0
while tol > 10**-7 and it < 5:
old_alpha = np.sum(X*alpha.T,axis=1)
alpha, V = nld_univariate_KFS(data,Z,H,T,Q,R,mu)
H = np.exp(-np.sum(X*alpha.T,axis=1))
mu = data - np.sum(X*alpha.T,axis=1) - np.exp(-np.sum(X*alpha.T,axis=1))*(data - np.exp(np.sum(X*alpha.T,axis=1)))
tol = np.mean(np.abs(np.sum(X*alpha.T,axis=1)-old_alpha))
it += 1
return H, mu | [
"def",
"approximating_model_reg",
"(",
"self",
",",
"beta",
",",
"T",
",",
"Z",
",",
"R",
",",
"Q",
",",
"h_approx",
",",
"data",
",",
"X",
",",
"state_no",
")",
":",
"H",
"=",
"np",
".",
"ones",
"(",
"data",
".",
"shape",
"[",
"0",
"]",
")",
... | Creates approximating Gaussian model for Poisson measurement density
- dynamic regression model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
T, Z, R, Q : np.array
State space matrices used in KFS algorithm
data: np.array
The univariate time series data
X: np.array
The regressors
state_no : int
Number of states
Returns
----------
H : np.array
Approximating measurement variance matrix
mu : np.array
Approximating measurement constants | [
"Creates",
"approximating",
"Gaussian",
"model",
"for",
"Poisson",
"measurement",
"density",
"-",
"dynamic",
"regression",
"model"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/poisson.py#L86-L131 |
236,363 | RJT1990/pyflux | pyflux/families/poisson.py | Poisson.logpdf | def logpdf(self, mu):
"""
Log PDF for Poisson prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu))
"""
if self.transform is not None:
mu = self.transform(mu)
return ss.poisson.logpmf(mu, self.lmd0) | python | def logpdf(self, mu):
if self.transform is not None:
mu = self.transform(mu)
return ss.poisson.logpmf(mu, self.lmd0) | [
"def",
"logpdf",
"(",
"self",
",",
"mu",
")",
":",
"if",
"self",
".",
"transform",
"is",
"not",
"None",
":",
"mu",
"=",
"self",
".",
"transform",
"(",
"mu",
")",
"return",
"ss",
".",
"poisson",
".",
"logpmf",
"(",
"mu",
",",
"self",
".",
"lmd0",
... | Log PDF for Poisson prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu)) | [
"Log",
"PDF",
"for",
"Poisson",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/poisson.py#L198-L213 |
236,364 | RJT1990/pyflux | pyflux/families/poisson.py | Poisson.setup | def setup():
""" Returns the attributes of this family
Notes
----------
- scale notes whether family has a variance parameter (sigma)
- shape notes whether family has a tail thickness parameter (nu)
- skewness notes whether family has a skewness parameter (gamma)
- mean_transform is a function which transforms the location parameter
- cythonized notes whether the family has cythonized routines
Returns
----------
- model name, link function, scale, shape, skewness, mean_transform, cythonized
"""
name = "Poisson"
link = np.exp
scale = False
shape = False
skewness = False
mean_transform = np.log
cythonized = True
return name, link, scale, shape, skewness, mean_transform, cythonized | python | def setup():
name = "Poisson"
link = np.exp
scale = False
shape = False
skewness = False
mean_transform = np.log
cythonized = True
return name, link, scale, shape, skewness, mean_transform, cythonized | [
"def",
"setup",
"(",
")",
":",
"name",
"=",
"\"Poisson\"",
"link",
"=",
"np",
".",
"exp",
"scale",
"=",
"False",
"shape",
"=",
"False",
"skewness",
"=",
"False",
"mean_transform",
"=",
"np",
".",
"log",
"cythonized",
"=",
"True",
"return",
"name",
",",... | Returns the attributes of this family
Notes
----------
- scale notes whether family has a variance parameter (sigma)
- shape notes whether family has a tail thickness parameter (nu)
- skewness notes whether family has a skewness parameter (gamma)
- mean_transform is a function which transforms the location parameter
- cythonized notes whether the family has cythonized routines
Returns
----------
- model name, link function, scale, shape, skewness, mean_transform, cythonized | [
"Returns",
"the",
"attributes",
"of",
"this",
"family"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/poisson.py#L243-L265 |
236,365 | RJT1990/pyflux | pyflux/families/poisson.py | Poisson.pdf | def pdf(self, mu):
"""
PDF for Poisson prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- p(mu)
"""
if self.transform is not None:
mu = self.transform(mu)
return ss.poisson.pmf(mu, self.lmd0) | python | def pdf(self, mu):
if self.transform is not None:
mu = self.transform(mu)
return ss.poisson.pmf(mu, self.lmd0) | [
"def",
"pdf",
"(",
"self",
",",
"mu",
")",
":",
"if",
"self",
".",
"transform",
"is",
"not",
"None",
":",
"mu",
"=",
"self",
".",
"transform",
"(",
"mu",
")",
"return",
"ss",
".",
"poisson",
".",
"pmf",
"(",
"mu",
",",
"self",
".",
"lmd0",
")"
... | PDF for Poisson prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- p(mu) | [
"PDF",
"for",
"Poisson",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/poisson.py#L294-L309 |
236,366 | RJT1990/pyflux | pyflux/families/poisson.py | Poisson.reg_score_function | def reg_score_function(X, y, mean, scale, shape, skewness):
""" GAS Poisson Regression Update term using gradient only - native Python function
Parameters
----------
X : float
datapoint for the right hand side variable
y : float
datapoint for the time series
mean : float
location parameter for the Poisson distribution
scale : float
scale parameter for the Poisson distribution
shape : float
tail thickness parameter for the Poisson distribution
skewness : float
skewness parameter for the Poisson distribution
Returns
----------
- Score of the Poisson family
"""
return X*(y-mean) | python | def reg_score_function(X, y, mean, scale, shape, skewness):
return X*(y-mean) | [
"def",
"reg_score_function",
"(",
"X",
",",
"y",
",",
"mean",
",",
"scale",
",",
"shape",
",",
"skewness",
")",
":",
"return",
"X",
"*",
"(",
"y",
"-",
"mean",
")"
] | GAS Poisson Regression Update term using gradient only - native Python function
Parameters
----------
X : float
datapoint for the right hand side variable
y : float
datapoint for the time series
mean : float
location parameter for the Poisson distribution
scale : float
scale parameter for the Poisson distribution
shape : float
tail thickness parameter for the Poisson distribution
skewness : float
skewness parameter for the Poisson distribution
Returns
----------
- Score of the Poisson family | [
"GAS",
"Poisson",
"Regression",
"Update",
"term",
"using",
"gradient",
"only",
"-",
"native",
"Python",
"function"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/poisson.py#L312-L339 |
236,367 | RJT1990/pyflux | pyflux/families/poisson.py | Poisson.second_order_score | def second_order_score(y, mean, scale, shape, skewness):
""" GAS Poisson Update term potentially using second-order information - native Python function
Parameters
----------
y : float
datapoint for the time series
mean : float
location parameter for the Poisson distribution
scale : float
scale parameter for the Poisson distribution
shape : float
tail thickness parameter for the Poisson distribution
skewness : float
skewness parameter for the Poisson distribution
Returns
----------
- Adjusted score of the Poisson family
"""
return (y-mean)/float(mean) | python | def second_order_score(y, mean, scale, shape, skewness):
return (y-mean)/float(mean) | [
"def",
"second_order_score",
"(",
"y",
",",
"mean",
",",
"scale",
",",
"shape",
",",
"skewness",
")",
":",
"return",
"(",
"y",
"-",
"mean",
")",
"/",
"float",
"(",
"mean",
")"
] | GAS Poisson Update term potentially using second-order information - native Python function
Parameters
----------
y : float
datapoint for the time series
mean : float
location parameter for the Poisson distribution
scale : float
scale parameter for the Poisson distribution
shape : float
tail thickness parameter for the Poisson distribution
skewness : float
skewness parameter for the Poisson distribution
Returns
----------
- Adjusted score of the Poisson family | [
"GAS",
"Poisson",
"Update",
"term",
"potentially",
"using",
"second",
"-",
"order",
"information",
"-",
"native",
"Python",
"function"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/poisson.py#L342-L366 |
236,368 | RJT1990/pyflux | pyflux/families/inverse_gamma.py | InverseGamma.logpdf | def logpdf(self, x):
"""
Log PDF for Inverse Gamma prior
Parameters
----------
x : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(x))
"""
if self.transform is not None:
x = self.transform(x)
return (-self.alpha-1)*np.log(x) - (self.beta/float(x)) | python | def logpdf(self, x):
if self.transform is not None:
x = self.transform(x)
return (-self.alpha-1)*np.log(x) - (self.beta/float(x)) | [
"def",
"logpdf",
"(",
"self",
",",
"x",
")",
":",
"if",
"self",
".",
"transform",
"is",
"not",
"None",
":",
"x",
"=",
"self",
".",
"transform",
"(",
"x",
")",
"return",
"(",
"-",
"self",
".",
"alpha",
"-",
"1",
")",
"*",
"np",
".",
"log",
"("... | Log PDF for Inverse Gamma prior
Parameters
----------
x : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(x)) | [
"Log",
"PDF",
"for",
"Inverse",
"Gamma",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/inverse_gamma.py#L33-L48 |
236,369 | RJT1990/pyflux | pyflux/families/inverse_gamma.py | InverseGamma.pdf | def pdf(self, x):
"""
PDF for Inverse Gamma prior
Parameters
----------
x : float
Latent variable for which the prior is being formed over
Returns
----------
- p(x)
"""
if self.transform is not None:
x = self.transform(x)
return (x**(-self.alpha-1))*np.exp(-(self.beta/float(x))) | python | def pdf(self, x):
if self.transform is not None:
x = self.transform(x)
return (x**(-self.alpha-1))*np.exp(-(self.beta/float(x))) | [
"def",
"pdf",
"(",
"self",
",",
"x",
")",
":",
"if",
"self",
".",
"transform",
"is",
"not",
"None",
":",
"x",
"=",
"self",
".",
"transform",
"(",
"x",
")",
"return",
"(",
"x",
"**",
"(",
"-",
"self",
".",
"alpha",
"-",
"1",
")",
")",
"*",
"... | PDF for Inverse Gamma prior
Parameters
----------
x : float
Latent variable for which the prior is being formed over
Returns
----------
- p(x) | [
"PDF",
"for",
"Inverse",
"Gamma",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/inverse_gamma.py#L50-L65 |
236,370 | RJT1990/pyflux | pyflux/families/cauchy.py | Cauchy.logpdf | def logpdf(self, mu):
"""
Log PDF for Cauchy prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu))
"""
if self.transform is not None:
mu = self.transform(mu)
return ss.cauchy.logpdf(mu, self.loc0, self.scale0) | python | def logpdf(self, mu):
if self.transform is not None:
mu = self.transform(mu)
return ss.cauchy.logpdf(mu, self.loc0, self.scale0) | [
"def",
"logpdf",
"(",
"self",
",",
"mu",
")",
":",
"if",
"self",
".",
"transform",
"is",
"not",
"None",
":",
"mu",
"=",
"self",
".",
"transform",
"(",
"mu",
")",
"return",
"ss",
".",
"cauchy",
".",
"logpdf",
"(",
"mu",
",",
"self",
".",
"loc0",
... | Log PDF for Cauchy prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu)) | [
"Log",
"PDF",
"for",
"Cauchy",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/cauchy.py#L155-L170 |
236,371 | RJT1990/pyflux | pyflux/families/cauchy.py | Cauchy.pdf | def pdf(self, mu):
"""
PDF for Cauchy prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- p(mu)
"""
return ss.cauchy.pdf(mu, self.loc0, self.scale0) | python | def pdf(self, mu):
return ss.cauchy.pdf(mu, self.loc0, self.scale0) | [
"def",
"pdf",
"(",
"self",
",",
"mu",
")",
":",
"return",
"ss",
".",
"cauchy",
".",
"pdf",
"(",
"mu",
",",
"self",
".",
"loc0",
",",
"self",
".",
"scale0",
")"
] | PDF for Cauchy prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- p(mu) | [
"PDF",
"for",
"Cauchy",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/cauchy.py#L172-L185 |
236,372 | RJT1990/pyflux | pyflux/families/cauchy.py | Cauchy.markov_blanket | def markov_blanket(y, mean, scale, shape, skewness):
""" Markov blanket for each likelihood term - used for state space models
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Cauchy distribution
scale : float
scale parameter for the Cauchy distribution
shape : float
tail thickness parameter for the Cauchy distribution
skewness : float
skewness parameter for the Cauchy distribution
Returns
----------
- Markov blanket of the Cauchy family
"""
return ss.cauchy.logpdf(y, loc=mean, scale=scale) | python | def markov_blanket(y, mean, scale, shape, skewness):
return ss.cauchy.logpdf(y, loc=mean, scale=scale) | [
"def",
"markov_blanket",
"(",
"y",
",",
"mean",
",",
"scale",
",",
"shape",
",",
"skewness",
")",
":",
"return",
"ss",
".",
"cauchy",
".",
"logpdf",
"(",
"y",
",",
"loc",
"=",
"mean",
",",
"scale",
"=",
"scale",
")"
] | Markov blanket for each likelihood term - used for state space models
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Cauchy distribution
scale : float
scale parameter for the Cauchy distribution
shape : float
tail thickness parameter for the Cauchy distribution
skewness : float
skewness parameter for the Cauchy distribution
Returns
----------
- Markov blanket of the Cauchy family | [
"Markov",
"blanket",
"for",
"each",
"likelihood",
"term",
"-",
"used",
"for",
"state",
"space",
"models"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/cauchy.py#L188-L212 |
236,373 | RJT1990/pyflux | pyflux/families/cauchy.py | Cauchy.setup | def setup():
""" Returns the attributes of this family if using in a probabilistic model
Notes
----------
- scale notes whether family has a variance parameter (sigma)
- shape notes whether family has a tail thickness parameter (nu)
- skewness notes whether family has a skewness parameter (gamma)
- mean_transform is a function which transforms the location parameter
- cythonized notes whether the family has cythonized routines
Returns
----------
- model name, link function, scale, shape, skewness, mean_transform, cythonized
"""
name = "Cauchy"
link = np.array
scale = True
shape = False
skewness = False
mean_transform = np.array
cythonized = True # used for GAS models
return name, link, scale, shape, skewness, mean_transform, cythonized | python | def setup():
name = "Cauchy"
link = np.array
scale = True
shape = False
skewness = False
mean_transform = np.array
cythonized = True # used for GAS models
return name, link, scale, shape, skewness, mean_transform, cythonized | [
"def",
"setup",
"(",
")",
":",
"name",
"=",
"\"Cauchy\"",
"link",
"=",
"np",
".",
"array",
"scale",
"=",
"True",
"shape",
"=",
"False",
"skewness",
"=",
"False",
"mean_transform",
"=",
"np",
".",
"array",
"cythonized",
"=",
"True",
"# used for GAS models",... | Returns the attributes of this family if using in a probabilistic model
Notes
----------
- scale notes whether family has a variance parameter (sigma)
- shape notes whether family has a tail thickness parameter (nu)
- skewness notes whether family has a skewness parameter (gamma)
- mean_transform is a function which transforms the location parameter
- cythonized notes whether the family has cythonized routines
Returns
----------
- model name, link function, scale, shape, skewness, mean_transform, cythonized | [
"Returns",
"the",
"attributes",
"of",
"this",
"family",
"if",
"using",
"in",
"a",
"probabilistic",
"model"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/cauchy.py#L215-L237 |
236,374 | RJT1990/pyflux | pyflux/families/cauchy.py | Cauchy.neg_loglikelihood | def neg_loglikelihood(y, mean, scale, shape, skewness):
""" Negative loglikelihood function for this distribution
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Cauchy distribution
scale : float
scale parameter for the Cauchy distribution
shape : float
tail thickness parameter for the Cauchy distribution
skewness : float
skewness parameter for the Cauchy distribution
Returns
----------
- Negative loglikelihood of the Cauchy family
"""
return -np.sum(ss.cauchy.logpdf(y, loc=mean, scale=scale)) | python | def neg_loglikelihood(y, mean, scale, shape, skewness):
return -np.sum(ss.cauchy.logpdf(y, loc=mean, scale=scale)) | [
"def",
"neg_loglikelihood",
"(",
"y",
",",
"mean",
",",
"scale",
",",
"shape",
",",
"skewness",
")",
":",
"return",
"-",
"np",
".",
"sum",
"(",
"ss",
".",
"cauchy",
".",
"logpdf",
"(",
"y",
",",
"loc",
"=",
"mean",
",",
"scale",
"=",
"scale",
")"... | Negative loglikelihood function for this distribution
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Cauchy distribution
scale : float
scale parameter for the Cauchy distribution
shape : float
tail thickness parameter for the Cauchy distribution
skewness : float
skewness parameter for the Cauchy distribution
Returns
----------
- Negative loglikelihood of the Cauchy family | [
"Negative",
"loglikelihood",
"function",
"for",
"this",
"distribution"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/cauchy.py#L294-L318 |
236,375 | RJT1990/pyflux | pyflux/families/cauchy.py | Cauchy.reg_score_function | def reg_score_function(X, y, mean, scale, shape, skewness):
""" GAS Cauchy Regression Update term using gradient only - native Python function
Parameters
----------
X : float
datapoint for the right hand side variable
y : float
datapoint for the time series
mean : float
location parameter for the Cauchy distribution
scale : float
scale parameter for the Cauchy distribution
shape : float
tail thickness parameter for the Cauchy distribution
skewness : float
skewness parameter for the Cauchy distribution
Returns
----------
- Score of the Cauchy family
"""
return 2.0*((y-mean)*X)/(np.power(scale,2)+np.power((y-mean),2)) | python | def reg_score_function(X, y, mean, scale, shape, skewness):
return 2.0*((y-mean)*X)/(np.power(scale,2)+np.power((y-mean),2)) | [
"def",
"reg_score_function",
"(",
"X",
",",
"y",
",",
"mean",
",",
"scale",
",",
"shape",
",",
"skewness",
")",
":",
"return",
"2.0",
"*",
"(",
"(",
"y",
"-",
"mean",
")",
"*",
"X",
")",
"/",
"(",
"np",
".",
"power",
"(",
"scale",
",",
"2",
"... | GAS Cauchy Regression Update term using gradient only - native Python function
Parameters
----------
X : float
datapoint for the right hand side variable
y : float
datapoint for the time series
mean : float
location parameter for the Cauchy distribution
scale : float
scale parameter for the Cauchy distribution
shape : float
tail thickness parameter for the Cauchy distribution
skewness : float
skewness parameter for the Cauchy distribution
Returns
----------
- Score of the Cauchy family | [
"GAS",
"Cauchy",
"Regression",
"Update",
"term",
"using",
"gradient",
"only",
"-",
"native",
"Python",
"function"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/cauchy.py#L322-L349 |
236,376 | RJT1990/pyflux | pyflux/arma/nnarx.py | NNARX.general_neg_loglik | def general_neg_loglik(self, beta):
""" Calculates the negative log-likelihood of the model
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for latent variables
Returns
----------
The negative logliklihood of the model
"""
mu, Y = self._model(beta)
parm = np.array([self.latent_variables.z_list[k].prior.transform(beta[k]) for k in range(beta.shape[0])])
#TODO: Replace above with transformation that only acts on scale, shape, skewness in future (speed-up)
model_scale, model_shape, model_skewness = self._get_scale_and_shape(parm)
return self.family.neg_loglikelihood(Y, self.link(mu), model_scale, model_shape, model_skewness) | python | def general_neg_loglik(self, beta):
mu, Y = self._model(beta)
parm = np.array([self.latent_variables.z_list[k].prior.transform(beta[k]) for k in range(beta.shape[0])])
#TODO: Replace above with transformation that only acts on scale, shape, skewness in future (speed-up)
model_scale, model_shape, model_skewness = self._get_scale_and_shape(parm)
return self.family.neg_loglikelihood(Y, self.link(mu), model_scale, model_shape, model_skewness) | [
"def",
"general_neg_loglik",
"(",
"self",
",",
"beta",
")",
":",
"mu",
",",
"Y",
"=",
"self",
".",
"_model",
"(",
"beta",
")",
"parm",
"=",
"np",
".",
"array",
"(",
"[",
"self",
".",
"latent_variables",
".",
"z_list",
"[",
"k",
"]",
".",
"prior",
... | Calculates the negative log-likelihood of the model
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for latent variables
Returns
----------
The negative logliklihood of the model | [
"Calculates",
"the",
"negative",
"log",
"-",
"likelihood",
"of",
"the",
"model"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/arma/nnarx.py#L430-L447 |
236,377 | RJT1990/pyflux | pyflux/arma/nnarx.py | NNARX.plot_fit | def plot_fit(self, **kwargs):
"""
Plots the fit of the model against the data
"""
import matplotlib.pyplot as plt
import seaborn as sns
figsize = kwargs.get('figsize',(10,7))
plt.figure(figsize=figsize)
date_index = self.index[self.ar:self.data.shape[0]]
mu, Y = self._model(self.latent_variables.get_z_values())
plt.plot(date_index,Y,label='Data')
plt.plot(date_index,mu,label='Filter',c='black')
plt.title(self.data_name)
plt.legend(loc=2)
plt.show() | python | def plot_fit(self, **kwargs):
import matplotlib.pyplot as plt
import seaborn as sns
figsize = kwargs.get('figsize',(10,7))
plt.figure(figsize=figsize)
date_index = self.index[self.ar:self.data.shape[0]]
mu, Y = self._model(self.latent_variables.get_z_values())
plt.plot(date_index,Y,label='Data')
plt.plot(date_index,mu,label='Filter',c='black')
plt.title(self.data_name)
plt.legend(loc=2)
plt.show() | [
"def",
"plot_fit",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"import",
"seaborn",
"as",
"sns",
"figsize",
"=",
"kwargs",
".",
"get",
"(",
"'figsize'",
",",
"(",
"10",
",",
"7",
")",
")",
"pl... | Plots the fit of the model against the data | [
"Plots",
"the",
"fit",
"of",
"the",
"model",
"against",
"the",
"data"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/arma/nnarx.py#L487-L503 |
236,378 | RJT1990/pyflux | pyflux/arma/nnarx.py | NNARX.predict_is | def predict_is(self, h=5, fit_once=True, fit_method='MLE', intervals=False, **kwargs):
""" Makes dynamic out-of-sample predictions with the estimated model on in-sample data
Parameters
----------
h : int (default : 5)
How many steps would you like to forecast?
fit_once : boolean
(default: True) Fits only once before the in-sample prediction; if False, fits after every new datapoint
fit_method : string
Which method to fit the model with
intervals: boolean
Whether to return prediction intervals
Returns
----------
- pd.DataFrame with predicted values
"""
predictions = []
for t in range(0,h):
x = NNAR(ar=self.ar, units=self.units,
layers=self.layers, data=self.data_original[:-h+t], family=self.family)
if fit_once is False:
x.fit(method=fit_method, printer=False)
if t == 0:
if fit_once is True:
x.fit(method=fit_method, printer=False)
saved_lvs = x.latent_variables
predictions = x.predict(1, intervals=intervals)
else:
if fit_once is True:
x.latent_variables = saved_lvs
predictions = pd.concat([predictions,x.predict(1, intervals=intervals)])
if intervals is True:
predictions.rename(columns={0:self.data_name, 1: "1% Prediction Interval",
2: "5% Prediction Interval", 3: "95% Prediction Interval", 4: "99% Prediction Interval"}, inplace=True)
else:
predictions.rename(columns={0:self.data_name}, inplace=True)
predictions.index = self.index[-h:]
return predictions | python | def predict_is(self, h=5, fit_once=True, fit_method='MLE', intervals=False, **kwargs):
predictions = []
for t in range(0,h):
x = NNAR(ar=self.ar, units=self.units,
layers=self.layers, data=self.data_original[:-h+t], family=self.family)
if fit_once is False:
x.fit(method=fit_method, printer=False)
if t == 0:
if fit_once is True:
x.fit(method=fit_method, printer=False)
saved_lvs = x.latent_variables
predictions = x.predict(1, intervals=intervals)
else:
if fit_once is True:
x.latent_variables = saved_lvs
predictions = pd.concat([predictions,x.predict(1, intervals=intervals)])
if intervals is True:
predictions.rename(columns={0:self.data_name, 1: "1% Prediction Interval",
2: "5% Prediction Interval", 3: "95% Prediction Interval", 4: "99% Prediction Interval"}, inplace=True)
else:
predictions.rename(columns={0:self.data_name}, inplace=True)
predictions.index = self.index[-h:]
return predictions | [
"def",
"predict_is",
"(",
"self",
",",
"h",
"=",
"5",
",",
"fit_once",
"=",
"True",
",",
"fit_method",
"=",
"'MLE'",
",",
"intervals",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"predictions",
"=",
"[",
"]",
"for",
"t",
"in",
"range",
"(",
... | Makes dynamic out-of-sample predictions with the estimated model on in-sample data
Parameters
----------
h : int (default : 5)
How many steps would you like to forecast?
fit_once : boolean
(default: True) Fits only once before the in-sample prediction; if False, fits after every new datapoint
fit_method : string
Which method to fit the model with
intervals: boolean
Whether to return prediction intervals
Returns
----------
- pd.DataFrame with predicted values | [
"Makes",
"dynamic",
"out",
"-",
"of",
"-",
"sample",
"predictions",
"with",
"the",
"estimated",
"model",
"on",
"in",
"-",
"sample",
"data"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/arma/nnarx.py#L557-L603 |
236,379 | RJT1990/pyflux | pyflux/ssm/nllm.py | NLLEV.likelihood_markov_blanket | def likelihood_markov_blanket(self, beta):
""" Creates likelihood markov blanket of the model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
- Negative loglikelihood
"""
states = beta[self.z_no:self.z_no+self.data_length] # the local level (untransformed)
parm = np.array([self.latent_variables.z_list[k].prior.transform(beta[k]) for k in range(self.z_no)]) # transformed distribution parameters
scale, shape, skewness = self._get_scale_and_shape(parm)
return self.family.markov_blanket(self.data, self.link(states), scale, shape, skewness) | python | def likelihood_markov_blanket(self, beta):
states = beta[self.z_no:self.z_no+self.data_length] # the local level (untransformed)
parm = np.array([self.latent_variables.z_list[k].prior.transform(beta[k]) for k in range(self.z_no)]) # transformed distribution parameters
scale, shape, skewness = self._get_scale_and_shape(parm)
return self.family.markov_blanket(self.data, self.link(states), scale, shape, skewness) | [
"def",
"likelihood_markov_blanket",
"(",
"self",
",",
"beta",
")",
":",
"states",
"=",
"beta",
"[",
"self",
".",
"z_no",
":",
"self",
".",
"z_no",
"+",
"self",
".",
"data_length",
"]",
"# the local level (untransformed)",
"parm",
"=",
"np",
".",
"array",
"... | Creates likelihood markov blanket of the model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
- Negative loglikelihood | [
"Creates",
"likelihood",
"markov",
"blanket",
"of",
"the",
"model"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/nllm.py#L135-L150 |
236,380 | RJT1990/pyflux | pyflux/ssm/nllm.py | NLLEV._animate_bbvi | def _animate_bbvi(self,stored_latent_variables,stored_predictive_likelihood):
""" Produces animated plot of BBVI optimization
Returns
----------
None (changes model attributes)
"""
from matplotlib.animation import FuncAnimation, writers
import matplotlib.pyplot as plt
import seaborn as sns
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ud = BBVINLLMAnimate(ax,self.data,stored_latent_variables,self.index,self.z_no,self.link)
anim = FuncAnimation(fig, ud, frames=np.arange(stored_latent_variables.shape[0]), init_func=ud.init,
interval=10, blit=True)
plt.plot(self.data)
plt.xlabel("Time")
plt.ylabel(self.data_name)
plt.show() | python | def _animate_bbvi(self,stored_latent_variables,stored_predictive_likelihood):
from matplotlib.animation import FuncAnimation, writers
import matplotlib.pyplot as plt
import seaborn as sns
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ud = BBVINLLMAnimate(ax,self.data,stored_latent_variables,self.index,self.z_no,self.link)
anim = FuncAnimation(fig, ud, frames=np.arange(stored_latent_variables.shape[0]), init_func=ud.init,
interval=10, blit=True)
plt.plot(self.data)
plt.xlabel("Time")
plt.ylabel(self.data_name)
plt.show() | [
"def",
"_animate_bbvi",
"(",
"self",
",",
"stored_latent_variables",
",",
"stored_predictive_likelihood",
")",
":",
"from",
"matplotlib",
".",
"animation",
"import",
"FuncAnimation",
",",
"writers",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"import",
"seab... | Produces animated plot of BBVI optimization
Returns
----------
None (changes model attributes) | [
"Produces",
"animated",
"plot",
"of",
"BBVI",
"optimization"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/nllm.py#L278-L298 |
236,381 | RJT1990/pyflux | pyflux/ssm/nllm.py | NLLEV.initialize_approx_dist | def initialize_approx_dist(self, phi, start_diffuse, gaussian_latents):
""" Initializes the appoximate distibution for the model
Parameters
----------
phi : np.ndarray
Latent variables
start_diffuse: boolean
Whether to start from diffuse values or not
gaussian_latents: LatentVariables object
Latent variables for the Gaussian approximation
Returns
----------
BBVI fit object
"""
# Starting values for approximate distribution
for i in range(len(self.latent_variables.z_list)):
approx_dist = self.latent_variables.z_list[i].q
if isinstance(approx_dist, fam.Normal):
self.latent_variables.z_list[i].q.mu0 = phi[i]
self.latent_variables.z_list[i].q.sigma0 = np.exp(-3.0)
q_list = [k.q for k in self.latent_variables.z_list]
# Get starting values for states
T, Z, R, Q = self._ss_matrices(phi)
H, mu = self.family.approximating_model(phi, T, Z, R, Q, gaussian_latents.get_z_values(transformed=True)[0], self.data)
a, V = self.smoothed_state(self.data, phi, H, mu)
V[0][0][0] = V[0][0][-1]
for item in range(self.data_length):
if start_diffuse is False:
q_list.append(fam.Normal(a[0][item], np.sqrt(np.abs(V[0][0][item]))))
else:
q_list.append(fam.Normal(self.family.itransform(np.mean(self.data)), np.sqrt(np.abs(V[0][0][item]))))
return q_list | python | def initialize_approx_dist(self, phi, start_diffuse, gaussian_latents):
# Starting values for approximate distribution
for i in range(len(self.latent_variables.z_list)):
approx_dist = self.latent_variables.z_list[i].q
if isinstance(approx_dist, fam.Normal):
self.latent_variables.z_list[i].q.mu0 = phi[i]
self.latent_variables.z_list[i].q.sigma0 = np.exp(-3.0)
q_list = [k.q for k in self.latent_variables.z_list]
# Get starting values for states
T, Z, R, Q = self._ss_matrices(phi)
H, mu = self.family.approximating_model(phi, T, Z, R, Q, gaussian_latents.get_z_values(transformed=True)[0], self.data)
a, V = self.smoothed_state(self.data, phi, H, mu)
V[0][0][0] = V[0][0][-1]
for item in range(self.data_length):
if start_diffuse is False:
q_list.append(fam.Normal(a[0][item], np.sqrt(np.abs(V[0][0][item]))))
else:
q_list.append(fam.Normal(self.family.itransform(np.mean(self.data)), np.sqrt(np.abs(V[0][0][item]))))
return q_list | [
"def",
"initialize_approx_dist",
"(",
"self",
",",
"phi",
",",
"start_diffuse",
",",
"gaussian_latents",
")",
":",
"# Starting values for approximate distribution",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"latent_variables",
".",
"z_list",
")",
")... | Initializes the appoximate distibution for the model
Parameters
----------
phi : np.ndarray
Latent variables
start_diffuse: boolean
Whether to start from diffuse values or not
gaussian_latents: LatentVariables object
Latent variables for the Gaussian approximation
Returns
----------
BBVI fit object | [
"Initializes",
"the",
"appoximate",
"distibution",
"for",
"the",
"model"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/nllm.py#L442-L482 |
236,382 | RJT1990/pyflux | pyflux/families/t.py | t.logpdf | def logpdf(self, mu):
"""
Log PDF for t prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu))
"""
if self.transform is not None:
mu = self.transform(mu)
return ss.t.logpdf(mu, df=self.df0, loc=self.loc0, scale=self.scale0) | python | def logpdf(self, mu):
if self.transform is not None:
mu = self.transform(mu)
return ss.t.logpdf(mu, df=self.df0, loc=self.loc0, scale=self.scale0) | [
"def",
"logpdf",
"(",
"self",
",",
"mu",
")",
":",
"if",
"self",
".",
"transform",
"is",
"not",
"None",
":",
"mu",
"=",
"self",
".",
"transform",
"(",
"mu",
")",
"return",
"ss",
".",
"t",
".",
"logpdf",
"(",
"mu",
",",
"df",
"=",
"self",
".",
... | Log PDF for t prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu)) | [
"Log",
"PDF",
"for",
"t",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/t.py#L186-L201 |
236,383 | RJT1990/pyflux | pyflux/families/t.py | t.second_order_score | def second_order_score(y, mean, scale, shape, skewness):
""" GAS t Update term potentially using second-order information - native Python function
Parameters
----------
y : float
datapoint for the time series
mean : float
location parameter for the t distribution
scale : float
scale parameter for the t distribution
shape : float
tail thickness parameter for the t distribution
skewness : float
skewness parameter for the t distribution
Returns
----------
- Adjusted score of the t family
"""
return ((shape+1)/shape)*(y-mean)/(np.power(scale,2) + (np.power(y-mean,2)/shape))/((shape+1)*((np.power(scale,2)*shape) - np.power(y-mean,2))/np.power((np.power(scale,2)*shape) + np.power(y-mean,2),2)) | python | def second_order_score(y, mean, scale, shape, skewness):
return ((shape+1)/shape)*(y-mean)/(np.power(scale,2) + (np.power(y-mean,2)/shape))/((shape+1)*((np.power(scale,2)*shape) - np.power(y-mean,2))/np.power((np.power(scale,2)*shape) + np.power(y-mean,2),2)) | [
"def",
"second_order_score",
"(",
"y",
",",
"mean",
",",
"scale",
",",
"shape",
",",
"skewness",
")",
":",
"return",
"(",
"(",
"shape",
"+",
"1",
")",
"/",
"shape",
")",
"*",
"(",
"y",
"-",
"mean",
")",
"/",
"(",
"np",
".",
"power",
"(",
"scale... | GAS t Update term potentially using second-order information - native Python function
Parameters
----------
y : float
datapoint for the time series
mean : float
location parameter for the t distribution
scale : float
scale parameter for the t distribution
shape : float
tail thickness parameter for the t distribution
skewness : float
skewness parameter for the t distribution
Returns
----------
- Adjusted score of the t family | [
"GAS",
"t",
"Update",
"term",
"potentially",
"using",
"second",
"-",
"order",
"information",
"-",
"native",
"Python",
"function"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/t.py#L330-L354 |
236,384 | RJT1990/pyflux | tools/cythonize.py | load_hashes | def load_hashes(filename):
"""Load the hashes dict from the hashfile"""
# { filename : (sha1 of header if available or 'NA',
# sha1 of input,
# sha1 of output) }
hashes = {}
try:
with open(filename, 'r') as cython_hash_file:
for hash_record in cython_hash_file:
(filename, header_hash,
cython_hash, gen_file_hash) = hash_record.split()
hashes[filename] = (header_hash, cython_hash, gen_file_hash)
except (KeyError, ValueError, AttributeError, IOError):
hashes = {}
return hashes | python | def load_hashes(filename):
# { filename : (sha1 of header if available or 'NA',
# sha1 of input,
# sha1 of output) }
hashes = {}
try:
with open(filename, 'r') as cython_hash_file:
for hash_record in cython_hash_file:
(filename, header_hash,
cython_hash, gen_file_hash) = hash_record.split()
hashes[filename] = (header_hash, cython_hash, gen_file_hash)
except (KeyError, ValueError, AttributeError, IOError):
hashes = {}
return hashes | [
"def",
"load_hashes",
"(",
"filename",
")",
":",
"# { filename : (sha1 of header if available or 'NA',",
"# sha1 of input,",
"# sha1 of output) }",
"hashes",
"=",
"{",
"}",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"... | Load the hashes dict from the hashfile | [
"Load",
"the",
"hashes",
"dict",
"from",
"the",
"hashfile"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/tools/cythonize.py#L81-L96 |
236,385 | RJT1990/pyflux | tools/cythonize.py | save_hashes | def save_hashes(hashes, filename):
"""Save the hashes dict to the hashfile"""
with open(filename, 'w') as cython_hash_file:
for key, value in hashes.items():
cython_hash_file.write("%s %s %s %s\n"
% (key, value[0], value[1], value[2])) | python | def save_hashes(hashes, filename):
with open(filename, 'w') as cython_hash_file:
for key, value in hashes.items():
cython_hash_file.write("%s %s %s %s\n"
% (key, value[0], value[1], value[2])) | [
"def",
"save_hashes",
"(",
"hashes",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"cython_hash_file",
":",
"for",
"key",
",",
"value",
"in",
"hashes",
".",
"items",
"(",
")",
":",
"cython_hash_file",
".",
"write",
... | Save the hashes dict to the hashfile | [
"Save",
"the",
"hashes",
"dict",
"to",
"the",
"hashfile"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/tools/cythonize.py#L99-L104 |
236,386 | RJT1990/pyflux | tools/cythonize.py | clean_path | def clean_path(path):
"""Clean the path"""
path = path.replace(os.sep, '/')
if path.startswith('./'):
path = path[2:]
return path | python | def clean_path(path):
path = path.replace(os.sep, '/')
if path.startswith('./'):
path = path[2:]
return path | [
"def",
"clean_path",
"(",
"path",
")",
":",
"path",
"=",
"path",
".",
"replace",
"(",
"os",
".",
"sep",
",",
"'/'",
")",
"if",
"path",
".",
"startswith",
"(",
"'./'",
")",
":",
"path",
"=",
"path",
"[",
"2",
":",
"]",
"return",
"path"
] | Clean the path | [
"Clean",
"the",
"path"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/tools/cythonize.py#L114-L119 |
236,387 | RJT1990/pyflux | tools/cythonize.py | get_hash_tuple | def get_hash_tuple(header_path, cython_path, gen_file_path):
"""Get the hashes from the given files"""
header_hash = (sha1_of_file(header_path)
if os.path.exists(header_path) else 'NA')
from_hash = sha1_of_file(cython_path)
to_hash = (sha1_of_file(gen_file_path)
if os.path.exists(gen_file_path) else 'NA')
return header_hash, from_hash, to_hash | python | def get_hash_tuple(header_path, cython_path, gen_file_path):
header_hash = (sha1_of_file(header_path)
if os.path.exists(header_path) else 'NA')
from_hash = sha1_of_file(cython_path)
to_hash = (sha1_of_file(gen_file_path)
if os.path.exists(gen_file_path) else 'NA')
return header_hash, from_hash, to_hash | [
"def",
"get_hash_tuple",
"(",
"header_path",
",",
"cython_path",
",",
"gen_file_path",
")",
":",
"header_hash",
"=",
"(",
"sha1_of_file",
"(",
"header_path",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"header_path",
")",
"else",
"'NA'",
")",
"from_has... | Get the hashes from the given files | [
"Get",
"the",
"hashes",
"from",
"the",
"given",
"files"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/tools/cythonize.py#L122-L131 |
236,388 | RJT1990/pyflux | pyflux/families/truncated_normal.py | TruncatedNormal.logpdf | def logpdf(self, mu):
"""
Log PDF for Truncated Normal prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu))
"""
if self.transform is not None:
mu = self.transform(mu)
if mu < self.lower and self.lower is not None:
return -10.0**6
elif mu > self.upper and self.upper is not None:
return -10.0**6
else:
return -np.log(float(self.sigma0)) - (0.5*(mu-self.mu0)**2)/float(self.sigma0**2) | python | def logpdf(self, mu):
if self.transform is not None:
mu = self.transform(mu)
if mu < self.lower and self.lower is not None:
return -10.0**6
elif mu > self.upper and self.upper is not None:
return -10.0**6
else:
return -np.log(float(self.sigma0)) - (0.5*(mu-self.mu0)**2)/float(self.sigma0**2) | [
"def",
"logpdf",
"(",
"self",
",",
"mu",
")",
":",
"if",
"self",
".",
"transform",
"is",
"not",
"None",
":",
"mu",
"=",
"self",
".",
"transform",
"(",
"mu",
")",
"if",
"mu",
"<",
"self",
".",
"lower",
"and",
"self",
".",
"lower",
"is",
"not",
"... | Log PDF for Truncated Normal prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu)) | [
"Log",
"PDF",
"for",
"Truncated",
"Normal",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/truncated_normal.py#L42-L62 |
236,389 | RJT1990/pyflux | pyflux/families/truncated_normal.py | TruncatedNormal.pdf | def pdf(self, mu):
"""
PDF for Truncated Normal prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- p(mu)
"""
if self.transform is not None:
mu = self.transform(mu)
if mu < self.lower and self.lower is not None:
return 0.0
elif mu > self.upper and self.upper is not None:
return 0.0
else:
return (1/float(self.sigma0))*np.exp(-(0.5*(mu-self.mu0)**2)/float(self.sigma0**2)) | python | def pdf(self, mu):
if self.transform is not None:
mu = self.transform(mu)
if mu < self.lower and self.lower is not None:
return 0.0
elif mu > self.upper and self.upper is not None:
return 0.0
else:
return (1/float(self.sigma0))*np.exp(-(0.5*(mu-self.mu0)**2)/float(self.sigma0**2)) | [
"def",
"pdf",
"(",
"self",
",",
"mu",
")",
":",
"if",
"self",
".",
"transform",
"is",
"not",
"None",
":",
"mu",
"=",
"self",
".",
"transform",
"(",
"mu",
")",
"if",
"mu",
"<",
"self",
".",
"lower",
"and",
"self",
".",
"lower",
"is",
"not",
"Non... | PDF for Truncated Normal prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- p(mu) | [
"PDF",
"for",
"Truncated",
"Normal",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/truncated_normal.py#L64-L84 |
236,390 | RJT1990/pyflux | pyflux/inference/metropolis_hastings.py | MetropolisHastings.tune_scale | def tune_scale(acceptance, scale):
""" Tunes scale for M-H algorithm
Parameters
----------
acceptance : float
The most recent acceptance rate
scale : float
The current scale parameter
Returns
----------
scale : float
An adjusted scale parameter
Notes
----------
Ross : Initially did this by trial and error, then refined by looking at other
implementations, so some credit here to PyMC3 which became a guideline for this.
"""
if acceptance > 0.8:
scale *= 2.0
elif acceptance <= 0.8 and acceptance > 0.4:
scale *= 1.3
elif acceptance < 0.234 and acceptance > 0.1:
scale *= (1/1.3)
elif acceptance <= 0.1 and acceptance > 0.05:
scale *= 0.4
elif acceptance <= 0.05 and acceptance > 0.01:
scale *= 0.2
elif acceptance <= 0.01:
scale *= 0.1
return scale | python | def tune_scale(acceptance, scale):
if acceptance > 0.8:
scale *= 2.0
elif acceptance <= 0.8 and acceptance > 0.4:
scale *= 1.3
elif acceptance < 0.234 and acceptance > 0.1:
scale *= (1/1.3)
elif acceptance <= 0.1 and acceptance > 0.05:
scale *= 0.4
elif acceptance <= 0.05 and acceptance > 0.01:
scale *= 0.2
elif acceptance <= 0.01:
scale *= 0.1
return scale | [
"def",
"tune_scale",
"(",
"acceptance",
",",
"scale",
")",
":",
"if",
"acceptance",
">",
"0.8",
":",
"scale",
"*=",
"2.0",
"elif",
"acceptance",
"<=",
"0.8",
"and",
"acceptance",
">",
"0.4",
":",
"scale",
"*=",
"1.3",
"elif",
"acceptance",
"<",
"0.234",
... | Tunes scale for M-H algorithm
Parameters
----------
acceptance : float
The most recent acceptance rate
scale : float
The current scale parameter
Returns
----------
scale : float
An adjusted scale parameter
Notes
----------
Ross : Initially did this by trial and error, then refined by looking at other
implementations, so some credit here to PyMC3 which became a guideline for this. | [
"Tunes",
"scale",
"for",
"M",
"-",
"H",
"algorithm"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/inference/metropolis_hastings.py#L66-L100 |
236,391 | RJT1990/pyflux | pyflux/families/normal.py | Normal.draw_variable_local | def draw_variable_local(self, size):
""" Simulate from the Normal distribution using instance values
Parameters
----------
size : int
How many simulations to perform
Returns
----------
np.ndarray of Normal random variable
"""
return ss.norm.rvs(loc=self.mu0, scale=self.sigma0, size=size) | python | def draw_variable_local(self, size):
return ss.norm.rvs(loc=self.mu0, scale=self.sigma0, size=size) | [
"def",
"draw_variable_local",
"(",
"self",
",",
"size",
")",
":",
"return",
"ss",
".",
"norm",
".",
"rvs",
"(",
"loc",
"=",
"self",
".",
"mu0",
",",
"scale",
"=",
"self",
".",
"sigma0",
",",
"size",
"=",
"size",
")"
] | Simulate from the Normal distribution using instance values
Parameters
----------
size : int
How many simulations to perform
Returns
----------
np.ndarray of Normal random variable | [
"Simulate",
"from",
"the",
"Normal",
"distribution",
"using",
"instance",
"values"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/normal.py#L154-L166 |
236,392 | RJT1990/pyflux | pyflux/families/normal.py | Normal.first_order_score | def first_order_score(y, mean, scale, shape, skewness):
""" GAS Normal Update term using gradient only - native Python function
Parameters
----------
y : float
datapoint for the time series
mean : float
location parameter for the Normal distribution
scale : float
scale parameter for the Normal distribution
shape : float
tail thickness parameter for the Normal distribution
skewness : float
skewness parameter for the Normal distribution
Returns
----------
- Score of the Normal family
"""
return (y-mean)/np.power(scale,2) | python | def first_order_score(y, mean, scale, shape, skewness):
return (y-mean)/np.power(scale,2) | [
"def",
"first_order_score",
"(",
"y",
",",
"mean",
",",
"scale",
",",
"shape",
",",
"skewness",
")",
":",
"return",
"(",
"y",
"-",
"mean",
")",
"/",
"np",
".",
"power",
"(",
"scale",
",",
"2",
")"
] | GAS Normal Update term using gradient only - native Python function
Parameters
----------
y : float
datapoint for the time series
mean : float
location parameter for the Normal distribution
scale : float
scale parameter for the Normal distribution
shape : float
tail thickness parameter for the Normal distribution
skewness : float
skewness parameter for the Normal distribution
Returns
----------
- Score of the Normal family | [
"GAS",
"Normal",
"Update",
"term",
"using",
"gradient",
"only",
"-",
"native",
"Python",
"function"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/normal.py#L169-L193 |
236,393 | RJT1990/pyflux | pyflux/families/normal.py | Normal.logpdf | def logpdf(self, mu):
"""
Log PDF for Normal prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu))
"""
if self.transform is not None:
mu = self.transform(mu)
return -np.log(float(self.sigma0)) - (0.5*(mu-self.mu0)**2)/float(self.sigma0**2) | python | def logpdf(self, mu):
if self.transform is not None:
mu = self.transform(mu)
return -np.log(float(self.sigma0)) - (0.5*(mu-self.mu0)**2)/float(self.sigma0**2) | [
"def",
"logpdf",
"(",
"self",
",",
"mu",
")",
":",
"if",
"self",
".",
"transform",
"is",
"not",
"None",
":",
"mu",
"=",
"self",
".",
"transform",
"(",
"mu",
")",
"return",
"-",
"np",
".",
"log",
"(",
"float",
"(",
"self",
".",
"sigma0",
")",
")... | Log PDF for Normal prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu)) | [
"Log",
"PDF",
"for",
"Normal",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/normal.py#L195-L210 |
236,394 | RJT1990/pyflux | pyflux/families/normal.py | Normal.pdf | def pdf(self, mu):
"""
PDF for Normal prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- p(mu)
"""
if self.transform is not None:
mu = self.transform(mu)
return (1.0/float(self.sigma0))*np.exp(-(0.5*(mu-self.mu0)**2)/float(self.sigma0**2)) | python | def pdf(self, mu):
if self.transform is not None:
mu = self.transform(mu)
return (1.0/float(self.sigma0))*np.exp(-(0.5*(mu-self.mu0)**2)/float(self.sigma0**2)) | [
"def",
"pdf",
"(",
"self",
",",
"mu",
")",
":",
"if",
"self",
".",
"transform",
"is",
"not",
"None",
":",
"mu",
"=",
"self",
".",
"transform",
"(",
"mu",
")",
"return",
"(",
"1.0",
"/",
"float",
"(",
"self",
".",
"sigma0",
")",
")",
"*",
"np",
... | PDF for Normal prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- p(mu) | [
"PDF",
"for",
"Normal",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/normal.py#L291-L306 |
236,395 | RJT1990/pyflux | pyflux/families/normal.py | Normal.vi_change_param | def vi_change_param(self, index, value):
""" Wrapper function for changing latent variables - variational inference
Parameters
----------
index : int
0 or 1 depending on which latent variable
value : float
What to change the latent variable to
"""
if index == 0:
self.mu0 = value
elif index == 1:
self.sigma0 = np.exp(value) | python | def vi_change_param(self, index, value):
if index == 0:
self.mu0 = value
elif index == 1:
self.sigma0 = np.exp(value) | [
"def",
"vi_change_param",
"(",
"self",
",",
"index",
",",
"value",
")",
":",
"if",
"index",
"==",
"0",
":",
"self",
".",
"mu0",
"=",
"value",
"elif",
"index",
"==",
"1",
":",
"self",
".",
"sigma0",
"=",
"np",
".",
"exp",
"(",
"value",
")"
] | Wrapper function for changing latent variables - variational inference
Parameters
----------
index : int
0 or 1 depending on which latent variable
value : float
What to change the latent variable to | [
"Wrapper",
"function",
"for",
"changing",
"latent",
"variables",
"-",
"variational",
"inference"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/normal.py#L365-L379 |
236,396 | RJT1990/pyflux | pyflux/families/normal.py | Normal.vi_return_param | def vi_return_param(self, index):
""" Wrapper function for selecting appropriate latent variable for variational inference
Parameters
----------
index : int
0 or 1 depending on which latent variable
Returns
----------
The appropriate indexed parameter
"""
if index == 0:
return self.mu0
elif index == 1:
return np.log(self.sigma0) | python | def vi_return_param(self, index):
if index == 0:
return self.mu0
elif index == 1:
return np.log(self.sigma0) | [
"def",
"vi_return_param",
"(",
"self",
",",
"index",
")",
":",
"if",
"index",
"==",
"0",
":",
"return",
"self",
".",
"mu0",
"elif",
"index",
"==",
"1",
":",
"return",
"np",
".",
"log",
"(",
"self",
".",
"sigma0",
")"
] | Wrapper function for selecting appropriate latent variable for variational inference
Parameters
----------
index : int
0 or 1 depending on which latent variable
Returns
----------
The appropriate indexed parameter | [
"Wrapper",
"function",
"for",
"selecting",
"appropriate",
"latent",
"variable",
"for",
"variational",
"inference"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/normal.py#L381-L396 |
236,397 | RJT1990/pyflux | pyflux/families/normal.py | Normal.vi_score | def vi_score(self, x, index):
""" Wrapper function for selecting appropriate score
Parameters
----------
x : float
A random variable
index : int
0 or 1 depending on which latent variable
Returns
----------
The gradient of the scale latent variable at x
"""
if index == 0:
return self.vi_loc_score(x)
elif index == 1:
return self.vi_scale_score(x) | python | def vi_score(self, x, index):
if index == 0:
return self.vi_loc_score(x)
elif index == 1:
return self.vi_scale_score(x) | [
"def",
"vi_score",
"(",
"self",
",",
"x",
",",
"index",
")",
":",
"if",
"index",
"==",
"0",
":",
"return",
"self",
".",
"vi_loc_score",
"(",
"x",
")",
"elif",
"index",
"==",
"1",
":",
"return",
"self",
".",
"vi_scale_score",
"(",
"x",
")"
] | Wrapper function for selecting appropriate score
Parameters
----------
x : float
A random variable
index : int
0 or 1 depending on which latent variable
Returns
----------
The gradient of the scale latent variable at x | [
"Wrapper",
"function",
"for",
"selecting",
"appropriate",
"score"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/normal.py#L426-L444 |
236,398 | RJT1990/pyflux | pyflux/families/laplace.py | Laplace.first_order_score | def first_order_score(y, mean, scale, shape, skewness):
""" GAS Laplace Update term using gradient only - native Python function
Parameters
----------
y : float
datapoint for the time series
mean : float
location parameter for the Laplace distribution
scale : float
scale parameter for the Laplace distribution
shape : float
tail thickness parameter for the Laplace distribution
skewness : float
skewness parameter for the Laplace distribution
Returns
----------
- Score of the Laplace family
"""
return (y-mean)/float(scale*np.abs(y-mean)) | python | def first_order_score(y, mean, scale, shape, skewness):
return (y-mean)/float(scale*np.abs(y-mean)) | [
"def",
"first_order_score",
"(",
"y",
",",
"mean",
",",
"scale",
",",
"shape",
",",
"skewness",
")",
":",
"return",
"(",
"y",
"-",
"mean",
")",
"/",
"float",
"(",
"scale",
"*",
"np",
".",
"abs",
"(",
"y",
"-",
"mean",
")",
")"
] | GAS Laplace Update term using gradient only - native Python function
Parameters
----------
y : float
datapoint for the time series
mean : float
location parameter for the Laplace distribution
scale : float
scale parameter for the Laplace distribution
shape : float
tail thickness parameter for the Laplace distribution
skewness : float
skewness parameter for the Laplace distribution
Returns
----------
- Score of the Laplace family | [
"GAS",
"Laplace",
"Update",
"term",
"using",
"gradient",
"only",
"-",
"native",
"Python",
"function"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/laplace.py#L156-L180 |
236,399 | RJT1990/pyflux | pyflux/families/laplace.py | Laplace.logpdf | def logpdf(self, mu):
"""
Log PDF for Laplace prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu))
"""
if self.transform is not None:
mu = self.transform(mu)
return ss.laplace.logpdf(mu, loc=self.loc0, scale=self.scale0) | python | def logpdf(self, mu):
if self.transform is not None:
mu = self.transform(mu)
return ss.laplace.logpdf(mu, loc=self.loc0, scale=self.scale0) | [
"def",
"logpdf",
"(",
"self",
",",
"mu",
")",
":",
"if",
"self",
".",
"transform",
"is",
"not",
"None",
":",
"mu",
"=",
"self",
".",
"transform",
"(",
"mu",
")",
"return",
"ss",
".",
"laplace",
".",
"logpdf",
"(",
"mu",
",",
"loc",
"=",
"self",
... | Log PDF for Laplace prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu)) | [
"Log",
"PDF",
"for",
"Laplace",
"prior"
] | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/laplace.py#L182-L197 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.