after_merge stringlengths 64 17k | before_merge stringlengths 60 17k |
|---|---|
def cmdb_get_mainline_object_topo(request, bk_biz_id, bk_supplier_account=''):
"""
@summary: 获取配置平台业务拓扑模型
@param request:
@param bk_biz_id:
@param bk_supplier_account:
@return:
"""
kwargs = {
'bk_biz_id': bk_biz_id,
'bk_supplier_account': bk_supplier_account,
}
cl... | def cmdb_get_mainline_object_topo(request, bk_biz_id, bk_supplier_account=''):
"""
@summary: 获取配置平台业务拓扑模型
@param request:
@param bk_biz_id:
@param bk_supplier_account:
@return:
"""
kwargs = {
'bk_biz_id': bk_biz_id,
'bk_supplier_account': bk_supplier_account,
}
cl... |
def cc_search_object_attribute(request, obj_id, biz_cc_id, supplier_account):
"""
@summary: 获取对象自定义属性
@param request:
@param biz_cc_id:
@return:
"""
client = get_client_by_user(request.user.username)
kwargs = {
'bk_obj_id': obj_id,
'bk_supplier_account': supplier_account
... | def cc_search_object_attribute(request, obj_id, biz_cc_id, supplier_account):
"""
@summary: 获取对象自定义属性
@param request:
@param biz_cc_id:
@return:
"""
client = get_client_by_request(request)
kwargs = {
'bk_obj_id': obj_id,
'bk_supplier_account': supplier_account
}
c... |
def cc_search_create_object_attribute(request, obj_id, biz_cc_id, supplier_account):
client = get_client_by_user(request.user.username)
kwargs = {
'bk_obj_id': obj_id,
'bk_supplier_account': supplier_account
}
cc_result = client.cc.search_object_attribute(kwargs)
if not cc_result['re... | def cc_search_create_object_attribute(request, obj_id, biz_cc_id, supplier_account):
client = get_client_by_request(request)
kwargs = {
'bk_obj_id': obj_id,
'bk_supplier_account': supplier_account
}
cc_result = client.cc.search_object_attribute(kwargs)
if not cc_result['result']:
... |
def cc_search_topo(request, obj_id, category, biz_cc_id, supplier_account):
"""
@summary: 查询对象拓扑
@param request:
@param biz_cc_id:
@return:
"""
client = get_client_by_user(request.user.username)
kwargs = {
'bk_biz_id': biz_cc_id,
'bk_supplier_account': supplier_account
... | def cc_search_topo(request, obj_id, category, biz_cc_id, supplier_account):
"""
@summary: 查询对象拓扑
@param request:
@param biz_cc_id:
@return:
"""
client = get_client_by_request(request)
kwargs = {
'bk_biz_id': biz_cc_id,
'bk_supplier_account': supplier_account
}
cc_... |
def job_get_script_list(request, biz_cc_id):
"""
查询业务脚本列表
:param request:
:param biz_cc_id:
:return:
"""
# 查询脚本列表
client = get_client_by_user(request.user.username)
script_type = request.GET.get('type')
kwargs = {
'bk_biz_id': biz_cc_id,
'is_public': True if scrip... | def job_get_script_list(request, biz_cc_id):
"""
查询业务脚本列表
:param request:
:param biz_cc_id:
:return:
"""
# 查询脚本列表
client = get_client_by_request(request)
script_type = request.GET.get('type')
kwargs = {
'bk_biz_id': biz_cc_id,
'is_public': True if script_type == '... |
def job_get_job_tasks_by_biz(request, biz_cc_id):
client = get_client_by_user(request.user.username)
job_result = client.job.get_job_list({'bk_biz_id': biz_cc_id})
if not job_result['result']:
message = _(u"查询作业平台(JOB)的作业模板[app_id=%s]接口job.get_task返回失败: %s") % (
biz_cc_id, job_result['me... | def job_get_job_tasks_by_biz(request, biz_cc_id):
client = get_client_by_request(request)
job_result = client.job.get_job_list({'bk_biz_id': biz_cc_id})
if not job_result['result']:
message = _(u"查询作业平台(JOB)的作业模板[app_id=%s]接口job.get_task返回失败: %s") % (
biz_cc_id, job_result['message'])
... |
def job_get_job_task_detail(request, biz_cc_id, task_id):
client = get_client_by_user(request.user.username)
job_result = client.job.get_job_detail({'bk_biz_id': biz_cc_id,
'bk_job_id': task_id})
if not job_result['result']:
message = _(u"查询作业平台(JOB)的作业模板详... | def job_get_job_task_detail(request, biz_cc_id, task_id):
client = get_client_by_request(request)
job_result = client.job.get_job_detail({'bk_biz_id': biz_cc_id,
'bk_job_id': task_id})
if not job_result['result']:
message = _(u"查询作业平台(JOB)的作业模板详情[app_id=%s... |
def get_bk_user(request):
bkuser = None
if request.weixin_user and not isinstance(request.weixin_user, AnonymousUser):
user_model = get_user_model()
try:
user_property = UserProperty.objects.get(key='wx_userid', value=request.weixin_user.userid)
except UserProperty.DoesNotExi... | def get_bk_user(request):
bkuser = None
if request.weixin_user and not isinstance(request.weixin_user, AnonymousUser):
try:
user_property = UserProperty.objects.get(key='wx_userid', value=request.weixin_user.userid)
bkuser = user_property.user
except UserProperty.DoesNotE... |
def fit(self, dataset: Dataset):
"""Calculates statistics for this workflow on the input dataset
Parameters
-----------
dataset: Dataset
The input dataset to calculate statistics for. If there is a train/test split this
data should be the training dataset onl... | def fit(self, dataset: Dataset):
"""Calculates statistics for this workflow on the input dataset
Parameters
-----------
dataset: Dataset
The input dataset to calculate statistics for. If there is a train/test split this
data should be the training dataset onl... |
def main(args):
"""Multi-GPU Criteo/DLRM Preprocessing Benchmark
This benchmark is designed to measure the time required to preprocess
the Criteo (1TB) dataset for Facebook’s DLRM model. The user must specify
the path of the raw dataset (using the `--data-path` flag), as well as the
output directo... | def main(args):
"""Multi-GPU Criteo/DLRM Preprocessing Benchmark
This benchmark is designed to measure the time required to preprocess
the Criteo (1TB) dataset for Facebook’s DLRM model. The user must specify
the path of the raw dataset (using the `--data-path` flag), as well as the
output directo... |
def __init__(self, out_dir, **kwargs):
super().__init__(out_dir, **kwargs)
self.data_paths = []
self.data_files = []
self.data_writers = []
self.data_bios = []
self._lock = threading.RLock()
self.pwriter = self._pwriter
self.pwriter_kwargs = {} | def __init__(self, out_dir, **kwargs):
super().__init__(out_dir, **kwargs)
self.data_paths = []
self.data_writers = []
self.data_bios = []
self._lock = threading.RLock()
self.pwriter = self._pwriter
self.pwriter_kwargs = {} |
def _append_writer(self, path, schema=None, add_args=None, add_kwargs=None):
# Add additional args and kwargs
_args = add_args or []
_kwargs = tlz.merge(self.pwriter_kwargs, add_kwargs or {})
if self.bytes_io:
bio = BytesIO()
self.data_bios.append(bio)
... | def _append_writer(self, path, schema=None, add_args=None, add_kwargs=None):
# Add additional args and kwargs
_args = add_args or []
_kwargs = tlz.merge(self.pwriter_kwargs, add_kwargs or {})
if self.bytes_io:
bio = BytesIO()
self.data_bios.append(bio)
... |
def _close_writers(self):
md_dict = {}
for writer, path in zip(self.data_writers, self.data_paths):
fn = path.split(self.fs.sep)[-1]
md_dict[fn] = writer.close(metadata_file_path=fn)
for f in self.data_files:
f.close()
return md_dict | def _close_writers(self):
md_dict = {}
for writer, path in zip(self.data_writers, self.data_paths):
fn = path.split(self.fs.sep)[-1]
md_dict[fn] = writer.close(metadata_file_path=fn)
return md_dict |
def fetch_table_data(
table_cache, path, cache="disk", cats_only=False, reader=None, columns=None, **kwargs
):
"""Utility to retrieve a cudf DataFrame from a cache (and add the
DataFrame to a cache if the element is missing). Note that `cats_only=True`
results in optimized logic for the `Categorify` tr... | def fetch_table_data(
table_cache, path, cache="disk", cats_only=False, reader=None, columns=None, **kwargs
):
"""Utility to retrieve a cudf DataFrame from a cache (and add the
DataFrame to a cache if the element is missing). Note that `cats_only=True`
results in optimized logic for the `Categorify` tr... |
def _chunkwise_moments(df):
df2 = cudf.DataFrame()
for col in df.columns:
df2[col] = df[col].astype("float64").pow(2)
vals = {
"df-count": df.count().to_frame().transpose(),
"df-sum": df.sum().astype("float64").to_frame().transpose(),
"df2-sum": df2.sum().to_frame().transpose... | def _chunkwise_moments(df):
df2 = cudf.DataFrame()
for col in df.columns:
df2[col] = df[col].astype("float64").pow(2)
vals = {
"df-count": df.count().to_frame().transpose(),
"df-sum": df.sum().to_frame().transpose(),
"df2-sum": df2.sum().to_frame().transpose(),
}
# NO... |
def to_ddf(self, columns=None):
return dask_cudf.read_parquet(
self.paths,
columns=columns,
# can't omit reading the index in if we aren't being passed columns
index=None if columns is None else False,
gather_statistics=False,
split_row... | def to_ddf(self, columns=None):
return dask_cudf.read_parquet(
self.paths,
columns=columns,
index=False,
gather_statistics=False,
split_row_groups=self.row_groups_per_part,
storage_options=self.storage_options,
) |
def get_ddf(self):
if self.ddf is None:
raise ValueError("No dask_cudf frame available.")
elif isinstance(self.ddf, Dataset):
# Right now we can't distinguish between input columns and generated columns
# in the dataset, we don't limit the columm set right now in ... | def get_ddf(self):
if self.ddf is None:
raise ValueError("No dask_cudf frame available.")
elif isinstance(self.ddf, Dataset):
columns = self.columns_ctx["all"]["base"]
return self.ddf.to_ddf(columns=columns, shuffle=self._shuffle_parts)
return self.ddf |
def add_data(self, gdf):
# Populate columns idxs
if not self.col_idx:
for i, x in enumerate(gdf.columns.values):
self.col_idx[str(x)] = i
# list columns in cudf don't currently support chunked writing in parquet.
# hack around this by just writing a singl... | def add_data(self, gdf):
# Populate columns idxs
if not self.col_idx:
for i, x in enumerate(gdf.columns.values):
self.col_idx[str(x)] = i
# list columns in cudf don't currently support chunked writing in parquet.
# hack around this by just writing a singl... |
def __init__(
self,
paths,
part_size,
storage_options,
row_groups_per_part=None,
legacy=False,
batch_size=None,
):
# TODO: Improve dask_cudf.read_parquet performance so that
# this class can be slimmed down.
super().__init__(paths, ... | def __init__(
self,
paths,
part_size,
storage_options,
row_groups_per_part=None,
legacy=False,
batch_size=None,
):
# TODO: Improve dask_cudf.read_parquet performance so that
# this class can be slimmed down.
super().__init__(paths, ... |
def __init__(self, *args, **kwargs):
super().__init__(*args)
self._meta = {}
self.csv_kwargs = kwargs
self.names = self.csv_kwargs.get("names", None)
# CSV reader needs a list of files
# (Assume flat directory structure if this is a dir)
if len(self.paths) == ... | def __init__(self, *args, **kwargs):
super().__init__(*args)
self._meta = {}
self.names = kwargs.pop("names", None)
self.csv_kwargs = kwargs
# CSV reader needs a list of files
# (Assume flat directory structure if this is a dir)
if len(self.paths) == 1 and sel... |
def to_ddf(self, columns=None):
return dask_cudf.read_csv(self.paths, chunksize=self.part_size, **self.csv_kwargs)[columns] | def to_ddf(self, columns=None):
return dask_cudf.read_csv(
self.paths, names=self.names, chunksize=self.part_size, **self.csv_kwargs
)[columns] |
def _predict(self, X):
"""Collect results from clf.predict calls."""
if self.refit:
return np.asarray([clf.predict(X) for clf in self.clfs_]).T
else:
return np.asarray([self.le_.transform(clf.predict(X))
for clf in self.clfs_]).T | def _predict(self, X):
"""Collect results from clf.predict calls."""
return np.asarray([clf.predict(X) for clf in self.clfs_]).T |
def transform(
self,
xx: Any,
yy: Any,
zz: Any = None,
tt: Any = None,
radians: bool = False,
errcheck: bool = False,
direction: Union[TransformDirection, str] = TransformDirection.FORWARD,
) -> Any:
"""
Transform points between two... | def transform(
self,
xx: Any,
yy: Any,
zz: Any = None,
tt: Any = None,
radians: bool = False,
errcheck: bool = False,
direction: Union[TransformDirection, str] = TransformDirection.FORWARD,
) -> Any:
"""
Transform points between two... |
def itransform(
self,
points: Any,
switch: bool = False,
time_3rd: bool = False,
radians: bool = False,
errcheck: bool = False,
direction: Union[TransformDirection, str] = TransformDirection.FORWARD,
) -> Iterator[Iterable]:
"""
Iterator/ge... | def itransform(
self,
points: Any,
switch: bool = False,
time_3rd: bool = False,
radians: bool = False,
errcheck: bool = False,
direction: Union[TransformDirection, str] = TransformDirection.FORWARD,
) -> Iterator[Iterable]:
"""
Iterator/ge... |
def from_user_input(value: Any) -> "CRS":
"""
Initialize a CRS class instance with:
- PROJ string
- Dictionary of PROJ parameters
- PROJ keyword arguments for parameters
- JSON string with PROJ parameters
- CRS WKT string
- An authority str... | def from_user_input(value: str) -> "CRS":
"""
Initialize a CRS class instance with:
- PROJ string
- Dictionary of PROJ parameters
- PROJ keyword arguments for parameters
- JSON string with PROJ parameters
- CRS WKT string
- An authority str... |
def __init__(
self,
name: str = "undefined",
datum: Any = "urn:ogc:def:datum:EPSG::6326",
ellipsoidal_cs: Any = None,
) -> None:
"""
Parameters
----------
name: str, optional
Name of the CRS. Default is undefined.
datum: Any, op... | def __init__(
self,
name: str = "undefined",
datum: Any = "urn:ogc:def:datum:EPSG::6326",
ellipsoidal_cs: Any = Ellipsoidal2DCS(),
) -> None:
"""
Parameters
----------
name: str, optional
Name of the CRS. Default is undefined.
d... |
def __init__(
self,
base_crs: Any,
conversion: Any,
ellipsoidal_cs: Any = None,
name: str = "undefined",
) -> None:
"""
Parameters
----------
base_crs: Any
Input to create the Geodetic CRS, a :class:`GeographicCRS` or
... | def __init__(
self,
base_crs: Any,
conversion: Any,
ellipsoidal_cs: Any = Ellipsoidal2DCS(),
name: str = "undefined",
) -> None:
"""
Parameters
----------
base_crs: Any
Input to create the Geodetic CRS, a :class:`GeographicCRS` ... |
def __init__(
self,
conversion: Any,
name: str = "undefined",
cartesian_cs: Any = None,
geodetic_crs: Any = None,
) -> None:
"""
Parameters
----------
conversion: Any
Anything accepted by :meth:`pyproj.crs.CoordinateSystem.from_... | def __init__(
self,
conversion: Any,
name: str = "undefined",
cartesian_cs: Any = Cartesian2DCS(),
geodetic_crs: Any = GeographicCRS(),
) -> None:
"""
Parameters
----------
conversion: Any
Anything accepted by :meth:`pyproj.crs.... |
def __init__(
self,
name: str,
datum: Any,
vertical_cs: Any = None,
geoid_model: Optional[str] = None,
) -> None:
"""
Parameters
----------
name: str
The name of the Vertical CRS (e.g. NAVD88 height).
datum: Any
... | def __init__(
self,
name: str,
datum: Any,
vertical_cs: Any = VerticalCS(),
geoid_model: str = None,
) -> None:
"""
Parameters
----------
name: str
The name of the Vertical CRS (e.g. NAVD88 height).
datum: Any
... |
def set_data_dir(proj_data_dir):
"""
Set the data directory for PROJ to use.
Parameters
----------
proj_data_dir: str
The path to rhe PROJ data directory.
"""
global _USER_PROJ_DATA
_USER_PROJ_DATA = proj_data_dir
# reset search paths
from pyproj._datadir import PYPROJ_C... | def set_data_dir(proj_data_dir):
"""
Set the data directory for PROJ to use.
Parameters
----------
proj_data_dir: str
The path to rhe PROJ data directory.
"""
global _USER_PROJ_DATA
_USER_PROJ_DATA = proj_data_dir
# reset search paths
from pyproj._datadir import PYPROJ_C... |
def set_data_dir(proj_data_dir):
"""
Set the data directory for PROJ to use.
Parameters
----------
proj_data_dir: str
The path to rhe PROJ data directory.
"""
global _USER_PROJ_DATA
_USER_PROJ_DATA = proj_data_dir
# reset search paths
from pyproj._datadir import PYPROJ_C... | def set_data_dir(proj_data_dir):
"""
Set the data directory for PROJ to use.
Parameters
----------
proj_data_dir: str
The path to rhe PROJ data directory.
"""
global _USER_PROJ_DATA
global _VALIDATED_PROJ_DATA
_USER_PROJ_DATA = proj_data_dir
# set to none to re-validate
... |
def get_data_dir():
"""
The order of preference for the data directory is:
1. The one set by pyproj.datadir.set_data_dir (if exists & valid)
2. The internal proj directory (if exists & valid)
3. The directory in PROJ_LIB (if exists & valid)
4. The directory on the PATH (if exists & valid)
... | def get_data_dir():
"""
The order of preference for the data directory is:
1. The one set by pyproj.datadir.set_data_dir (if exists & valid)
2. The internal proj directory (if exists & valid)
3. The directory in PROJ_LIB (if exists & valid)
4. The directory on the PATH (if exists & valid)
... |
def from_proj(proj_from, proj_to, skip_equivalent=False, always_xy=False):
"""Make a Transformer from a :obj:`~pyproj.proj.Proj` or input used to create one.
Parameters
----------
proj_from: :obj:`~pyproj.proj.Proj` or input used to create one
Projection of input data.
... | def from_proj(proj_from, proj_to, skip_equivalent=False, always_xy=False):
"""Make a Transformer from a :obj:`~pyproj.proj.Proj` or input used to create one.
Parameters
----------
proj_from: :obj:`~pyproj.proj.Proj` or input used to create one
Projection of input data.
... |
def from_crs(crs_from, crs_to, skip_equivalent=False, always_xy=False):
"""Make a Transformer from a :obj:`~pyproj.crs.CRS` or input used to create one.
Parameters
----------
crs_from: ~pyproj.crs.CRS or input used to create one
Projection of input data.
crs_to: ... | def from_crs(crs_from, crs_to, skip_equivalent=False, always_xy=False):
"""Make a Transformer from a :obj:`~pyproj.crs.CRS` or input used to create one.
Parameters
----------
crs_from: ~pyproj.crs.CRS or input used to create one
Projection of input data.
crs_to: ... |
def from_pipeline(proj_pipeline):
"""Make a Transformer from a PROJ pipeline string.
https://proj4.org/operations/pipeline.html
Parameters
----------
proj_pipeline: str
Projection pipeline string.
Returns
-------
~Transformer
""... | def from_pipeline(proj_pipeline):
"""Make a Transformer from a PROJ pipeline string.
https://proj4.org/operations/pipeline.html
Parameters
----------
proj_pipeline: str
Projection pipeline string.
Returns
-------
~Transformer
""... |
def _dict2string(projparams):
# convert a dict to a proj4 string.
pjargs = []
proj_inserted = False
for key, value in projparams.items():
# the towgs84 as list
if isinstance(value, (list, tuple)):
value = ",".join([str(val) for val in value])
# issue 183 (+ no_rot)
... | def _dict2string(projparams):
# convert a dict to a proj4 string.
pjargs = []
for key, value in projparams.items():
# the towgs84 as list
if isinstance(value, (list, tuple)):
value = ",".join([str(val) for val in value])
# issue 183 (+ no_rot)
if value is None or ... |
def __init__(self, projparams=None, preserve_units=True, **kwargs):
"""
initialize a Proj class instance.
See the proj documentation (https://github.com/OSGeo/proj.4/wiki)
for more information about projection parameters.
Parameters
----------
projparams: in... | def __init__(self, projparams=None, preserve_units=True, **kwargs):
"""
initialize a Proj class instance.
See the proj documentation (https://github.com/OSGeo/proj.4/wiki)
for more information about projection parameters.
Parameters
----------
projparams: in... |
def Kuf_conv_patch(inducing_variable, kernel, Xnew):
Xp = kernel.get_patches(Xnew) # [N, num_patches, patch_len]
bigKzx = kernel.base_kernel.K(
inducing_variable.Z, Xp
) # [M, N, P] -- thanks to broadcasting of kernels
Kzx = tf.reduce_sum(bigKzx * kernel.weights if hasattr(kernel, "weights") e... | def Kuf_conv_patch(feat, kern, Xnew):
Xp = kern.get_patches(Xnew) # [N, num_patches, patch_len]
bigKzx = kern.base_kernel.K(feat.Z, Xp) # [M, N, P] -- thanks to broadcasting of kernels
Kzx = tf.reduce_sum(bigKzx * kern.weights if hasattr(kern, "weights") else bigKzx, [2])
return Kzx / kern.num_patches |
def Kuu_kernel_inducingpoints(inducing_variable: InducingPoints, kernel: Kernel, *, jitter=0.0):
Kzz = kernel(inducing_variable.Z)
Kzz += jitter * tf.eye(inducing_variable.num_inducing, dtype=Kzz.dtype)
return Kzz | def Kuu_kernel_inducingpoints(inducing_variable: InducingPoints, kernel: Kernel, *, jitter=0.0):
Kzz = kernel(inducing_variable.Z)
Kzz += jitter * tf.eye(len(inducing_variable), dtype=Kzz.dtype)
return Kzz |
def Kuu_sqexp_multiscale(inducing_variable: Multiscale, kernel: SquaredExponential, *, jitter=0.0):
Zmu, Zlen = kernel.slice(inducing_variable.Z, inducing_variable.scales)
idlengthscales2 = tf.square(kernel.lengthscales + Zlen)
sc = tf.sqrt(
idlengthscales2[None, ...] + idlengthscales2[:, None, ...]... | def Kuu_sqexp_multiscale(inducing_variable: Multiscale, kernel: SquaredExponential, *, jitter=0.0):
Zmu, Zlen = kernel.slice(inducing_variable.Z, inducing_variable.scales)
idlengthscales2 = tf.square(kernel.lengthscales + Zlen)
sc = tf.sqrt(
idlengthscales2[None, ...] + idlengthscales2[:, None, ...]... |
def Kuu_conv_patch(inducing_variable, kernel, jitter=0.0):
return kernel.base_kernel.K(inducing_variable.Z) + jitter * tf.eye(
inducing_variable.num_inducing, dtype=default_float()
) | def Kuu_conv_patch(feat, kern, jitter=0.0):
return kern.base_kernel.K(feat.Z) + jitter * tf.eye(len(feat), dtype=default_float()) |
def _Kuu(
inducing_variable: FallbackSeparateIndependentInducingVariables,
kernel: Union[SeparateIndependent, LinearCoregionalization],
*,
jitter=0.0,
):
Kmms = [Kuu(f, k) for f, k in zip(inducing_variable.inducing_variable_list, kernel.kernels)]
Kmm = tf.stack(Kmms, axis=0) # [L, M, M]
jit... | def _Kuu(
inducing_variable: FallbackSeparateIndependentInducingVariables,
kernel: Union[SeparateIndependent, LinearCoregionalization],
*,
jitter=0.0,
):
Kmms = [Kuu(f, k) for f, k in zip(inducing_variable.inducing_variable_list, kernel.kernels)]
Kmm = tf.stack(Kmms, axis=0) # [L, M, M]
jit... |
def __init__(self, Z: TensorData, name: Optional[str] = None):
"""
:param Z: the initial positions of the inducing points, size [M, D]
"""
super().__init__(name=name)
if not isinstance(Z, (tf.Variable, tfp.util.TransformedVariable)):
Z = Parameter(Z)
self.... | def __init__(self, Z: TensorData, name: Optional[str] = None):
"""
:param Z: the initial positions of the inducing points, size [M, D]
"""
super().__init__(name=name)
self.Z = Parameter(Z, dtype=default_float()) |
def __len__(self) -> int:
return tf.shape(self.Z)[0] | def __len__(self) -> int:
return self.Z.shape[0] |
def __len__(self) -> int:
return self.inducing_variable.num_inducing | def __len__(self) -> int:
return len(self.inducing_variable) |
def __len__(self) -> int:
# TODO(st--) we should check that they all have the same length...
return self.inducing_variable_list[0].num_inducing | def __len__(self) -> int:
return len(self.inducing_variable_list[0]) |
def __init__(
self,
distribution_class: Type[tfp.distributions.Distribution] = tfp.distributions.Normal,
scale_transform: Optional[tfp.bijectors.Bijector] = None,
**kwargs,
):
"""
:param distribution_class: distribution class parameterized by `loc` and `scale`
... | def __init__(
self,
distribution_class: Type[tfp.distributions.Distribution] = tfp.distributions.Normal,
scale_transform: tfp.bijectors.Bijector = positive(base="exp"),
**kwargs,
):
"""
:param distribution_class: distribution class parameterized by `loc` and `scal... |
def conditional_distribution(Fs) -> tfp.distributions.Distribution:
tf.debugging.assert_equal(tf.shape(Fs)[-1], 2)
loc = Fs[..., :1]
scale = self.scale_transform(Fs[..., 1:])
return distribution_class(loc, scale) | def conditional_distribution(Fs) -> tfp.distributions.Distribution:
tf.debugging.assert_equal(tf.shape(Fs)[-1], 2)
loc = Fs[..., :1]
scale = scale_transform(Fs[..., 1:])
return distribution_class(loc, scale) |
def elbo(self) -> tf.Tensor:
"""
Construct a tensorflow function to compute the bound on the marginal
likelihood.
"""
Y_data = self.data
pX = DiagonalGaussian(self.X_data_mean, self.X_data_var)
num_inducing = self.inducing_variable.num_inducing
psi0 ... | def elbo(self) -> tf.Tensor:
"""
Construct a tensorflow function to compute the bound on the marginal
likelihood.
"""
Y_data = self.data
pX = DiagonalGaussian(self.X_data_mean, self.X_data_var)
num_inducing = len(self.inducing_variable)
psi0 = tf.red... |
def predict_f(
self, Xnew: InputData, full_cov: bool = False, full_output_cov: bool = False
) -> MeanAndVariance:
"""
Compute the mean and variance of the latent function at some new points.
Note that this is very similar to the SGPR prediction, for which
there are notes ... | def predict_f(
self, Xnew: InputData, full_cov: bool = False, full_output_cov: bool = False
) -> MeanAndVariance:
"""
Compute the mean and variance of the latent function at some new points.
Note that this is very similar to the SGPR prediction, for which
there are notes ... |
def __init__(
self,
data: RegressionData,
kernel: Kernel,
likelihood: Likelihood,
mean_function: Optional[MeanFunction] = None,
num_latent_gps: Optional[int] = None,
inducing_variable: Optional[InducingPoints] = None,
):
"""
data is a tuple... | def __init__(
self,
data: RegressionData,
kernel: Kernel,
likelihood: Likelihood,
mean_function: Optional[MeanFunction] = None,
num_latent_gps: Optional[int] = None,
inducing_variable: Optional[InducingPoints] = None,
):
"""
data is a tuple... |
def upper_bound(self) -> tf.Tensor:
"""
Upper bound for the sparse GP regression marginal likelihood. Note that
the same inducing points are used for calculating the upper bound, as are
used for computing the likelihood approximation. This may not lead to the
best upper boun... | def upper_bound(self) -> tf.Tensor:
"""
Upper bound for the sparse GP regression marginal likelihood. Note that
the same inducing points are used for calculating the upper bound, as are
used for computing the likelihood approximation. This may not lead to the
best upper boun... |
def elbo(self) -> tf.Tensor:
"""
Construct a tensorflow function to compute the bound on the marginal
likelihood. For a derivation of the terms in here, see the associated
SGPR notebook.
"""
X_data, Y_data = self.data
num_inducing = self.inducing_variable.num... | def elbo(self) -> tf.Tensor:
"""
Construct a tensorflow function to compute the bound on the marginal
likelihood. For a derivation of the terms in here, see the associated
SGPR notebook.
"""
X_data, Y_data = self.data
num_inducing = len(self.inducing_variable... |
def predict_f(self, Xnew: InputData, full_cov=False, full_output_cov=False) -> MeanAndVariance:
"""
Compute the mean and variance of the latent function at some new points
Xnew. For a derivation of the terms in here, see the associated SGPR
notebook.
"""
X_data, Y_dat... | def predict_f(self, Xnew: InputData, full_cov=False, full_output_cov=False) -> MeanAndVariance:
"""
Compute the mean and variance of the latent function at some new points
Xnew. For a derivation of the terms in here, see the associated SGPR
notebook.
"""
X_data, Y_dat... |
def common_terms(self):
X_data, Y_data = self.data
num_inducing = self.inducing_variable.num_inducing
err = Y_data - self.mean_function(X_data) # size [N, R]
Kdiag = self.kernel(X_data, full_cov=False)
kuf = Kuf(self.inducing_variable, self.kernel, X_data)
kuu = Kuu(... | def common_terms(self):
X_data, Y_data = self.data
num_inducing = len(self.inducing_variable)
err = Y_data - self.mean_function(X_data) # size [N, R]
Kdiag = self.kernel(X_data, full_cov=False)
kuf = Kuf(self.inducing_variable, self.kernel, X_data)
kuu = Kuu(self.ind... |
def __init__(
self,
kernel,
likelihood,
inducing_variable,
*,
mean_function=None,
num_latent_gps: int = 1,
q_diag: bool = False,
q_mu=None,
q_sqrt=None,
whiten: bool = True,
num_data=None,
):
"""
- ke... | def __init__(
self,
kernel,
likelihood,
inducing_variable,
*,
mean_function=None,
num_latent_gps: int = 1,
q_diag: bool = False,
q_mu=None,
q_sqrt=None,
whiten: bool = True,
num_data=None,
):
"""
- ke... |
def ndiagquad(funcs, H: int, Fmu, Fvar, logspace: bool = False, **Ys):
"""
Computes N Gaussian expectation integrals of one or more functions
using Gauss-Hermite quadrature. The Gaussians must be independent.
The means and variances of the Gaussians are specified by Fmu and Fvar.
The N-integrals ar... | def ndiagquad(funcs, H: int, Fmu, Fvar, logspace: bool = False, **Ys):
"""
Computes N Gaussian expectation integrals of one or more functions
using Gauss-Hermite quadrature. The Gaussians must be independent.
The means and variances of the Gaussians are specified by Fmu and Fvar.
The N-integrals ar... |
def wrapper(old_fun):
def new_fun(X, **Ys):
Xs = tf.unstack(X, axis=-1)
fun_eval = old_fun(*Xs, **Ys)
return tf.cond(
pred=tf.less(tf.rank(fun_eval), tf.rank(X)),
true_fn=lambda: fun_eval[..., tf.newaxis],
false_fn=lambda: f... | def wrapper(old_fun):
def new_fun(X, **Ys):
Xs = tf.unstack(X, axis=-1)
fun_eval = old_fun(*Xs, **Ys)
if tf.rank(fun_eval) < tf.rank(X):
fun_eval = tf.expand_dims(fun_eval, axis=-1)
return fun_eval
return new_fun |
def new_fun(X, **Ys):
Xs = tf.unstack(X, axis=-1)
fun_eval = old_fun(*Xs, **Ys)
return tf.cond(
pred=tf.less(tf.rank(fun_eval), tf.rank(X)),
true_fn=lambda: fun_eval[..., tf.newaxis],
false_fn=lambda: fun_eval,
) | def new_fun(X, **Ys):
Xs = tf.unstack(X, axis=-1)
fun_eval = old_fun(*Xs, **Ys)
if tf.rank(fun_eval) < tf.rank(X):
fun_eval = tf.expand_dims(fun_eval, axis=-1)
return fun_eval |
def __init__(
self,
data: OutputData,
latent_dim: int,
X_data_mean: Optional[tf.Tensor] = None,
kernel: Optional[Kernel] = None,
mean_function: Optional[MeanFunction] = None,
):
"""
Initialise GPLVM object. This method only works with a Gaussian li... | def __init__(
self,
data: OutputData,
latent_dim: int,
X_data_mean: Optional[tf.Tensor] = None,
kernel: Optional[Kernel] = None,
mean_function: Optional[MeanFunction] = None,
):
"""
Initialise GPLVM object. This method only works with a Gaussian li... |
def __init__(
self,
data: OutputData,
X_data_mean: tf.Tensor,
X_data_var: tf.Tensor,
kernel: Kernel,
num_inducing_variables: Optional[int] = None,
inducing_variable=None,
X_prior_mean=None,
X_prior_var=None,
):
"""
Initialis... | def __init__(
self,
data: OutputData,
X_data_mean: tf.Tensor,
X_data_var: tf.Tensor,
kernel: Kernel,
num_inducing_variables: Optional[int] = None,
inducing_variable=None,
X_prior_mean=None,
X_prior_var=None,
):
"""
Initialis... |
def __init__(
self,
data: RegressionData,
kernel: Kernel,
mean_function: Optional[MeanFunction] = None,
noise_variance: float = 1.0,
):
likelihood = gpflow.likelihoods.Gaussian(noise_variance)
_, Y_data = data
super().__init__(kernel, likelihood, m... | def __init__(
self,
data: RegressionData,
kernel: Kernel,
mean_function: Optional[MeanFunction] = None,
noise_variance: float = 1.0,
):
likelihood = gpflow.likelihoods.Gaussian(noise_variance)
_, Y_data = data
super().__init__(kernel, likelihood, m... |
def __init__(
self,
data: RegressionData,
kernel: Kernel,
likelihood: Likelihood,
mean_function: Optional[MeanFunction] = None,
num_latent_gps: Optional[int] = None,
inducing_variable: Optional[InducingPoints] = None,
):
"""
data is a tuple... | def __init__(
self,
data: RegressionData,
kernel: Kernel,
likelihood: Likelihood,
mean_function: Optional[MeanFunction] = None,
num_latent_gps: Optional[int] = None,
inducing_variable: Optional[InducingPoints] = None,
):
"""
data is a tuple... |
def __init__(
self,
data: RegressionData,
kernel: Kernel,
inducing_variable: InducingPoints,
*,
mean_function: Optional[MeanFunction] = None,
num_latent_gps: Optional[int] = None,
noise_variance: float = 1.0,
):
"""
`data`: a tuple... | def __init__(
self,
data: RegressionData,
kernel: Kernel,
inducing_variable: InducingPoints,
*,
mean_function: Optional[MeanFunction] = None,
num_latent_gps: Optional[int] = None,
noise_variance: float = 1.0,
):
"""
`data`: a tuple... |
def __init__(
self,
data: RegressionData,
kernel: Kernel,
likelihood: Likelihood,
mean_function: Optional[MeanFunction] = None,
num_latent_gps: Optional[int] = None,
):
"""
data = (X, Y) contains the input points [N, D] and the observations [N, P]
... | def __init__(
self,
data: RegressionData,
kernel: Kernel,
likelihood: Likelihood,
mean_function: Optional[MeanFunction] = None,
num_latent_gps: Optional[int] = None,
):
"""
data = (X, Y) contains the input points [N, D] and the observations [N, P]
... |
def __init__(
self,
data: RegressionData,
kernel: Kernel,
likelihood: Likelihood,
mean_function: Optional[MeanFunction] = None,
num_latent_gps: Optional[int] = None,
):
"""
data = (X, Y) contains the input points [N, D] and the observations [N, P]
... | def __init__(
self,
data: RegressionData,
kernel: Kernel,
likelihood: Likelihood,
mean_function: Optional[MeanFunction] = None,
num_latent_gps: Optional[int] = None,
):
"""
data = (X, Y) contains the input points [N, D] and the observations [N, P]
... |
def __init__(
self,
data: RegressionData,
kernel: Kernel,
likelihood: Likelihood,
mean_function: Optional[MeanFunction] = None,
num_latent_gps: Optional[int] = None,
):
"""
data is a tuple of X, Y with X, a data matrix, size [N, D] and Y, a data ma... | def __init__(
self,
data: RegressionData,
kernel: Kernel,
likelihood: Likelihood,
mean_function: Optional[MeanFunction] = None,
num_latent_gps: Optional[int] = None,
):
"""
data is a tuple of X, Y with X, a data matrix, size [N, D] and Y, a data ma... |
def K(self, X: tf.Tensor, X2: Optional[tf.Tensor] = None) -> tf.Tensor:
sig_X = self._sigmoids(X) # N1 x 1 x Ncp
sig_X2 = self._sigmoids(X2) if X2 is not None else sig_X # N2 x 1 x Ncp
# `starters` are the sigmoids going from 0 -> 1, whilst `stoppers` go
# from 1 -> 0, dimensions ... | def K(self, X: tf.Tensor, X2: Optional[tf.Tensor] = None) -> tf.Tensor:
sig_X = self._sigmoids(X) # N x 1 x Ncp
sig_X2 = self._sigmoids(X2) if X2 is not None else sig_X
# `starters` are the sigmoids going from 0 -> 1, whilst `stoppers` go
# from 1 -> 0, dimensions are N x N x Ncp
... |
def autoflow(*af_args, **af_kwargs):
def autoflow_wrapper(method):
@functools.wraps(method)
def runnable(obj, *args, **kwargs):
if not isinstance(obj, Node):
raise GPflowError(
'AutoFlow works only with node-like objects.')
if obj.is_built_... | def autoflow(*af_args, **af_kwargs):
def autoflow_wrapper(method):
@functools.wraps(method)
def runnable(obj, *args, **kwargs):
if not isinstance(obj, Node):
raise GPflowError(
'AutoFlow works only with node-like objects.')
if obj.is_built_... |
def autoflow_wrapper(method):
@functools.wraps(method)
def runnable(obj, *args, **kwargs):
if not isinstance(obj, Node):
raise GPflowError(
'AutoFlow works only with node-like objects.')
if obj.is_built_coherence(obj.graph) is Build.NO:
... | def autoflow_wrapper(method):
@functools.wraps(method)
def runnable(obj, *args, **kwargs):
if not isinstance(obj, Node):
raise GPflowError(
'AutoFlow works only with node-like objects.')
if obj.is_built_coherence(obj.graph) is Build.NO:
... |
def runnable(obj, *args, **kwargs):
if not isinstance(obj, Node):
raise GPflowError(
'AutoFlow works only with node-like objects.')
if obj.is_built_coherence(obj.graph) is Build.NO:
raise GPflowError('Not built with "{graph}".'.format(g... | def runnable(obj, *args, **kwargs):
if not isinstance(obj, Node):
raise GPflowError(
'AutoFlow works only with node-like objects.')
if obj.is_built_coherence(obj.graph) is Build.NO:
raise GPflowError('Not built with "{graph}".'.format(g... |
def initialize_variables(variables=None, session=None, force=False, **run_kwargs):
session = tf.get_default_session() if session is None else session
if variables is None:
initializer = tf.global_variables_initializer()
else:
if force:
vars_for_init = list(_initializable_tensors(... | def initialize_variables(variables=None, session=None, force=False, **run_kwargs):
session = tf.get_default_session() if session is None else session
if variables is None:
initializer = tf.global_variables_initializer()
else:
if force:
initializer = tf.variables_initializer(varia... |
def _clear(self):
self._reset_name()
self._initial_value_tensor = None
self._dataholder_tensor = None
self._is_initialized_tensor = None | def _clear(self):
self._reset_name()
self._initial_value_tensor = None
self._dataholder_tensor = None |
def _build(self):
tensor = self._build_parameter()
self._dataholder_tensor = tensor
self._is_initialized_tensor = tf.is_variable_initialized(tensor) | def _build(self):
self._dataholder_tensor = self._build_parameter() # pylint: disable=W0201 |
def _init_parameter_defaults(self):
self._initial_value_tensor = None
self._dataholder_tensor = None
self._is_initialized_tensor = None | def _init_parameter_defaults(self):
self._initial_value_tensor = None
self._dataholder_tensor = None |
def initializables(self):
if self._externally_defined:
return None
return [(self.parameter_tensor, self.is_initialized_tensor)] | def initializables(self):
if self._externally_defined:
return None
return [self.parameter_tensor] |
def read_value(self, session=None):
if session is not None and not isinstance(session, tf.Session):
raise ValueError('TensorFlow session expected as an argument.')
if session is None and self._externally_defined:
raise GPflowError('Externally defined parameter requires sessio... | def read_value(self, session=None):
if session is not None:
if not isinstance(session, tf.Session):
raise ValueError('TensorFlow session expected as session argument.')
is_built = self.is_built_coherence(session.graph)
if is_built is Build.YES:
... |
def _clear(self):
self._reset_name()
self._externally_defined = False
self._is_initialized_tensor = None
self._initial_value_tensor = None
self._unconstrained_tensor = None
self._constrained_tensor = None
self._prior_tensor = None | def _clear(self):
self._reset_name()
self._externally_defined = False # pylint: disable=W0201
self._initial_value_tensor = None # pylint: disable=W0201
self._unconstrained_tensor = None # pylint: disable=W0201
self._constrained_tensor = None # pylint: disable=W0201
... |
def _build(self):
unconstrained = self._build_parameter()
constrained = self._build_constrained(unconstrained)
prior = self._build_prior(unconstrained, constrained)
self._is_initialized_tensor = tf.is_variable_initialized(unconstrained)
self._unconstrained_tensor = unconstra... | def _build(self):
unconstrained = self._build_parameter()
constrained = self._build_constrained(unconstrained)
prior = self._build_prior(unconstrained, constrained)
self._unconstrained_tensor = unconstrained # pylint: disable=W0201
self._constrained_tensor = constrained ... |
def _build_parameter(self):
if self._externally_defined:
self._check_tensor_trainable(self.parameter_tensor)
return self.parameter_tensor
name = self._parameter_name()
tensor = misc.get_variable_by_name(name)
if tensor is not None:
raise GPflowErr... | def _build_parameter(self):
if self._externally_defined:
self._check_tensor_trainable(self.parameter_tensor)
return self.parameter_tensor
name = self._parameter_name()
tensor = misc.get_variable_by_name(name)
if tensor is not None:
raise GPflowErr... |
def _init_parameter_defaults(self):
self._is_initialized_tensor = None
self._initial_value_tensor = None
self._unconstrained_tensor = None
self._prior_tensor = None
self._constrained_tensor = None | def _init_parameter_defaults(self):
self._initial_value_tensor = None
self._unconstrained_tensor = None
self._prior_tensor = None
self._constrained_tensor = None |
def minimize(self, model, session=None, var_list=None, feed_dict=None,
maxiter=1000, initialize=False, anchor=True, **kwargs):
"""
Minimizes objective function of the model.
:param model: GPflow model with objective tensor.
:param session: Session where optimization... | def minimize(self, model, session=None, var_list=None, feed_dict=None,
maxiter=1000, initialize=True, anchor=True, **kwargs):
"""
Minimizes objective function of the model.
:param model: GPflow model with objective tensor.
:param session: Session where optimization ... |
def prob_is_largest(self, Y, mu, var, gh_x, gh_w):
# work out what the mean and variance is of the indicated latent function.
oh_on = tf.cast(tf.one_hot(tf.reshape(Y, (-1,)), self.num_classes, 1., 0.), tf.float64)
mu_selected = tf.reduce_sum(oh_on * mu, 1)
var_selected = tf.reduce_su... | def prob_is_largest(self, Y, mu, var, gh_x, gh_w):
# work out what the mean and variance is of the indicated latent function.
oh_on = tf.cast(tf.one_hot(tf.reshape(Y, (-1,)), self.num_classes, 1., 0.), tf.float64)
mu_selected = tf.reduce_sum(oh_on * mu, 1)
var_selected = tf.reduce_su... |
End of preview. Expand in Data Studio
No dataset card yet
- Downloads last month
- 3