ext
stringclasses 9
values | sha
stringlengths 40
40
| content
stringlengths 3
1.04M
|
---|---|---|
py | 1a2ea122f01cb5680dc97307e94fd9cddb4075fa | '''
Created on 05.01.2014
@author: root
'''
from org.askalon.jlibcloud.compute.wrapperInterfaces.base import StorageVolume as JStorageVolume
from javaimpl.compute.utils import none_check
class StorageVolumeImpl(JStorageVolume):
'''
classdocs
'''
def __init__(self, volume):
'''
Constructor
'''
#keep a reference to access in jython
self.volume = volume
self.obj = volume
if hasattr(volume, 'uuid'):
self.uuidp = none_check(volume.uuid, "")
else:
self.uuidp = ""
if hasattr(volume, 'id'):
self.idp = none_check(volume.id, "")
else:
self.idp = ""
if hasattr(volume, 'name'):
self.namep = none_check(volume.name, "")
else:
self.namep = ""
if hasattr(volume, 'size'):
self.sizep = none_check(volume.size, -1)
else:
self.sizep = -1
if hasattr(volume, 'extra'):
self.extrap = volume.extra
else:
self.extrap = {}
if hasattr(volume, '__repr__()'):
self.reprp = volume.__repr__()
else:
self.reprp = str(volume)
def getUUID(self):
return self.uuidp
def getId(self):
return self.idp
def getName(self):
return self.namep
def getSizeGB(self):
return self.sizep
def getExtra(self):
return self.extrap
def attach(self, node, device=None):
return self.volume.attach(node.node, device)
def detach(self):
return self.volume.detach()
def destroy(self):
return self.volume.destroy()
def listSnapshots(self):
return self.volume.list_snapshots()
def createSnapshot(self, name):
return self.volume.snapshot(name)
def toString(self):
return self.reprp |
py | 1a2ea2af726cdd1dd54a38cdc9d44649d4b224ba | from __future__ import annotations
import copy as _copy
import enum
import logging as _logging
import os
import pathlib
import typing
from dataclasses import dataclass
from datetime import datetime
from inspect import getfullargspec as _getargspec
import six as _six
from flytekit.common import constants as _constants
from flytekit.common import interface as _interface
from flytekit.common import sdk_bases as _sdk_bases
from flytekit.common import utils as _common_utils
from flytekit.common.core.identifier import WorkflowExecutionIdentifier
from flytekit.common.exceptions import scopes as _exception_scopes
from flytekit.common.exceptions import user as _user_exceptions
from flytekit.common.tasks import output as _task_output
from flytekit.common.tasks import task as _base_task
from flytekit.common.types import helpers as _type_helpers
from flytekit.configuration import internal as _internal_config
from flytekit.configuration import resources as _resource_config
from flytekit.configuration import sdk as _sdk_config
from flytekit.configuration import secrets
from flytekit.engines import loader as _engine_loader
from flytekit.interfaces.stats import taggable
from flytekit.models import literals as _literal_models
from flytekit.models import task as _task_models
class SecretsManager(object):
"""
This provides a secrets resolution logic at runtime.
The resolution order is
- Try env var first. The env var should have the configuration.SECRETS_ENV_PREFIX. The env var will be all upper
cased
- If not then try the file where the name matches lower case
``configuration.SECRETS_DEFAULT_DIR/<group>/configuration.SECRETS_FILE_PREFIX<key>``
All configuration values can always be overridden by injecting an environment variable
"""
def __init__(self):
self._base_dir = str(secrets.SECRETS_DEFAULT_DIR.get()).strip()
self._file_prefix = str(secrets.SECRETS_FILE_PREFIX.get()).strip()
self._env_prefix = str(secrets.SECRETS_ENV_PREFIX.get()).strip()
def get(self, group: str, key: str) -> str:
"""
Retrieves a secret using the resolution order -> Env followed by file. If not found raises a ValueError
"""
self.check_group_key(group, key)
env_var = self.get_secrets_env_var(group, key)
fpath = self.get_secrets_file(group, key)
v = os.environ.get(env_var)
if v is not None:
return v
if os.path.exists(fpath):
with open(fpath, "r") as f:
return f.read().strip()
raise ValueError(
f"Unable to find secret for key {key} in group {group} " f"in Env Var:{env_var} and FilePath: {fpath}"
)
def get_secrets_env_var(self, group: str, key: str) -> str:
"""
Returns a string that matches the ENV Variable to look for the secrets
"""
self.check_group_key(group, key)
return f"{self._env_prefix}{group.upper()}_{key.upper()}"
def get_secrets_file(self, group: str, key: str) -> str:
"""
Returns a path that matches the file to look for the secrets
"""
self.check_group_key(group, key)
return os.path.join(self._base_dir, group.lower(), f"{self._file_prefix}{key.lower()}")
@staticmethod
def check_group_key(group: str, key: str):
if group is None or group == "":
raise ValueError("secrets group is a mandatory field.")
if key is None or key == "":
raise ValueError("secrets key is a mandatory field.")
# TODO: Clean up working dir name
class ExecutionParameters(object):
"""
This is a run-time user-centric context object that is accessible to every @task method. It can be accessed using
.. code-block:: python
flytekit.current_context()
This object provides the following
* a statsd handler
* a logging handler
* the execution ID as an :py:class:`flytekit.models.core.identifier.WorkflowExecutionIdentifier` object
* a working directory for the user to write arbitrary files to
Please do not confuse this object with the :py:class:`flytekit.FlyteContext` object.
"""
@dataclass(init=False)
class Builder(object):
stats: taggable.TaggableStats
execution_date: datetime
logging: _logging
execution_id: str
attrs: typing.Dict[str, typing.Any]
working_dir: typing.Union[os.PathLike, _common_utils.AutoDeletingTempDir]
def __init__(self, current: typing.Optional[ExecutionParameters] = None):
self.stats = current.stats if current else None
self.execution_date = current.execution_date if current else None
self.working_dir = current.working_directory if current else None
self.execution_id = current.execution_id if current else None
self.logging = current.logging if current else None
self.attrs = current._attrs if current else {}
def add_attr(self, key: str, v: typing.Any) -> ExecutionParameters.Builder:
self.attrs[key] = v
return self
def build(self) -> ExecutionParameters:
if not isinstance(self.working_dir, _common_utils.AutoDeletingTempDir):
pathlib.Path(self.working_dir).mkdir(parents=True, exist_ok=True)
return ExecutionParameters(
execution_date=self.execution_date,
stats=self.stats,
tmp_dir=self.working_dir,
execution_id=self.execution_id,
logging=self.logging,
**self.attrs,
)
@staticmethod
def new_builder(current: ExecutionParameters = None) -> Builder:
return ExecutionParameters.Builder(current=current)
def builder(self) -> Builder:
return ExecutionParameters.Builder(current=self)
def __init__(self, execution_date, tmp_dir, stats, execution_id, logging, **kwargs):
"""
Args:
execution_date: Date when the execution is running
tmp_dir: temporary directory for the execution
stats: handle to emit stats
execution_id: Identifier for the xecution
logging: handle to logging
"""
self._stats = stats
self._execution_date = execution_date
self._working_directory = tmp_dir
self._execution_id = execution_id
self._logging = logging
# AutoDeletingTempDir's should be used with a with block, which creates upon entry
self._attrs = kwargs
# It is safe to recreate the Secrets Manager
self._secrets_manager = SecretsManager()
@property
def stats(self) -> taggable.TaggableStats:
"""
A handle to a special statsd object that provides usefully tagged stats.
TODO: Usage examples and better comments
"""
return self._stats
@property
def logging(self) -> _logging:
"""
A handle to a useful logging object.
TODO: Usage examples
"""
return self._logging
@property
def working_directory(self) -> _common_utils.AutoDeletingTempDir:
"""
A handle to a special working directory for easily producing temporary files.
TODO: Usage examples
TODO: This does not always return a AutoDeletingTempDir
"""
return self._working_directory
@property
def execution_date(self) -> datetime:
"""
This is a datetime representing the time at which a workflow was started. This is consistent across all tasks
executed in a workflow or sub-workflow.
.. note::
Do NOT use this execution_date to drive any production logic. It might be useful as a tag for data to help
in debugging.
"""
return self._execution_date
@property
def execution_id(self) -> str:
"""
This is the identifier of the workflow execution within the underlying engine. It will be consistent across all
task executions in a workflow or sub-workflow execution.
.. note::
Do NOT use this execution_id to drive any production logic. This execution ID should only be used as a tag
on output data to link back to the workflow run that created it.
"""
return self._execution_id
@property
def secrets(self) -> SecretsManager:
return self._secrets_manager
def __getattr__(self, attr_name: str) -> typing.Any:
"""
This houses certain task specific context. For example in Spark, it houses the SparkSession, etc
"""
attr_name = attr_name.upper()
if self._attrs and attr_name in self._attrs:
return self._attrs[attr_name]
raise AssertionError(f"{attr_name} not available as a parameter in Flyte context - are you in right task-type?")
def has_attr(self, attr_name: str) -> bool:
attr_name = attr_name.upper()
if self._attrs and attr_name in self._attrs:
return True
return False
def get(self, key: str) -> typing.Any:
"""
Returns task specific context if present else raise an error. The returned context will match the key
"""
return self.__getattr__(attr_name=key)
class SdkRunnableContainer(_task_models.Container, metaclass=_sdk_bases.ExtendedSdkType):
"""
This is not necessarily a local-only Container object. So long as configuration is present, you can use this object
"""
def __init__(
self,
command,
args,
resources,
env,
config,
):
super(SdkRunnableContainer, self).__init__("", command, args, resources, env or {}, config)
@property
def args(self):
"""
:rtype: list[Text]
"""
return _sdk_config.SDK_PYTHON_VENV.get() + self._args
@property
def image(self):
"""
:rtype: Text
"""
return _internal_config.IMAGE.get()
@property
def env(self):
"""
:rtype: dict[Text,Text]
"""
env = super(SdkRunnableContainer, self).env.copy()
env.update(
{
_internal_config.CONFIGURATION_PATH.env_var: _internal_config.CONFIGURATION_PATH.get(),
_internal_config.IMAGE.env_var: _internal_config.IMAGE.get(),
# TODO: Phase out the below. Propeller will set these and these are not SDK specific
_internal_config.PROJECT.env_var: _internal_config.PROJECT.get(),
_internal_config.DOMAIN.env_var: _internal_config.DOMAIN.get(),
_internal_config.NAME.env_var: _internal_config.NAME.get(),
_internal_config.VERSION.env_var: _internal_config.VERSION.get(),
}
)
return env
@classmethod
def get_resources(
cls,
storage_request=None,
cpu_request=None,
gpu_request=None,
memory_request=None,
storage_limit=None,
cpu_limit=None,
gpu_limit=None,
memory_limit=None,
):
"""
:param Text storage_request:
:param Text cpu_request:
:param Text gpu_request:
:param Text memory_request:
:param Text storage_limit:
:param Text cpu_limit:
:param Text gpu_limit:
:param Text memory_limit:
"""
requests = []
if storage_request:
requests.append(
_task_models.Resources.ResourceEntry(_task_models.Resources.ResourceName.STORAGE, storage_request)
)
if cpu_request:
requests.append(_task_models.Resources.ResourceEntry(_task_models.Resources.ResourceName.CPU, cpu_request))
if gpu_request:
requests.append(_task_models.Resources.ResourceEntry(_task_models.Resources.ResourceName.GPU, gpu_request))
if memory_request:
requests.append(
_task_models.Resources.ResourceEntry(_task_models.Resources.ResourceName.MEMORY, memory_request)
)
limits = []
if storage_limit:
limits.append(
_task_models.Resources.ResourceEntry(_task_models.Resources.ResourceName.STORAGE, storage_limit)
)
if cpu_limit:
limits.append(_task_models.Resources.ResourceEntry(_task_models.Resources.ResourceName.CPU, cpu_limit))
if gpu_limit:
limits.append(_task_models.Resources.ResourceEntry(_task_models.Resources.ResourceName.GPU, gpu_limit))
if memory_limit:
limits.append(
_task_models.Resources.ResourceEntry(_task_models.Resources.ResourceName.MEMORY, memory_limit)
)
return _task_models.Resources(limits=limits, requests=requests)
class SdkRunnableTaskStyle(enum.Enum):
V0 = 0
V1 = 1
class SdkRunnableTask(_base_task.SdkTask, metaclass=_sdk_bases.ExtendedSdkType):
"""
This class includes the additional logic for building a task that executes in Python code. It has even more
validation checks to ensure proper behavior than it's superclasses.
Since an SdkRunnableTask is assumed to run by hooking into Python code, we will provide additional shortcuts and
methods on this object.
"""
def __init__(
self,
task_function,
task_type,
discovery_version,
retries,
interruptible,
deprecated,
storage_request,
cpu_request,
gpu_request,
memory_request,
storage_limit,
cpu_limit,
gpu_limit,
memory_limit,
discoverable,
timeout,
environment,
custom,
):
"""
:param task_function: Function container user code. This will be executed via the SDK's engine.
:param Text task_type: string describing the task type
:param Text discovery_version: string describing the version for task discovery purposes
:param int retries: Number of retries to attempt
:param bool interruptible: Specify whether task is interruptible
:param Text deprecated:
:param Text storage_request:
:param Text cpu_request:
:param Text gpu_request:
:param Text memory_request:
:param Text storage_limit:
:param Text cpu_limit:
:param Text gpu_limit:
:param Text memory_limit:
:param bool discoverable:
:param datetime.timedelta timeout:
:param dict[Text, Text] environment:
:param dict[Text, T] custom:
"""
# Circular dependency
from flytekit import __version__
self._task_function = task_function
super(SdkRunnableTask, self).__init__(
task_type,
_task_models.TaskMetadata(
discoverable,
_task_models.RuntimeMetadata(
_task_models.RuntimeMetadata.RuntimeType.FLYTE_SDK,
__version__,
"python",
),
timeout,
_literal_models.RetryStrategy(retries),
interruptible,
discovery_version,
deprecated,
),
# TODO: If we end up using SdkRunnableTask for the new code, make sure this is set correctly.
_interface.TypedInterface({}, {}),
custom,
container=self._get_container_definition(
storage_request=storage_request,
cpu_request=cpu_request,
gpu_request=gpu_request,
memory_request=memory_request,
storage_limit=storage_limit,
cpu_limit=cpu_limit,
gpu_limit=gpu_limit,
memory_limit=memory_limit,
environment=environment,
),
)
self.id._name = "{}.{}".format(self.task_module, self.task_function_name)
self._has_fast_registered = False
# TODO: Remove this in the future, I don't think we'll be using this.
self._task_style = SdkRunnableTaskStyle.V0
_banned_inputs = {}
_banned_outputs = {}
@_exception_scopes.system_entry_point
def add_inputs(self, inputs):
"""
Adds the inputs to this task. This can be called multiple times, but it will fail if an input with a given
name is added more than once, a name collides with an output, or if the name doesn't exist as an arg name in
the wrapped function.
:param dict[Text, flytekit.models.interface.Variable] inputs: names and variables
"""
self._validate_inputs(inputs)
self.interface.inputs.update(inputs)
@classmethod
def promote_from_model(cls, base_model):
# TODO: If the task exists in this container, we should be able to retrieve it.
raise _user_exceptions.FlyteAssertion("Cannot promote a base object to a runnable task.")
@property
def task_style(self):
return self._task_style
@property
def task_function(self):
return self._task_function
@property
def task_function_name(self):
"""
:rtype: Text
"""
return self.task_function.__name__
@property
def task_module(self):
"""
:rtype: Text
"""
return self._task_function.__module__
def validate(self):
super(SdkRunnableTask, self).validate()
missing_args = self._missing_mapped_inputs_outputs()
if len(missing_args) > 0:
raise _user_exceptions.FlyteAssertion(
"The task {} is invalid because not all inputs and outputs in the "
"task function definition were specified in @outputs and @inputs. "
"We are missing definitions for {}.".format(self, missing_args)
)
@_exception_scopes.system_entry_point
def unit_test(self, **input_map):
"""
:param dict[Text, T] input_map: Python Std input from users. We will cast these to the appropriate Flyte
literals.
:returns: Depends on the behavior of the specific task in the unit engine.
"""
return (
_engine_loader.get_engine("unit")
.get_task(self)
.execute(
_type_helpers.pack_python_std_map_to_literal_map(
input_map,
{
k: _type_helpers.get_sdk_type_from_literal_type(v.type)
for k, v in _six.iteritems(self.interface.inputs)
},
)
)
)
@_exception_scopes.system_entry_point
def local_execute(self, **input_map):
"""
:param dict[Text, T] input_map: Python Std input from users. We will cast these to the appropriate Flyte
literals.
:rtype: dict[Text, T]
:returns: The output produced by this task in Python standard format.
"""
return (
_engine_loader.get_engine("local")
.get_task(self)
.execute(
_type_helpers.pack_python_std_map_to_literal_map(
input_map,
{
k: _type_helpers.get_sdk_type_from_literal_type(v.type)
for k, v in _six.iteritems(self.interface.inputs)
},
)
)
)
def _execute_user_code(self, context, inputs):
"""
:param flytekit.engines.common.EngineContext context:
:param dict[Text, T] inputs: This variable is a bit of a misnomer, since it's both inputs and outputs. The
dictionary passed here will be passed to the user-defined function, and will have values that are a
variety of types. The T's here are Python std values for inputs. If there isn't a native Python type for
something (like Schema or Blob), they are the Flyte classes. For outputs they are OutputReferences.
(Note that these are not the same OutputReferences as in BindingData's)
:rtype: Any: the returned object from user code.
:returns: This function must return a dictionary mapping 'filenames' to Flyte Interface Entities. These
entities will be used by the engine to pass data from node to node, populate metadata, etc. etc.. Each
engine will have different behavior. For instance, the Flyte engine will upload the entities to a remote
working directory (with the names provided), which will in turn allow Flyte Propeller to push along the
workflow. Where as local engine will merely feed the outputs directly into the next node.
"""
if self.task_style == SdkRunnableTaskStyle.V0:
return _exception_scopes.user_entry_point(self.task_function)(
ExecutionParameters(
execution_date=context.execution_date,
# TODO: it might be better to consider passing the full struct
execution_id=_six.text_type(WorkflowExecutionIdentifier.promote_from_model(context.execution_id)),
stats=context.stats,
logging=context.logging,
tmp_dir=context.working_directory,
),
**inputs,
)
@_exception_scopes.system_entry_point
def execute(self, context, inputs):
"""
:param flytekit.engines.common.EngineContext context:
:param flytekit.models.literals.LiteralMap inputs:
:rtype: dict[Text, flytekit.models.common.FlyteIdlEntity]
:returns: This function must return a dictionary mapping 'filenames' to Flyte Interface Entities. These
entities will be used by the engine to pass data from node to node, populate metadata, etc. etc.. Each
engine will have different behavior. For instance, the Flyte engine will upload the entities to a remote
working directory (with the names provided), which will in turn allow Flyte Propeller to push along the
workflow. Where as local engine will merely feed the outputs directly into the next node.
"""
inputs_dict = _type_helpers.unpack_literal_map_to_sdk_python_std(
inputs, {k: _type_helpers.get_sdk_type_from_literal_type(v.type) for k, v in self.interface.inputs.items()}
)
outputs_dict = {
name: _task_output.OutputReference(_type_helpers.get_sdk_type_from_literal_type(variable.type))
for name, variable in _six.iteritems(self.interface.outputs)
}
# Old style - V0: If annotations are used to define outputs, do not append outputs to the inputs dict
if not self.task_function.__annotations__ or "return" not in self.task_function.__annotations__:
inputs_dict.update(outputs_dict)
self._execute_user_code(context, inputs_dict)
return {
_constants.OUTPUT_FILE_NAME: _literal_models.LiteralMap(
literals={k: v.sdk_value for k, v in _six.iteritems(outputs_dict)}
)
}
@_exception_scopes.system_entry_point
def fast_register(self, project, domain, name, digest, additional_distribution, dest_dir) -> str:
"""
The fast register call essentially hijacks the task container commandline.
Say an existing task container definition had a commandline like so:
flyte_venv pyflyte-execute --task-module app.workflows.my_workflow --task-name my_task
The fast register command introduces a wrapper call to fast-execute the original commandline like so:
flyte_venv pyflyte-fast-execute --additional-distribution s3://my-s3-bucket/foo/bar/12345.tar.gz --
flyte_venv pyflyte-execute --task-module app.workflows.my_workflow --task-name my_task
At execution time pyflyte-fast-execute will ensure the additional distribution (i.e. the fast-registered code)
exists before calling the original task commandline.
:param Text project: The project in which to register this task.
:param Text domain: The domain in which to register this task.
:param Text name: The name to give this task.
:param Text digest: The version in which to register this task.
:param Text additional_distribution: User-specified location for remote source code distribution.
:param Text The optional location for where to install the additional distribution at runtime
:rtype: Text: Registered identifier.
"""
original_container = self.container
container = _copy.deepcopy(original_container)
args = ["pyflyte-fast-execute", "--additional-distribution", additional_distribution]
if dest_dir:
args += ["--dest-dir", dest_dir]
args += ["--"] + container.args
container._args = args
self._container = container
try:
registered_id = self.register(project, domain, name, digest)
except Exception:
self._container = original_container
raise
self._has_fast_registered = True
self._container = original_container
return str(registered_id)
@property
def has_fast_registered(self) -> bool:
return self._has_fast_registered
def _get_container_definition(
self,
storage_request=None,
cpu_request=None,
gpu_request=None,
memory_request=None,
storage_limit=None,
cpu_limit=None,
gpu_limit=None,
memory_limit=None,
environment=None,
cls=None,
):
"""
:param Text storage_request:
:param Text cpu_request:
:param Text gpu_request:
:param Text memory_request:
:param Text storage_limit:
:param Text cpu_limit:
:param Text gpu_limit:
:param Text memory_limit:
:param dict[Text,Text] environment:
:param cls Optional[type]: Type of container to instantiate. Generally should subclass SdkRunnableContainer.
:rtype: flytekit.models.task.Container
"""
storage_limit = storage_limit or _resource_config.DEFAULT_STORAGE_LIMIT.get()
storage_request = storage_request or _resource_config.DEFAULT_STORAGE_REQUEST.get()
cpu_limit = cpu_limit or _resource_config.DEFAULT_CPU_LIMIT.get()
cpu_request = cpu_request or _resource_config.DEFAULT_CPU_REQUEST.get()
gpu_limit = gpu_limit or _resource_config.DEFAULT_GPU_LIMIT.get()
gpu_request = gpu_request or _resource_config.DEFAULT_GPU_REQUEST.get()
memory_limit = memory_limit or _resource_config.DEFAULT_MEMORY_LIMIT.get()
memory_request = memory_request or _resource_config.DEFAULT_MEMORY_REQUEST.get()
resources = SdkRunnableContainer.get_resources(
storage_request, cpu_request, gpu_request, memory_request, storage_limit, cpu_limit, gpu_limit, memory_limit
)
return (cls or SdkRunnableContainer)(
command=[],
args=[
"pyflyte-execute",
"--task-module",
self.task_module,
"--task-name",
self.task_function_name,
"--inputs",
"{{.input}}",
"--output-prefix",
"{{.outputPrefix}}",
"--raw-output-data-prefix",
"{{.rawOutputDataPrefix}}",
],
resources=resources,
env=environment,
config={},
)
def _validate_inputs(self, inputs):
"""
This method should be overridden in sub-classes that intend to do additional checks on inputs. If validation
fails, this function should raise an informative exception.
:param dict[Text, flytekit.models.interface.Variable] inputs: Input variables to validate
:raises: flytekit.common.exceptions.user.FlyteValidationException
"""
super(SdkRunnableTask, self)._validate_inputs(inputs)
for k, v in _six.iteritems(inputs):
if not self._is_argname_in_function_definition(k):
raise _user_exceptions.FlyteValidationException(
"The input named '{}' was not specified in the task function. Therefore, this input cannot be "
"provided to the task.".format(k)
)
if _type_helpers.get_sdk_type_from_literal_type(v.type) in type(self)._banned_inputs:
raise _user_exceptions.FlyteValidationException(
"The input '{}' is not an accepted input type.".format(v)
)
def _validate_outputs(self, outputs):
"""
This method should be overridden in sub-classes that intend to do additional checks on outputs. If validation
fails, this function should raise an informative exception.
:param dict[Text, flytekit.models.interface.Variable] outputs: Output variables to validate
:raises: flytekit.common.exceptions.user.FlyteValidationException
"""
super(SdkRunnableTask, self)._validate_outputs(outputs)
for k, v in _six.iteritems(outputs):
if not self._is_argname_in_function_definition(k):
raise _user_exceptions.FlyteValidationException(
"The output named '{}' was not specified in the task function. Therefore, this output cannot be "
"provided to the task.".format(k)
)
if _type_helpers.get_sdk_type_from_literal_type(v.type) in type(self)._banned_outputs:
raise _user_exceptions.FlyteValidationException(
"The output '{}' is not an accepted output type.".format(v)
)
def _get_kwarg_inputs(self):
# Trim off first parameter as it is reserved for workflow_parameters
return set(_getargspec(self.task_function).args[1:])
def _is_argname_in_function_definition(self, key):
return key in self._get_kwarg_inputs()
def _missing_mapped_inputs_outputs(self):
# Trim off first parameter as it is reserved for workflow_parameters
args = self._get_kwarg_inputs()
inputs_and_outputs = set(self.interface.outputs.keys()) | set(self.interface.inputs.keys())
return args ^ inputs_and_outputs
|
py | 1a2ea3181e94fd94bc50e28da8a2d0ae58cf4fe6 | # A sample recursive neural network for text classification
# @Time: 8/13/2020
# @Author: lnblanke
# @Email: fjh314.84@gmail.com
# @File: cnn.py
import numpy as np
import tensorflow as tf
from blocks import RNN, Dense
from model import Model
import os
path = os.path.join("glove.6B.100d.txt")
embedding_indices = {}
with open(path) as f:
for line in f:
word, coef = line.split(maxsplit = 1)
coef = np.fromstring(coef, "f", sep = " ")
embedding_indices[word] = coef
def embedding(x):
word_idx = tf.keras.datasets.imdb.get_word_index()
embedding_dim = 100
l, w = x.shape
embed = np.zeros((l, w, embedding_dim))
vec_to_word = {vec + 3: ww for ww, vec in word_idx.items()}
vec_to_word[0] = "<pad>"
vec_to_word[1] = "<sos>"
vec_to_word[2] = "<unk>"
for i in range(l):
for j in range(w):
embedding_vec = embedding_indices.get(vec_to_word[x[i][j]])
if embedding_vec is not None:
embed[i][j] = embedding_vec
return embed
word_size = 15000
(train_x, train_y), (test_x, test_y) = tf.keras.datasets.imdb.load_data(num_words = word_size)
max_len = 300
train_x = tf.keras.preprocessing.sequence.pad_sequences(train_x, max_len)[:1000]
train_y = train_y[:1000]
test_x = tf.keras.preprocessing.sequence.pad_sequences(test_x, max_len)[:200]
test_y = test_y[:200]
train_x_embed = embedding(train_x)
test_x_embed = embedding(test_x)
rate = 1e-2 # Learning rate
epoch = 100 # Learning epochs
patience = 10 # Early stop patience
model = Model("RNN")
model.add(RNN(input_size = 100, output_size = 64, units = 128))
model.add(Dense(64, 2, activation = "softmax"))
if __name__ == '__main__':
model.fit(train_x_embed, train_y, loss_func = "cross entropy loss", epochs = epoch, learning_rate = rate,
patience = patience)
pred = model.predict(test_x_embed)
print("Accuracy: %.2f" % (np.sum(pred == test_y) / len(test_y) * 100) + "%")
|
py | 1a2ea31bf03207358eb5c02a59efac22ead89f6f | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Generated code. DO NOT EDIT!
#
# Snippet for CreateDocument
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-dialogflow
# [START dialogflow_v2_generated_Documents_CreateDocument_sync]
from google.cloud import dialogflow_v2
def sample_create_document():
# Create a client
client = dialogflow_v2.DocumentsClient()
# Initialize request argument(s)
document = dialogflow_v2.Document()
document.content_uri = "content_uri_value"
document.display_name = "display_name_value"
document.mime_type = "mime_type_value"
document.knowledge_types = "AGENT_FACING_SMART_REPLY"
request = dialogflow_v2.CreateDocumentRequest(
parent="parent_value",
document=document,
)
# Make the request
operation = client.create_document(request=request)
print("Waiting for operation to complete...")
response = operation.result()
# Handle the response
print(response)
# [END dialogflow_v2_generated_Documents_CreateDocument_sync]
|
py | 1a2ea33be5b1c12b6b57d8e9ec275581e3599fc4 | #Download Data and Save Data
import urllib
print "downloading with urllib"
dl_url = http://s3.amazonaws.com/open_data/*
urllib.urlretrieve(dl_url)
# file1 = opendata_giftcards000.gz
# file2 = opendata_giving_page_projects000.gz
# file3 = opendata_giving_pages000.gz
# file4 = opendata_essays000.gz
# file5 = opendata_resources000.gz
# file6 = opendata_donations000.gz
# file7 = opendata_projects000.gz
# http://s3.amazonaws.com/open_data/opendata_giftcards000.gz
# http://s3.amazonaws.com/open_data/opendata_giving_page_projects000.gz
# http://s3.amazonaws.com/open_data/opendata_giving_pages000.gz
# http://s3.amazonaws.com/open_data/opendata_essays000.gz
# http://s3.amazonaws.com/open_data/opendata_resources000.gz
# http://s3.amazonaws.com/open_data/opendata_donations000.gz
# http://s3.amazonaws.com/open_data/opendata_projects000.gz |
py | 1a2ea363968078399a54b10dc83f806c9fe801d3 | """Initial migration
Revision ID: e4ef83148109
Revises:
Create Date: 2021-11-25 12:45:30.514576
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'e4ef83148109'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
|
py | 1a2ea3684f76dacee9cee3bfdd0a4cf2e4102106 | import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django_admin_monitoring',
version='0.1.3',
packages=find_packages(),
include_package_data=True,
license='MIT License',
description='A simple Django app that provides ability to monitor such things as user feedback in admin',
long_description=README,
url='https://github.com/eternalfame/django_admin_monitoring',
author='Vyacheslav Sukhenko',
author_email='eternalfame@mail.ru',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
) |
py | 1a2ea48516f54a1066414fdda5b0d25b2432255c | # Authors: Peter Prettenhofer <peter.prettenhofer@gmail.com> (main author)
# Mathieu Blondel (partial_fit support)
#
# License: BSD 3 clause
"""Classification and regression using Stochastic Gradient Descent (SGD)."""
import numpy as np
import warnings
from abc import ABCMeta, abstractmethod
from joblib import Parallel
from ..base import clone, is_classifier
from ._base import LinearClassifierMixin, SparseCoefMixin
from ._base import make_dataset
from ..base import BaseEstimator, RegressorMixin
from ..utils import check_array, check_random_state, check_X_y
from ..utils.extmath import safe_sparse_dot
from ..utils.multiclass import _check_partial_fit_first_call
from ..utils.validation import check_is_fitted, _check_sample_weight
from ..utils.validation import _deprecate_positional_args
from ..utils.fixes import delayed
from ..exceptions import ConvergenceWarning
from ..model_selection import StratifiedShuffleSplit, ShuffleSplit
from ._sgd_fast import _plain_sgd
from ..utils import compute_class_weight
from ._sgd_fast import Hinge
from ._sgd_fast import SquaredHinge
from ._sgd_fast import Log
from ._sgd_fast import ModifiedHuber
from ._sgd_fast import SquaredLoss
from ._sgd_fast import Huber
from ._sgd_fast import EpsilonInsensitive
from ._sgd_fast import SquaredEpsilonInsensitive
from ..utils.fixes import _joblib_parallel_args
from ..utils import deprecated
LEARNING_RATE_TYPES = {"constant": 1, "optimal": 2, "invscaling": 3,
"adaptive": 4, "pa1": 5, "pa2": 6}
PENALTY_TYPES = {"none": 0, "l2": 2, "l1": 1, "elasticnet": 3}
DEFAULT_EPSILON = 0.1
# Default value of ``epsilon`` parameter.
MAX_INT = np.iinfo(np.int32).max
class _ValidationScoreCallback:
"""Callback for early stopping based on validation score"""
def __init__(self, estimator, X_val, y_val, sample_weight_val,
classes=None):
self.estimator = clone(estimator)
self.estimator.t_ = 1 # to pass check_is_fitted
if classes is not None:
self.estimator.classes_ = classes
self.X_val = X_val
self.y_val = y_val
self.sample_weight_val = sample_weight_val
def __call__(self, coef, intercept):
est = self.estimator
est.coef_ = coef.reshape(1, -1)
est.intercept_ = np.atleast_1d(intercept)
return est.score(self.X_val, self.y_val, self.sample_weight_val)
class BaseSGD(SparseCoefMixin, BaseEstimator, metaclass=ABCMeta):
"""Base class for SGD classification and regression."""
@_deprecate_positional_args
def __init__(self, loss, *, penalty='l2', alpha=0.0001, C=1.0,
l1_ratio=0.15, fit_intercept=True, max_iter=1000, tol=1e-3,
shuffle=True, verbose=0, epsilon=0.1, random_state=None,
learning_rate="optimal", eta0=0.0, power_t=0.5,
early_stopping=False, validation_fraction=0.1,
n_iter_no_change=5, warm_start=False, average=False):
self.loss = loss
self.penalty = penalty
self.learning_rate = learning_rate
self.epsilon = epsilon
self.alpha = alpha
self.C = C
self.l1_ratio = l1_ratio
self.fit_intercept = fit_intercept
self.shuffle = shuffle
self.random_state = random_state
self.verbose = verbose
self.eta0 = eta0
self.power_t = power_t
self.early_stopping = early_stopping
self.validation_fraction = validation_fraction
self.n_iter_no_change = n_iter_no_change
self.warm_start = warm_start
self.average = average
self.max_iter = max_iter
self.tol = tol
# current tests expect init to do parameter validation
# but we are not allowed to set attributes
self._validate_params()
def set_params(self, **kwargs):
"""Set and validate the parameters of estimator.
Parameters
----------
**kwargs : dict
Estimator parameters.
Returns
-------
self : object
Estimator instance.
"""
super().set_params(**kwargs)
self._validate_params()
return self
@abstractmethod
def fit(self, X, y):
"""Fit model."""
def _validate_params(self, for_partial_fit=False):
"""Validate input params. """
if not isinstance(self.shuffle, bool):
raise ValueError("shuffle must be either True or False")
if not isinstance(self.early_stopping, bool):
raise ValueError("early_stopping must be either True or False")
if self.early_stopping and for_partial_fit:
raise ValueError("early_stopping should be False with partial_fit")
if self.max_iter is not None and self.max_iter <= 0:
raise ValueError("max_iter must be > zero. Got %f" % self.max_iter)
if not (0.0 <= self.l1_ratio <= 1.0):
raise ValueError("l1_ratio must be in [0, 1]")
if self.alpha < 0.0:
raise ValueError("alpha must be >= 0")
if self.n_iter_no_change < 1:
raise ValueError("n_iter_no_change must be >= 1")
if not (0.0 < self.validation_fraction < 1.0):
raise ValueError("validation_fraction must be in range (0, 1)")
if self.learning_rate in ("constant", "invscaling", "adaptive"):
if self.eta0 <= 0.0:
raise ValueError("eta0 must be > 0")
if self.learning_rate == "optimal" and self.alpha == 0:
raise ValueError("alpha must be > 0 since "
"learning_rate is 'optimal'. alpha is used "
"to compute the optimal learning rate.")
# raises ValueError if not registered
self._get_penalty_type(self.penalty)
self._get_learning_rate_type(self.learning_rate)
if self.loss not in self.loss_functions:
raise ValueError("The loss %s is not supported. " % self.loss)
def _get_loss_function(self, loss):
"""Get concrete ``LossFunction`` object for str ``loss``. """
try:
loss_ = self.loss_functions[loss]
loss_class, args = loss_[0], loss_[1:]
if loss in ('huber', 'epsilon_insensitive',
'squared_epsilon_insensitive'):
args = (self.epsilon, )
return loss_class(*args)
except KeyError as e:
raise ValueError("The loss %s is not supported. " % loss) from e
def _get_learning_rate_type(self, learning_rate):
try:
return LEARNING_RATE_TYPES[learning_rate]
except KeyError as e:
raise ValueError("learning rate %s "
"is not supported. " % learning_rate) from e
def _get_penalty_type(self, penalty):
penalty = str(penalty).lower()
try:
return PENALTY_TYPES[penalty]
except KeyError as e:
raise ValueError("Penalty %s is not supported. " % penalty) from e
def _allocate_parameter_mem(self, n_classes, n_features, coef_init=None,
intercept_init=None):
"""Allocate mem for parameters; initialize if provided."""
if n_classes > 2:
# allocate coef_ for multi-class
if coef_init is not None:
coef_init = np.asarray(coef_init, order="C")
if coef_init.shape != (n_classes, n_features):
raise ValueError("Provided ``coef_`` does not match "
"dataset. ")
self.coef_ = coef_init
else:
self.coef_ = np.zeros((n_classes, n_features),
dtype=np.float64, order="C")
# allocate intercept_ for multi-class
if intercept_init is not None:
intercept_init = np.asarray(intercept_init, order="C")
if intercept_init.shape != (n_classes, ):
raise ValueError("Provided intercept_init "
"does not match dataset.")
self.intercept_ = intercept_init
else:
self.intercept_ = np.zeros(n_classes, dtype=np.float64,
order="C")
else:
# allocate coef_ for binary problem
if coef_init is not None:
coef_init = np.asarray(coef_init, dtype=np.float64,
order="C")
coef_init = coef_init.ravel()
if coef_init.shape != (n_features,):
raise ValueError("Provided coef_init does not "
"match dataset.")
self.coef_ = coef_init
else:
self.coef_ = np.zeros(n_features,
dtype=np.float64,
order="C")
# allocate intercept_ for binary problem
if intercept_init is not None:
intercept_init = np.asarray(intercept_init, dtype=np.float64)
if intercept_init.shape != (1,) and intercept_init.shape != ():
raise ValueError("Provided intercept_init "
"does not match dataset.")
self.intercept_ = intercept_init.reshape(1,)
else:
self.intercept_ = np.zeros(1, dtype=np.float64, order="C")
# initialize average parameters
if self.average > 0:
self._standard_coef = self.coef_
self._standard_intercept = self.intercept_
self._average_coef = np.zeros(self.coef_.shape,
dtype=np.float64,
order="C")
self._average_intercept = np.zeros(self._standard_intercept.shape,
dtype=np.float64,
order="C")
def _make_validation_split(self, y):
"""Split the dataset between training set and validation set.
Parameters
----------
y : ndarray of shape (n_samples, )
Target values.
Returns
-------
validation_mask : ndarray of shape (n_samples, )
Equal to 1 on the validation set, 0 on the training set.
"""
n_samples = y.shape[0]
validation_mask = np.zeros(n_samples, dtype=np.uint8)
if not self.early_stopping:
# use the full set for training, with an empty validation set
return validation_mask
if is_classifier(self):
splitter_type = StratifiedShuffleSplit
else:
splitter_type = ShuffleSplit
cv = splitter_type(test_size=self.validation_fraction,
random_state=self.random_state)
idx_train, idx_val = next(cv.split(np.zeros(shape=(y.shape[0], 1)), y))
if idx_train.shape[0] == 0 or idx_val.shape[0] == 0:
raise ValueError(
"Splitting %d samples into a train set and a validation set "
"with validation_fraction=%r led to an empty set (%d and %d "
"samples). Please either change validation_fraction, increase "
"number of samples, or disable early_stopping."
% (n_samples, self.validation_fraction, idx_train.shape[0],
idx_val.shape[0]))
validation_mask[idx_val] = 1
return validation_mask
def _make_validation_score_cb(self, validation_mask, X, y, sample_weight,
classes=None):
if not self.early_stopping:
return None
return _ValidationScoreCallback(
self, X[validation_mask], y[validation_mask],
sample_weight[validation_mask], classes=classes)
# mypy error: Decorated property not supported
@deprecated("Attribute standard_coef_ was deprecated " # type: ignore
"in version 0.23 and will be removed in 1.0 "
"(renaming of 0.25).")
@property
def standard_coef_(self):
return self._standard_coef
# mypy error: Decorated property not supported
@deprecated( # type: ignore
"Attribute standard_intercept_ was deprecated "
"in version 0.23 and will be removed in 1.0 (renaming of 0.25)."
)
@property
def standard_intercept_(self):
return self._standard_intercept
# mypy error: Decorated property not supported
@deprecated("Attribute average_coef_ was deprecated " # type: ignore
"in version 0.23 and will be removed in 1.0 "
"(renaming of 0.25).")
@property
def average_coef_(self):
return self._average_coef
# mypy error: Decorated property not supported
@deprecated("Attribute average_intercept_ was deprecated " # type: ignore
"in version 0.23 and will be removed in 1.0 "
"(renaming of 0.25).")
@property
def average_intercept_(self):
return self._average_intercept
def _prepare_fit_binary(est, y, i):
"""Initialization for fit_binary.
Returns y, coef, intercept, average_coef, average_intercept.
"""
y_i = np.ones(y.shape, dtype=np.float64, order="C")
y_i[y != est.classes_[i]] = -1.0
average_intercept = 0
average_coef = None
if len(est.classes_) == 2:
if not est.average:
coef = est.coef_.ravel()
intercept = est.intercept_[0]
else:
coef = est._standard_coef.ravel()
intercept = est._standard_intercept[0]
average_coef = est._average_coef.ravel()
average_intercept = est._average_intercept[0]
else:
if not est.average:
coef = est.coef_[i]
intercept = est.intercept_[i]
else:
coef = est._standard_coef[i]
intercept = est._standard_intercept[i]
average_coef = est._average_coef[i]
average_intercept = est._average_intercept[i]
return y_i, coef, intercept, average_coef, average_intercept
def fit_binary(est, i, X, y, alpha, C, learning_rate, max_iter,
pos_weight, neg_weight, sample_weight, validation_mask=None,
random_state=None):
"""Fit a single binary classifier.
The i'th class is considered the "positive" class.
Parameters
----------
est : Estimator object
The estimator to fit
i : int
Index of the positive class
X : numpy array or sparse matrix of shape [n_samples,n_features]
Training data
y : numpy array of shape [n_samples, ]
Target values
alpha : float
The regularization parameter
C : float
Maximum step size for passive aggressive
learning_rate : string
The learning rate. Accepted values are 'constant', 'optimal',
'invscaling', 'pa1' and 'pa2'.
max_iter : int
The maximum number of iterations (epochs)
pos_weight : float
The weight of the positive class
neg_weight : float
The weight of the negative class
sample_weight : numpy array of shape [n_samples, ]
The weight of each sample
validation_mask : numpy array of shape [n_samples, ], default=None
Precomputed validation mask in case _fit_binary is called in the
context of a one-vs-rest reduction.
random_state : int, RandomState instance, default=None
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
"""
# if average is not true, average_coef, and average_intercept will be
# unused
y_i, coef, intercept, average_coef, average_intercept = \
_prepare_fit_binary(est, y, i)
assert y_i.shape[0] == y.shape[0] == sample_weight.shape[0]
random_state = check_random_state(random_state)
dataset, intercept_decay = make_dataset(
X, y_i, sample_weight, random_state=random_state)
penalty_type = est._get_penalty_type(est.penalty)
learning_rate_type = est._get_learning_rate_type(learning_rate)
if validation_mask is None:
validation_mask = est._make_validation_split(y_i)
classes = np.array([-1, 1], dtype=y_i.dtype)
validation_score_cb = est._make_validation_score_cb(
validation_mask, X, y_i, sample_weight, classes=classes)
# numpy mtrand expects a C long which is a signed 32 bit integer under
# Windows
seed = random_state.randint(MAX_INT)
tol = est.tol if est.tol is not None else -np.inf
coef, intercept, average_coef, average_intercept, n_iter_ = _plain_sgd(
coef, intercept, average_coef, average_intercept, est.loss_function_,
penalty_type, alpha, C, est.l1_ratio, dataset, validation_mask,
est.early_stopping, validation_score_cb, int(est.n_iter_no_change),
max_iter, tol, int(est.fit_intercept), int(est.verbose),
int(est.shuffle), seed, pos_weight, neg_weight, learning_rate_type,
est.eta0, est.power_t, est.t_, intercept_decay, est.average)
if est.average:
if len(est.classes_) == 2:
est._average_intercept[0] = average_intercept
else:
est._average_intercept[i] = average_intercept
return coef, intercept, n_iter_
class BaseSGDClassifier(LinearClassifierMixin, BaseSGD, metaclass=ABCMeta):
loss_functions = {
"hinge": (Hinge, 1.0),
"squared_hinge": (SquaredHinge, 1.0),
"perceptron": (Hinge, 0.0),
"log": (Log, ),
"modified_huber": (ModifiedHuber, ),
"squared_loss": (SquaredLoss, ),
"huber": (Huber, DEFAULT_EPSILON),
"epsilon_insensitive": (EpsilonInsensitive, DEFAULT_EPSILON),
"squared_epsilon_insensitive": (SquaredEpsilonInsensitive,
DEFAULT_EPSILON),
}
@abstractmethod
@_deprecate_positional_args
def __init__(self, loss="hinge", *, penalty='l2', alpha=0.0001,
l1_ratio=0.15, fit_intercept=True, max_iter=1000, tol=1e-3,
shuffle=True, verbose=0, epsilon=DEFAULT_EPSILON, n_jobs=None,
random_state=None, learning_rate="optimal", eta0=0.0,
power_t=0.5, early_stopping=False,
validation_fraction=0.1, n_iter_no_change=5,
class_weight=None, warm_start=False, average=False):
super().__init__(
loss=loss, penalty=penalty, alpha=alpha, l1_ratio=l1_ratio,
fit_intercept=fit_intercept, max_iter=max_iter, tol=tol,
shuffle=shuffle, verbose=verbose, epsilon=epsilon,
random_state=random_state, learning_rate=learning_rate, eta0=eta0,
power_t=power_t, early_stopping=early_stopping,
validation_fraction=validation_fraction,
n_iter_no_change=n_iter_no_change, warm_start=warm_start,
average=average)
self.class_weight = class_weight
self.n_jobs = n_jobs
def _partial_fit(self, X, y, alpha, C,
loss, learning_rate, max_iter,
classes, sample_weight,
coef_init, intercept_init):
X, y = check_X_y(X, y, accept_sparse='csr', dtype=np.float64,
order="C", accept_large_sparse=False)
n_samples, n_features = X.shape
_check_partial_fit_first_call(self, classes)
n_classes = self.classes_.shape[0]
# Allocate datastructures from input arguments
self._expanded_class_weight = compute_class_weight(
self.class_weight, classes=self.classes_, y=y)
sample_weight = _check_sample_weight(sample_weight, X)
if getattr(self, "coef_", None) is None or coef_init is not None:
self._allocate_parameter_mem(n_classes, n_features,
coef_init, intercept_init)
elif n_features != self.coef_.shape[-1]:
raise ValueError("Number of features %d does not match previous "
"data %d." % (n_features, self.coef_.shape[-1]))
self.loss_function_ = self._get_loss_function(loss)
if not hasattr(self, "t_"):
self.t_ = 1.0
# delegate to concrete training procedure
if n_classes > 2:
self._fit_multiclass(X, y, alpha=alpha, C=C,
learning_rate=learning_rate,
sample_weight=sample_weight,
max_iter=max_iter)
elif n_classes == 2:
self._fit_binary(X, y, alpha=alpha, C=C,
learning_rate=learning_rate,
sample_weight=sample_weight,
max_iter=max_iter)
else:
raise ValueError(
"The number of classes has to be greater than one;"
" got %d class" % n_classes)
return self
def _fit(self, X, y, alpha, C, loss, learning_rate, coef_init=None,
intercept_init=None, sample_weight=None):
self._validate_params()
if hasattr(self, "classes_"):
self.classes_ = None
X, y = self._validate_data(X, y, accept_sparse='csr',
dtype=np.float64, order="C",
accept_large_sparse=False)
# labels can be encoded as float, int, or string literals
# np.unique sorts in asc order; largest class id is positive class
classes = np.unique(y)
if self.warm_start and hasattr(self, "coef_"):
if coef_init is None:
coef_init = self.coef_
if intercept_init is None:
intercept_init = self.intercept_
else:
self.coef_ = None
self.intercept_ = None
if self.average > 0:
self._standard_coef = self.coef_
self._standard_intercept = self.intercept_
self._average_coef = None
self._average_intercept = None
# Clear iteration count for multiple call to fit.
self.t_ = 1.0
self._partial_fit(X, y, alpha, C, loss, learning_rate, self.max_iter,
classes, sample_weight, coef_init, intercept_init)
if (self.tol is not None and self.tol > -np.inf
and self.n_iter_ == self.max_iter):
warnings.warn("Maximum number of iteration reached before "
"convergence. Consider increasing max_iter to "
"improve the fit.",
ConvergenceWarning)
return self
def _fit_binary(self, X, y, alpha, C, sample_weight,
learning_rate, max_iter):
"""Fit a binary classifier on X and y. """
coef, intercept, n_iter_ = fit_binary(self, 1, X, y, alpha, C,
learning_rate, max_iter,
self._expanded_class_weight[1],
self._expanded_class_weight[0],
sample_weight,
random_state=self.random_state)
self.t_ += n_iter_ * X.shape[0]
self.n_iter_ = n_iter_
# need to be 2d
if self.average > 0:
if self.average <= self.t_ - 1:
self.coef_ = self._average_coef.reshape(1, -1)
self.intercept_ = self._average_intercept
else:
self.coef_ = self._standard_coef.reshape(1, -1)
self._standard_intercept = np.atleast_1d(intercept)
self.intercept_ = self._standard_intercept
else:
self.coef_ = coef.reshape(1, -1)
# intercept is a float, need to convert it to an array of length 1
self.intercept_ = np.atleast_1d(intercept)
def _fit_multiclass(self, X, y, alpha, C, learning_rate,
sample_weight, max_iter):
"""Fit a multi-class classifier by combining binary classifiers
Each binary classifier predicts one class versus all others. This
strategy is called OvA (One versus All) or OvR (One versus Rest).
"""
# Precompute the validation split using the multiclass labels
# to ensure proper balancing of the classes.
validation_mask = self._make_validation_split(y)
# Use joblib to fit OvA in parallel.
# Pick the random seed for each job outside of fit_binary to avoid
# sharing the estimator random state between threads which could lead
# to non-deterministic behavior
random_state = check_random_state(self.random_state)
seeds = random_state.randint(MAX_INT, size=len(self.classes_))
result = Parallel(n_jobs=self.n_jobs, verbose=self.verbose,
**_joblib_parallel_args(require="sharedmem"))(
delayed(fit_binary)(self, i, X, y, alpha, C, learning_rate,
max_iter, self._expanded_class_weight[i],
1., sample_weight,
validation_mask=validation_mask,
random_state=seed)
for i, seed in enumerate(seeds))
# take the maximum of n_iter_ over every binary fit
n_iter_ = 0.
for i, (_, intercept, n_iter_i) in enumerate(result):
self.intercept_[i] = intercept
n_iter_ = max(n_iter_, n_iter_i)
self.t_ += n_iter_ * X.shape[0]
self.n_iter_ = n_iter_
if self.average > 0:
if self.average <= self.t_ - 1.0:
self.coef_ = self._average_coef
self.intercept_ = self._average_intercept
else:
self.coef_ = self._standard_coef
self._standard_intercept = np.atleast_1d(self.intercept_)
self.intercept_ = self._standard_intercept
def partial_fit(self, X, y, classes=None, sample_weight=None):
"""Perform one epoch of stochastic gradient descent on given samples.
Internally, this method uses ``max_iter = 1``. Therefore, it is not
guaranteed that a minimum of the cost function is reached after calling
it once. Matters such as objective convergence and early stopping
should be handled by the user.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Subset of the training data.
y : ndarray of shape (n_samples,)
Subset of the target values.
classes : ndarray of shape (n_classes,), default=None
Classes across all calls to partial_fit.
Can be obtained by via `np.unique(y_all)`, where y_all is the
target vector of the entire dataset.
This argument is required for the first call to partial_fit
and can be omitted in the subsequent calls.
Note that y doesn't need to contain all labels in `classes`.
sample_weight : array-like, shape (n_samples,), default=None
Weights applied to individual samples.
If not provided, uniform weights are assumed.
Returns
-------
self :
Returns an instance of self.
"""
self._validate_params(for_partial_fit=True)
if self.class_weight in ['balanced']:
raise ValueError("class_weight '{0}' is not supported for "
"partial_fit. In order to use 'balanced' weights,"
" use compute_class_weight('{0}', "
"classes=classes, y=y). "
"In place of y you can us a large enough sample "
"of the full training set target to properly "
"estimate the class frequency distributions. "
"Pass the resulting weights as the class_weight "
"parameter.".format(self.class_weight))
return self._partial_fit(X, y, alpha=self.alpha, C=1.0, loss=self.loss,
learning_rate=self.learning_rate, max_iter=1,
classes=classes, sample_weight=sample_weight,
coef_init=None, intercept_init=None)
def fit(self, X, y, coef_init=None, intercept_init=None,
sample_weight=None):
"""Fit linear model with Stochastic Gradient Descent.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training data.
y : ndarray of shape (n_samples,)
Target values.
coef_init : ndarray of shape (n_classes, n_features), default=None
The initial coefficients to warm-start the optimization.
intercept_init : ndarray of shape (n_classes,), default=None
The initial intercept to warm-start the optimization.
sample_weight : array-like, shape (n_samples,), default=None
Weights applied to individual samples.
If not provided, uniform weights are assumed. These weights will
be multiplied with class_weight (passed through the
constructor) if class_weight is specified.
Returns
-------
self :
Returns an instance of self.
"""
return self._fit(X, y, alpha=self.alpha, C=1.0,
loss=self.loss, learning_rate=self.learning_rate,
coef_init=coef_init, intercept_init=intercept_init,
sample_weight=sample_weight)
class SGDClassifier(BaseSGDClassifier):
"""Linear classifiers (SVM, logistic regression, etc.) with SGD training.
This estimator implements regularized linear models with stochastic
gradient descent (SGD) learning: the gradient of the loss is estimated
each sample at a time and the model is updated along the way with a
decreasing strength schedule (aka learning rate). SGD allows minibatch
(online/out-of-core) learning via the `partial_fit` method.
For best results using the default learning rate schedule, the data should
have zero mean and unit variance.
This implementation works with data represented as dense or sparse arrays
of floating point values for the features. The model it fits can be
controlled with the loss parameter; by default, it fits a linear support
vector machine (SVM).
The regularizer is a penalty added to the loss function that shrinks model
parameters towards the zero vector using either the squared euclidean norm
L2 or the absolute norm L1 or a combination of both (Elastic Net). If the
parameter update crosses the 0.0 value because of the regularizer, the
update is truncated to 0.0 to allow for learning sparse models and achieve
online feature selection.
Read more in the :ref:`User Guide <sgd>`.
Parameters
----------
loss : str, default='hinge'
The loss function to be used. Defaults to 'hinge', which gives a
linear SVM.
The possible options are 'hinge', 'log', 'modified_huber',
'squared_hinge', 'perceptron', or a regression loss: 'squared_loss',
'huber', 'epsilon_insensitive', or 'squared_epsilon_insensitive'.
The 'log' loss gives logistic regression, a probabilistic classifier.
'modified_huber' is another smooth loss that brings tolerance to
outliers as well as probability estimates.
'squared_hinge' is like hinge but is quadratically penalized.
'perceptron' is the linear loss used by the perceptron algorithm.
The other losses are designed for regression but can be useful in
classification as well; see
:class:`~sklearn.linear_model.SGDRegressor` for a description.
More details about the losses formulas can be found in the
:ref:`User Guide <sgd_mathematical_formulation>`.
penalty : {'l2', 'l1', 'elasticnet'}, default='l2'
The penalty (aka regularization term) to be used. Defaults to 'l2'
which is the standard regularizer for linear SVM models. 'l1' and
'elasticnet' might bring sparsity to the model (feature selection)
not achievable with 'l2'.
alpha : float, default=0.0001
Constant that multiplies the regularization term. The higher the
value, the stronger the regularization.
Also used to compute the learning rate when set to `learning_rate` is
set to 'optimal'.
l1_ratio : float, default=0.15
The Elastic Net mixing parameter, with 0 <= l1_ratio <= 1.
l1_ratio=0 corresponds to L2 penalty, l1_ratio=1 to L1.
Only used if `penalty` is 'elasticnet'.
fit_intercept : bool, default=True
Whether the intercept should be estimated or not. If False, the
data is assumed to be already centered.
max_iter : int, default=1000
The maximum number of passes over the training data (aka epochs).
It only impacts the behavior in the ``fit`` method, and not the
:meth:`partial_fit` method.
.. versionadded:: 0.19
tol : float, default=1e-3
The stopping criterion. If it is not None, training will stop
when (loss > best_loss - tol) for ``n_iter_no_change`` consecutive
epochs.
.. versionadded:: 0.19
shuffle : bool, default=True
Whether or not the training data should be shuffled after each epoch.
verbose : int, default=0
The verbosity level.
epsilon : float, default=0.1
Epsilon in the epsilon-insensitive loss functions; only if `loss` is
'huber', 'epsilon_insensitive', or 'squared_epsilon_insensitive'.
For 'huber', determines the threshold at which it becomes less
important to get the prediction exactly right.
For epsilon-insensitive, any differences between the current prediction
and the correct label are ignored if they are less than this threshold.
n_jobs : int, default=None
The number of CPUs to use to do the OVA (One Versus All, for
multi-class problems) computation.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.
random_state : int, RandomState instance, default=None
Used for shuffling the data, when ``shuffle`` is set to ``True``.
Pass an int for reproducible output across multiple function calls.
See :term:`Glossary <random_state>`.
learning_rate : str, default='optimal'
The learning rate schedule:
- 'constant': `eta = eta0`
- 'optimal': `eta = 1.0 / (alpha * (t + t0))`
where t0 is chosen by a heuristic proposed by Leon Bottou.
- 'invscaling': `eta = eta0 / pow(t, power_t)`
- 'adaptive': eta = eta0, as long as the training keeps decreasing.
Each time n_iter_no_change consecutive epochs fail to decrease the
training loss by tol or fail to increase validation score by tol if
early_stopping is True, the current learning rate is divided by 5.
.. versionadded:: 0.20
Added 'adaptive' option
eta0 : double, default=0.0
The initial learning rate for the 'constant', 'invscaling' or
'adaptive' schedules. The default value is 0.0 as eta0 is not used by
the default schedule 'optimal'.
power_t : double, default=0.5
The exponent for inverse scaling learning rate [default 0.5].
early_stopping : bool, default=False
Whether to use early stopping to terminate training when validation
score is not improving. If set to True, it will automatically set aside
a stratified fraction of training data as validation and terminate
training when validation score returned by the `score` method is not
improving by at least tol for n_iter_no_change consecutive epochs.
.. versionadded:: 0.20
Added 'early_stopping' option
validation_fraction : float, default=0.1
The proportion of training data to set aside as validation set for
early stopping. Must be between 0 and 1.
Only used if `early_stopping` is True.
.. versionadded:: 0.20
Added 'validation_fraction' option
n_iter_no_change : int, default=5
Number of iterations with no improvement to wait before early stopping.
.. versionadded:: 0.20
Added 'n_iter_no_change' option
class_weight : dict, {class_label: weight} or "balanced", default=None
Preset for the class_weight fit parameter.
Weights associated with classes. If not given, all classes
are supposed to have weight one.
The "balanced" mode uses the values of y to automatically adjust
weights inversely proportional to class frequencies in the input data
as ``n_samples / (n_classes * np.bincount(y))``.
warm_start : bool, default=False
When set to True, reuse the solution of the previous call to fit as
initialization, otherwise, just erase the previous solution.
See :term:`the Glossary <warm_start>`.
Repeatedly calling fit or partial_fit when warm_start is True can
result in a different solution than when calling fit a single time
because of the way the data is shuffled.
If a dynamic learning rate is used, the learning rate is adapted
depending on the number of samples already seen. Calling ``fit`` resets
this counter, while ``partial_fit`` will result in increasing the
existing counter.
average : bool or int, default=False
When set to True, computes the averaged SGD weights accross all
updates and stores the result in the ``coef_`` attribute. If set to
an int greater than 1, averaging will begin once the total number of
samples seen reaches `average`. So ``average=10`` will begin
averaging after seeing 10 samples.
Attributes
----------
coef_ : ndarray of shape (1, n_features) if n_classes == 2 else \
(n_classes, n_features)
Weights assigned to the features.
intercept_ : ndarray of shape (1,) if n_classes == 2 else (n_classes,)
Constants in decision function.
n_iter_ : int
The actual number of iterations before reaching the stopping criterion.
For multiclass fits, it is the maximum over every binary fit.
loss_function_ : concrete ``LossFunction``
classes_ : array of shape (n_classes,)
t_ : int
Number of weight updates performed during training.
Same as ``(n_iter_ * n_samples)``.
See Also
--------
sklearn.svm.LinearSVC : Linear support vector classification.
LogisticRegression : Logistic regression.
Perceptron : Inherits from SGDClassifier. ``Perceptron()`` is equivalent to
``SGDClassifier(loss="perceptron", eta0=1, learning_rate="constant",
penalty=None)``.
Examples
--------
>>> import numpy as np
>>> from sklearn.linear_model import SGDClassifier
>>> from sklearn.preprocessing import StandardScaler
>>> from sklearn.pipeline import make_pipeline
>>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])
>>> Y = np.array([1, 1, 2, 2])
>>> # Always scale the input. The most convenient way is to use a pipeline.
>>> clf = make_pipeline(StandardScaler(),
... SGDClassifier(max_iter=1000, tol=1e-3))
>>> clf.fit(X, Y)
Pipeline(steps=[('standardscaler', StandardScaler()),
('sgdclassifier', SGDClassifier())])
>>> print(clf.predict([[-0.8, -1]]))
[1]
"""
@_deprecate_positional_args
def __init__(self, loss="hinge", *, penalty='l2', alpha=0.0001,
l1_ratio=0.15,
fit_intercept=True, max_iter=1000, tol=1e-3, shuffle=True,
verbose=0, epsilon=DEFAULT_EPSILON, n_jobs=None,
random_state=None, learning_rate="optimal", eta0=0.0,
power_t=0.5, early_stopping=False, validation_fraction=0.1,
n_iter_no_change=5, class_weight=None, warm_start=False,
average=False):
super().__init__(
loss=loss, penalty=penalty, alpha=alpha, l1_ratio=l1_ratio,
fit_intercept=fit_intercept, max_iter=max_iter, tol=tol,
shuffle=shuffle, verbose=verbose, epsilon=epsilon, n_jobs=n_jobs,
random_state=random_state, learning_rate=learning_rate, eta0=eta0,
power_t=power_t, early_stopping=early_stopping,
validation_fraction=validation_fraction,
n_iter_no_change=n_iter_no_change, class_weight=class_weight,
warm_start=warm_start, average=average)
def _check_proba(self):
if self.loss not in ("log", "modified_huber"):
raise AttributeError("probability estimates are not available for"
" loss=%r" % self.loss)
@property
def predict_proba(self):
"""Probability estimates.
This method is only available for log loss and modified Huber loss.
Multiclass probability estimates are derived from binary (one-vs.-rest)
estimates by simple normalization, as recommended by Zadrozny and
Elkan.
Binary probability estimates for loss="modified_huber" are given by
(clip(decision_function(X), -1, 1) + 1) / 2. For other loss functions
it is necessary to perform proper probability calibration by wrapping
the classifier with
:class:`~sklearn.calibration.CalibratedClassifierCV` instead.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Input data for prediction.
Returns
-------
ndarray of shape (n_samples, n_classes)
Returns the probability of the sample for each class in the model,
where classes are ordered as they are in `self.classes_`.
References
----------
Zadrozny and Elkan, "Transforming classifier scores into multiclass
probability estimates", SIGKDD'02,
http://www.research.ibm.com/people/z/zadrozny/kdd2002-Transf.pdf
The justification for the formula in the loss="modified_huber"
case is in the appendix B in:
http://jmlr.csail.mit.edu/papers/volume2/zhang02c/zhang02c.pdf
"""
self._check_proba()
return self._predict_proba
def _predict_proba(self, X):
check_is_fitted(self)
if self.loss == "log":
return self._predict_proba_lr(X)
elif self.loss == "modified_huber":
binary = (len(self.classes_) == 2)
scores = self.decision_function(X)
if binary:
prob2 = np.ones((scores.shape[0], 2))
prob = prob2[:, 1]
else:
prob = scores
np.clip(scores, -1, 1, prob)
prob += 1.
prob /= 2.
if binary:
prob2[:, 0] -= prob
prob = prob2
else:
# the above might assign zero to all classes, which doesn't
# normalize neatly; work around this to produce uniform
# probabilities
prob_sum = prob.sum(axis=1)
all_zero = (prob_sum == 0)
if np.any(all_zero):
prob[all_zero, :] = 1
prob_sum[all_zero] = len(self.classes_)
# normalize
prob /= prob_sum.reshape((prob.shape[0], -1))
return prob
else:
raise NotImplementedError("predict_(log_)proba only supported when"
" loss='log' or loss='modified_huber' "
"(%r given)" % self.loss)
@property
def predict_log_proba(self):
"""Log of probability estimates.
This method is only available for log loss and modified Huber loss.
When loss="modified_huber", probability estimates may be hard zeros
and ones, so taking the logarithm is not possible.
See ``predict_proba`` for details.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Input data for prediction.
Returns
-------
T : array-like, shape (n_samples, n_classes)
Returns the log-probability of the sample for each class in the
model, where classes are ordered as they are in
`self.classes_`.
"""
self._check_proba()
return self._predict_log_proba
def _predict_log_proba(self, X):
return np.log(self.predict_proba(X))
def _more_tags(self):
return {
'_xfail_checks': {
'check_sample_weights_invariance':
'zero sample_weight is not equivalent to removing samples',
}
}
class BaseSGDRegressor(RegressorMixin, BaseSGD):
loss_functions = {
"squared_loss": (SquaredLoss, ),
"huber": (Huber, DEFAULT_EPSILON),
"epsilon_insensitive": (EpsilonInsensitive, DEFAULT_EPSILON),
"squared_epsilon_insensitive": (SquaredEpsilonInsensitive,
DEFAULT_EPSILON),
}
@abstractmethod
@_deprecate_positional_args
def __init__(self, loss="squared_loss", *, penalty="l2", alpha=0.0001,
l1_ratio=0.15, fit_intercept=True, max_iter=1000, tol=1e-3,
shuffle=True, verbose=0, epsilon=DEFAULT_EPSILON,
random_state=None, learning_rate="invscaling", eta0=0.01,
power_t=0.25, early_stopping=False, validation_fraction=0.1,
n_iter_no_change=5, warm_start=False, average=False):
super().__init__(
loss=loss, penalty=penalty, alpha=alpha, l1_ratio=l1_ratio,
fit_intercept=fit_intercept, max_iter=max_iter, tol=tol,
shuffle=shuffle, verbose=verbose, epsilon=epsilon,
random_state=random_state, learning_rate=learning_rate, eta0=eta0,
power_t=power_t, early_stopping=early_stopping,
validation_fraction=validation_fraction,
n_iter_no_change=n_iter_no_change, warm_start=warm_start,
average=average)
def _partial_fit(self, X, y, alpha, C, loss, learning_rate,
max_iter, sample_weight, coef_init, intercept_init):
X, y = self._validate_data(X, y, accept_sparse="csr", copy=False,
order='C', dtype=np.float64,
accept_large_sparse=False)
y = y.astype(np.float64, copy=False)
n_samples, n_features = X.shape
sample_weight = _check_sample_weight(sample_weight, X)
# Allocate datastructures from input arguments
if getattr(self, "coef_", None) is None:
self._allocate_parameter_mem(1, n_features, coef_init,
intercept_init)
elif n_features != self.coef_.shape[-1]:
raise ValueError("Number of features %d does not match previous "
"data %d." % (n_features, self.coef_.shape[-1]))
if self.average > 0 and getattr(self, "_average_coef", None) is None:
self._average_coef = np.zeros(n_features,
dtype=np.float64,
order="C")
self._average_intercept = np.zeros(1, dtype=np.float64, order="C")
self._fit_regressor(X, y, alpha, C, loss, learning_rate,
sample_weight, max_iter)
return self
def partial_fit(self, X, y, sample_weight=None):
"""Perform one epoch of stochastic gradient descent on given samples.
Internally, this method uses ``max_iter = 1``. Therefore, it is not
guaranteed that a minimum of the cost function is reached after calling
it once. Matters such as objective convergence and early stopping
should be handled by the user.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Subset of training data
y : numpy array of shape (n_samples,)
Subset of target values
sample_weight : array-like, shape (n_samples,), default=None
Weights applied to individual samples.
If not provided, uniform weights are assumed.
Returns
-------
self : returns an instance of self.
"""
self._validate_params(for_partial_fit=True)
return self._partial_fit(X, y, self.alpha, C=1.0,
loss=self.loss,
learning_rate=self.learning_rate, max_iter=1,
sample_weight=sample_weight, coef_init=None,
intercept_init=None)
def _fit(self, X, y, alpha, C, loss, learning_rate, coef_init=None,
intercept_init=None, sample_weight=None):
self._validate_params()
if self.warm_start and getattr(self, "coef_", None) is not None:
if coef_init is None:
coef_init = self.coef_
if intercept_init is None:
intercept_init = self.intercept_
else:
self.coef_ = None
self.intercept_ = None
# Clear iteration count for multiple call to fit.
self.t_ = 1.0
self._partial_fit(X, y, alpha, C, loss, learning_rate,
self.max_iter, sample_weight, coef_init,
intercept_init)
if (self.tol is not None and self.tol > -np.inf
and self.n_iter_ == self.max_iter):
warnings.warn("Maximum number of iteration reached before "
"convergence. Consider increasing max_iter to "
"improve the fit.",
ConvergenceWarning)
return self
def fit(self, X, y, coef_init=None, intercept_init=None,
sample_weight=None):
"""Fit linear model with Stochastic Gradient Descent.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training data
y : ndarray of shape (n_samples,)
Target values
coef_init : ndarray of shape (n_features,), default=None
The initial coefficients to warm-start the optimization.
intercept_init : ndarray of shape (1,), default=None
The initial intercept to warm-start the optimization.
sample_weight : array-like, shape (n_samples,), default=None
Weights applied to individual samples (1. for unweighted).
Returns
-------
self : returns an instance of self.
"""
return self._fit(X, y, alpha=self.alpha, C=1.0,
loss=self.loss, learning_rate=self.learning_rate,
coef_init=coef_init,
intercept_init=intercept_init,
sample_weight=sample_weight)
def _decision_function(self, X):
"""Predict using the linear model
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Returns
-------
ndarray of shape (n_samples,)
Predicted target values per element in X.
"""
check_is_fitted(self)
X = check_array(X, accept_sparse='csr')
scores = safe_sparse_dot(X, self.coef_.T,
dense_output=True) + self.intercept_
return scores.ravel()
def predict(self, X):
"""Predict using the linear model
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Returns
-------
ndarray of shape (n_samples,)
Predicted target values per element in X.
"""
return self._decision_function(X)
def _fit_regressor(self, X, y, alpha, C, loss, learning_rate,
sample_weight, max_iter):
dataset, intercept_decay = make_dataset(X, y, sample_weight)
loss_function = self._get_loss_function(loss)
penalty_type = self._get_penalty_type(self.penalty)
learning_rate_type = self._get_learning_rate_type(learning_rate)
if not hasattr(self, "t_"):
self.t_ = 1.0
validation_mask = self._make_validation_split(y)
validation_score_cb = self._make_validation_score_cb(
validation_mask, X, y, sample_weight)
random_state = check_random_state(self.random_state)
# numpy mtrand expects a C long which is a signed 32 bit integer under
# Windows
seed = random_state.randint(0, np.iinfo(np.int32).max)
tol = self.tol if self.tol is not None else -np.inf
if self.average:
coef = self._standard_coef
intercept = self._standard_intercept
average_coef = self._average_coef
average_intercept = self._average_intercept
else:
coef = self.coef_
intercept = self.intercept_
average_coef = None # Not used
average_intercept = [0] # Not used
coef, intercept, average_coef, average_intercept, self.n_iter_ = \
_plain_sgd(coef,
intercept[0],
average_coef,
average_intercept[0],
loss_function,
penalty_type,
alpha, C,
self.l1_ratio,
dataset,
validation_mask, self.early_stopping,
validation_score_cb,
int(self.n_iter_no_change),
max_iter, tol,
int(self.fit_intercept),
int(self.verbose),
int(self.shuffle),
seed,
1.0, 1.0,
learning_rate_type,
self.eta0, self.power_t, self.t_,
intercept_decay, self.average)
self.t_ += self.n_iter_ * X.shape[0]
if self.average > 0:
self._average_intercept = np.atleast_1d(average_intercept)
self._standard_intercept = np.atleast_1d(intercept)
if self.average <= self.t_ - 1.0:
# made enough updates for averaging to be taken into account
self.coef_ = average_coef
self.intercept_ = np.atleast_1d(average_intercept)
else:
self.coef_ = coef
self.intercept_ = np.atleast_1d(intercept)
else:
self.intercept_ = np.atleast_1d(intercept)
class SGDRegressor(BaseSGDRegressor):
"""Linear model fitted by minimizing a regularized empirical loss with SGD
SGD stands for Stochastic Gradient Descent: the gradient of the loss is
estimated each sample at a time and the model is updated along the way with
a decreasing strength schedule (aka learning rate).
The regularizer is a penalty added to the loss function that shrinks model
parameters towards the zero vector using either the squared euclidean norm
L2 or the absolute norm L1 or a combination of both (Elastic Net). If the
parameter update crosses the 0.0 value because of the regularizer, the
update is truncated to 0.0 to allow for learning sparse models and achieve
online feature selection.
This implementation works with data represented as dense numpy arrays of
floating point values for the features.
Read more in the :ref:`User Guide <sgd>`.
Parameters
----------
loss : str, default='squared_loss'
The loss function to be used. The possible values are 'squared_loss',
'huber', 'epsilon_insensitive', or 'squared_epsilon_insensitive'
The 'squared_loss' refers to the ordinary least squares fit.
'huber' modifies 'squared_loss' to focus less on getting outliers
correct by switching from squared to linear loss past a distance of
epsilon. 'epsilon_insensitive' ignores errors less than epsilon and is
linear past that; this is the loss function used in SVR.
'squared_epsilon_insensitive' is the same but becomes squared loss past
a tolerance of epsilon.
More details about the losses formulas can be found in the
:ref:`User Guide <sgd_mathematical_formulation>`.
penalty : {'l2', 'l1', 'elasticnet'}, default='l2'
The penalty (aka regularization term) to be used. Defaults to 'l2'
which is the standard regularizer for linear SVM models. 'l1' and
'elasticnet' might bring sparsity to the model (feature selection)
not achievable with 'l2'.
alpha : float, default=0.0001
Constant that multiplies the regularization term. The higher the
value, the stronger the regularization.
Also used to compute the learning rate when set to `learning_rate` is
set to 'optimal'.
l1_ratio : float, default=0.15
The Elastic Net mixing parameter, with 0 <= l1_ratio <= 1.
l1_ratio=0 corresponds to L2 penalty, l1_ratio=1 to L1.
Only used if `penalty` is 'elasticnet'.
fit_intercept : bool, default=True
Whether the intercept should be estimated or not. If False, the
data is assumed to be already centered.
max_iter : int, default=1000
The maximum number of passes over the training data (aka epochs).
It only impacts the behavior in the ``fit`` method, and not the
:meth:`partial_fit` method.
.. versionadded:: 0.19
tol : float, default=1e-3
The stopping criterion. If it is not None, training will stop
when (loss > best_loss - tol) for ``n_iter_no_change`` consecutive
epochs.
.. versionadded:: 0.19
shuffle : bool, default=True
Whether or not the training data should be shuffled after each epoch.
verbose : int, default=0
The verbosity level.
epsilon : float, default=0.1
Epsilon in the epsilon-insensitive loss functions; only if `loss` is
'huber', 'epsilon_insensitive', or 'squared_epsilon_insensitive'.
For 'huber', determines the threshold at which it becomes less
important to get the prediction exactly right.
For epsilon-insensitive, any differences between the current prediction
and the correct label are ignored if they are less than this threshold.
random_state : int, RandomState instance, default=None
Used for shuffling the data, when ``shuffle`` is set to ``True``.
Pass an int for reproducible output across multiple function calls.
See :term:`Glossary <random_state>`.
learning_rate : string, default='invscaling'
The learning rate schedule:
- 'constant': `eta = eta0`
- 'optimal': `eta = 1.0 / (alpha * (t + t0))`
where t0 is chosen by a heuristic proposed by Leon Bottou.
- 'invscaling': `eta = eta0 / pow(t, power_t)`
- 'adaptive': eta = eta0, as long as the training keeps decreasing.
Each time n_iter_no_change consecutive epochs fail to decrease the
training loss by tol or fail to increase validation score by tol if
early_stopping is True, the current learning rate is divided by 5.
.. versionadded:: 0.20
Added 'adaptive' option
eta0 : double, default=0.01
The initial learning rate for the 'constant', 'invscaling' or
'adaptive' schedules. The default value is 0.01.
power_t : double, default=0.25
The exponent for inverse scaling learning rate.
early_stopping : bool, default=False
Whether to use early stopping to terminate training when validation
score is not improving. If set to True, it will automatically set aside
a fraction of training data as validation and terminate
training when validation score returned by the `score` method is not
improving by at least `tol` for `n_iter_no_change` consecutive
epochs.
.. versionadded:: 0.20
Added 'early_stopping' option
validation_fraction : float, default=0.1
The proportion of training data to set aside as validation set for
early stopping. Must be between 0 and 1.
Only used if `early_stopping` is True.
.. versionadded:: 0.20
Added 'validation_fraction' option
n_iter_no_change : int, default=5
Number of iterations with no improvement to wait before early stopping.
.. versionadded:: 0.20
Added 'n_iter_no_change' option
warm_start : bool, default=False
When set to True, reuse the solution of the previous call to fit as
initialization, otherwise, just erase the previous solution.
See :term:`the Glossary <warm_start>`.
Repeatedly calling fit or partial_fit when warm_start is True can
result in a different solution than when calling fit a single time
because of the way the data is shuffled.
If a dynamic learning rate is used, the learning rate is adapted
depending on the number of samples already seen. Calling ``fit`` resets
this counter, while ``partial_fit`` will result in increasing the
existing counter.
average : bool or int, default=False
When set to True, computes the averaged SGD weights accross all
updates and stores the result in the ``coef_`` attribute. If set to
an int greater than 1, averaging will begin once the total number of
samples seen reaches `average`. So ``average=10`` will begin
averaging after seeing 10 samples.
Attributes
----------
coef_ : ndarray of shape (n_features,)
Weights assigned to the features.
intercept_ : ndarray of shape (1,)
The intercept term.
average_coef_ : ndarray of shape (n_features,)
Averaged weights assigned to the features. Only available
if ``average=True``.
.. deprecated:: 0.23
Attribute ``average_coef_`` was deprecated
in version 0.23 and will be removed in 1.0 (renaming of 0.25).
average_intercept_ : ndarray of shape (1,)
The averaged intercept term. Only available if ``average=True``.
.. deprecated:: 0.23
Attribute ``average_intercept_`` was deprecated
in version 0.23 and will be removed in 1.0 (renaming of 0.25).
n_iter_ : int
The actual number of iterations before reaching the stopping criterion.
t_ : int
Number of weight updates performed during training.
Same as ``(n_iter_ * n_samples)``.
Examples
--------
>>> import numpy as np
>>> from sklearn.linear_model import SGDRegressor
>>> from sklearn.pipeline import make_pipeline
>>> from sklearn.preprocessing import StandardScaler
>>> n_samples, n_features = 10, 5
>>> rng = np.random.RandomState(0)
>>> y = rng.randn(n_samples)
>>> X = rng.randn(n_samples, n_features)
>>> # Always scale the input. The most convenient way is to use a pipeline.
>>> reg = make_pipeline(StandardScaler(),
... SGDRegressor(max_iter=1000, tol=1e-3))
>>> reg.fit(X, y)
Pipeline(steps=[('standardscaler', StandardScaler()),
('sgdregressor', SGDRegressor())])
See Also
--------
Ridge, ElasticNet, Lasso, sklearn.svm.SVR
"""
@_deprecate_positional_args
def __init__(self, loss="squared_loss", *, penalty="l2", alpha=0.0001,
l1_ratio=0.15, fit_intercept=True, max_iter=1000, tol=1e-3,
shuffle=True, verbose=0, epsilon=DEFAULT_EPSILON,
random_state=None, learning_rate="invscaling", eta0=0.01,
power_t=0.25, early_stopping=False, validation_fraction=0.1,
n_iter_no_change=5, warm_start=False, average=False):
super().__init__(
loss=loss, penalty=penalty, alpha=alpha, l1_ratio=l1_ratio,
fit_intercept=fit_intercept, max_iter=max_iter, tol=tol,
shuffle=shuffle, verbose=verbose, epsilon=epsilon,
random_state=random_state, learning_rate=learning_rate, eta0=eta0,
power_t=power_t, early_stopping=early_stopping,
validation_fraction=validation_fraction,
n_iter_no_change=n_iter_no_change, warm_start=warm_start,
average=average)
def _more_tags(self):
return {
'_xfail_checks': {
'check_sample_weights_invariance':
'zero sample_weight is not equivalent to removing samples',
}
}
|
py | 1a2ea4a95b867ca5afe641e37e6aa7e734f024ea | """
Compai core functions
"""
from functools import partial, reduce, wraps
from operator import itemgetter
from typing import Callable, List, TypeVar
T = TypeVar('T')
def compose(*F: List[Callable]):
"""Compose the list of functions in F from right to left
Arguments:
F: List of functions
Examples:
```pycon
>>> compose(lambda x: x + 1, lambda x: x * 2)(5)
11
>>>
```
"""
return reduce(lambda f, g: lambda x: f(g(x)), F)
def fmap(f):
return partial(map, f)
def ffilter(f):
return partial(filter, f)
def none_map(func, if_none=None):
"""Returns a function that will call func if the argument is not none, and return if_none otherwise.
Examples:
```pycon
>>> f = none_map(str, if_none=const(1))
>>> f(1)
'1'
>>> f(None)
1
>>>
```
"""
@wraps(func)
def _func(x):
if x is not None:
return func(x)
return if_none()
return _func
def tupled(func):
"""Returns a tupled version of the function.
Examples:
```pycon
>>> tupled(lambda a, b: a + b)((2, 3))
5
>>>
```
"""
@wraps(func)
def _func(x):
return func(*x)
return _func
def tuple_map(*fs):
"""Returns a function that will apply every f_i for evey element of the tuple argument.
Examples:
```pycon
>>> inc = lambda x: x + 1
>>> tuple_map(None, inc)((1, 2))
(1, 3)
>>> tuple_map(inc)((1, 2))
(2, 2)
>>>
```
"""
return compose(
tuple,
fmap(
tupled(lambda i, v: fs[i](v) if i < len(fs) and fs[i] else v),
),
enumerate,
)
def dict_map(**fs):
"""Map especific elements in a dict.
Examples:
```pycon
>>> dict_map(a=int, b=str)(dict(a='1', b=123, c=True))
{'a': 1, 'b': '123', 'c': True}
>>>
```
"""
def _change_dict(d):
d = d.copy()
for k, f in fs.items():
if k in d:
d[k] = f(d[k])
return d
return _change_dict
def identity(x):
return x
def apply(f, *args):
return f(*args)
def const(x: T) -> Callable[..., T]:
"""Returns a function that will always return `x`.
Arguments:
x: Any value
Examples:
```pycon
>>> f = const('foo')
>>> f()
'foo'
>>> f(1, a='brr')
'foo'
>>>
```
"""
return lambda *_, **__: x
def length(xs):
"""Returns the length of xs.
Examples:
```pycon
>>> length([1, 2, 3])
3
>>> length(range(10))
10
>>> length(None for _ in range(10))
10
>>>
```
"""
len_ = getattr(xs, '__len__', None)
def default_len():
return sum(1 for _ in xs)
return compose(
apply,
none_map(identity, if_none=const(default_len))
)(len_)
def swap(x):
return itemgetter(1, 0)(x)
|
py | 1a2ea62077698c22303df4b8b2247d3b05a6f55f | from datetime import datetime, timedelta
import pytest
import pytz
from kaffepause.breaks.selectors import get_pending_break_invitations
from kaffepause.breaks.test.factories import BreakFactory, BreakInvitationFactory
pytestmark = pytest.mark.django_db
def test_get_break_invitations_awaiting_reply_returns_unanswered_invitations(user):
"""Should return all non-expired break invitations the user has not replied to."""
unanswered_break_invitation = BreakInvitationFactory()
unanswered_break_invitation.subject.connect(BreakFactory())
unanswered_break_invitation.addressees.connect(user)
an_hour_ago = datetime.now(pytz.utc) - timedelta(hours=10)
expired_break = BreakFactory()
expired_break.starting_at = an_hour_ago
expired_break.save()
expired_break_invitation = BreakInvitationFactory()
expired_break_invitation.subject.connect(expired_break)
expired_break_invitation.addressees.connect(user)
accepted_break_invitation = BreakInvitationFactory()
accepted_break_invitation.subject.connect(BreakFactory())
accepted_break_invitation.addressees.connect(user)
accepted_break_invitation.acceptees.connect(user)
declined_break_invitation = BreakInvitationFactory()
declined_break_invitation.subject.connect(BreakFactory())
declined_break_invitation.addressees.connect(user)
declined_break_invitation.declinees.connect(user)
actual_break_invitations = get_pending_break_invitations(actor=user)
assert unanswered_break_invitation in actual_break_invitations
assert expired_break_invitation not in actual_break_invitations
assert accepted_break_invitation not in actual_break_invitations
assert declined_break_invitation not in actual_break_invitations
def test_get_break_invitations_awaiting_reply_returns_unanswered_invitations_expired_five_minutes_ago(
user,
):
"""Should return unanswered invitations who's break has started within 5 minutes ago."""
two_minutes_ago = datetime.now(pytz.utc) - timedelta(minutes=2)
non_expired_break = BreakFactory()
non_expired_break.starting_at = two_minutes_ago
non_expired_break.save()
non_expired_break_invitation = BreakInvitationFactory()
non_expired_break_invitation.subject.connect(non_expired_break)
non_expired_break_invitation.addressees.connect(user)
ten_minutes_ago = datetime.now(pytz.utc) - timedelta(minutes=10)
expired_break = BreakFactory()
expired_break.starting_at = ten_minutes_ago
expired_break.save()
expired_break_invitation = BreakInvitationFactory()
expired_break_invitation.subject.connect(expired_break)
expired_break_invitation.addressees.connect(user)
actual_break_invitations = get_pending_break_invitations(actor=user)
assert non_expired_break_invitation in actual_break_invitations
assert expired_break_invitation not in actual_break_invitations
|
py | 1a2ea6f5dd39841efa40a1e50731abfd2df8685c | import numpy as np
from scipy.sparse import diags
from scipy.sparse import kron
from scipy.sparse import eye
from .two_particles import TwoParticles
from ..util.constants import *
from .. import Eigenstates
class TwoFermions(TwoParticles):
def get_eigenstates(self, H, max_states, eigenvalues, eigenvectors):
eigenvectors = eigenvectors.T.reshape(( max_states, *[H.N]*H.ndim) )
# Normalize the eigenvectors
eigenvectors = eigenvectors/np.sqrt(H.dx**H.ndim)
energies = []
eigenstates_array = []
#antisymmetrize eigenvectors: This is made by applying (𝜓(r1 , s1, r2 , s2) - 𝜓(r2 , s2, r1 , s1))/sqrt(2) to each state.
for i in range(max_states):
eigenstate_tmp = (eigenvectors[i] - eigenvectors[i].swapaxes(0,1))/np.sqrt(2)
norm = np.sum(eigenstate_tmp*eigenstate_tmp)*H.dx**H.ndim
TOL = 0.02
# check if is eigenstate_tmp is a normalizable eigenstate. (norm shouldn't be zero)
if norm > TOL :
# for some reason when the eigenstate is degenerated it isn't normalized
#print("norm",norm)
eigenstate_tmp = eigenstate_tmp/np.sqrt(norm)
if eigenstates_array != []: #check if it's the first eigenstate
inner_product = np.sum(eigenstates_array[-1]* eigenstate_tmp)*H.dx**H.ndim
#print("inner_product",inner_product)
else:
inner_product = 0
if np.abs(inner_product) < TOL: # check if is eigenstate_tmp is repeated. (inner_product should be zero)
eigenstates_array += [eigenstate_tmp]
energies += [eigenvalues[i]]
if H.spatial_ndim == 1:
type = "TwoIdenticalParticles1D"
elif H.spatial_ndim == 2:
type = "TwoIdenticalParticles2D"
eigenstates = Eigenstates(energies, eigenstates_array, H.extent, H.N, type)
return eigenstates |
py | 1a2ea70915788a9b5c94a3368918c20c33a3fba8 | from .Helper import StudyManage,StageControl
from .Helper.StageControl import CStageControl
from .DataStruct.DataSet import CFlowDict
|
py | 1a2ea73f55442ae5ef4c6061276deb17c954c9ee | #!/usr/bin/env python
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
d = generate_distutils_setup(
## don't do this unless you want a globally visible script
# scripts=['bin/myscript'],
packages=['rqt_smach'],
package_dir={'': 'src'},
scripts=['scripts/rqt_smach']
)
setup(**d)
|
py | 1a2ea7930e307d1b563ec44c435e5d27b999a6bf | """
Copyright 2018 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
""" Activation generator helper classes for TCAV"""
'''
The following class was modified to enable numeric class labels
'''
from abc import ABCMeta
from abc import abstractmethod
from multiprocessing import dummy as multiprocessing
import os.path
import numpy as np
import PIL.Image
import tensorflow as tf
class ActivationGeneratorInterface(object):
"""Interface for an activation generator for a model"""
__metaclass__ = ABCMeta
@abstractmethod
def process_and_load_activations(self, bottleneck_names, concepts):
pass
@abstractmethod
def get_model(self):
pass
class ActivationGeneratorBase(ActivationGeneratorInterface):
"""Basic abstract activation generator for a model"""
def __init__(self, model, acts_dir, max_examples=500):
self.model = model
self.acts_dir = acts_dir
self.max_examples = max_examples
def get_model(self):
return self.model
@abstractmethod
def get_examples_for_concept(self, concept):
pass
def get_activations_for_concept(self, concept, bottleneck):
examples = self.get_examples_for_concept(concept)
return self.get_activations_for_examples(examples, bottleneck)
def get_activations_for_examples(self, examples, bottleneck):
acts = self.model.run_examples(examples, bottleneck)
return self.model.reshape_activations(acts).squeeze()
def process_and_load_activations(self, bottleneck_names, concepts):
acts = {}
if self.acts_dir and not tf.gfile.Exists(self.acts_dir):
tf.gfile.MakeDirs(self.acts_dir)
for concept in concepts:
if concept not in acts:
acts[concept] = {}
for bottleneck_name in bottleneck_names:
acts_path = os.path.join(self.acts_dir, 'acts_{}_{}'.format(
concept, bottleneck_name)) if self.acts_dir else None
if acts_path and tf.gfile.Exists(acts_path):
with tf.gfile.Open(acts_path, 'rb') as f:
acts[concept][bottleneck_name] = np.load(f).squeeze()
tf.logging.info('Loaded {} shape {}'.format(
acts_path, acts[concept][bottleneck_name].shape))
else:
acts[concept][bottleneck_name] = self.get_activations_for_concept(
concept, bottleneck_name)
if acts_path:
tf.logging.info('{} does not exist, Making one...'.format(
acts_path))
with tf.gfile.Open(acts_path, 'wb') as f:
np.save(f, acts[concept][bottleneck_name], allow_pickle=False)
return acts
class ImageActivationGenerator(ActivationGeneratorBase):
"""Activation generator for a basic image model"""
def __init__(self, model, source_dir, acts_dir, max_examples=10):
self.source_dir = source_dir
super(ImageActivationGenerator, self).__init__(
model, acts_dir, max_examples)
def get_examples_for_concept(self, concept):
concept_dir = os.path.join(self.source_dir, concept)
print(concept_dir, concept)
img_paths = [os.path.join(concept_dir, d)
for d in tf.gfile.ListDirectory(concept_dir)]
imgs = self.load_images_from_files(img_paths, self.max_examples,
shape=self.model.get_image_shape()[:2])
return imgs
def load_image_from_file(self, filename, shape):
"""Given a filename, try to open the file. If failed, return None.
Args:
filename: location of the image file
shape: the shape of the image file to be scaled
Returns:
the image if succeeds, None if fails.
Rasies:
exception if the image was not the right shape.
"""
if not tf.gfile.Exists(filename):
tf.logging.error('Cannot find file: {}'.format(filename))
return None
try:
img = np.array(PIL.Image.open(tf.gfile.Open(filename, 'rb')).resize(
shape, PIL.Image.BILINEAR))
# Normalize pixel values to between 0 and 1.
img = np.float32(img) / 255.0
if not (len(img.shape) == 3 and img.shape[2] == 3):
return None
else:
return img
except Exception as e:
tf.logging.info(e)
return None
return img
def load_images_from_files(self, filenames, max_imgs=500,
do_shuffle=True, run_parallel=True,
shape=(299, 299),
num_workers=100):
"""Return image arrays from filenames.
Args:
filenames: locations of image files.
max_imgs: maximum number of images from filenames.
do_shuffle: before getting max_imgs files, shuffle the names or not
run_parallel: get images in parallel or not
shape: desired shape of the image
num_workers: number of workers in parallelization.
Returns:
image arrays
"""
imgs = []
# First shuffle a copy of the filenames.
filenames = filenames[:]
if do_shuffle:
np.random.shuffle(filenames)
if run_parallel:
pool = multiprocessing.Pool(num_workers)
imgs = pool.map(
lambda filename: self.load_image_from_file(filename, shape),
filenames[:max_imgs])
imgs = [img for img in imgs if img is not None]
else:
for filename in filenames:
img = self.load_image_from_file(filename, shape)
if img is not None:
imgs.append(img)
if len(imgs) >= max_imgs:
break
return np.array(imgs)
|
py | 1a2ea9756620b796158af7da3296c4fe6127c95d | import base64
import logging
from urllib import urlencode
from dateutil.tz import tzutc
import httplib2
from sharpy.exceptions import AccessDenied
from sharpy.exceptions import BadRequest
from sharpy.exceptions import CheddarError
from sharpy.exceptions import CheddarFailure
from sharpy.exceptions import NaughtyGateway
from sharpy.exceptions import NotFound
from sharpy.exceptions import PreconditionFailed
from sharpy.exceptions import UnprocessableEntity
client_log = logging.getLogger('SharpyClient')
class Client(object):
default_endpoint = 'https://cheddargetter.com/xml'
def __init__(self, username, password, product_code, cache=None,
timeout=None, endpoint=None):
'''
username - Your cheddargetter username (probably an email address)
password - Your cheddargetter password
product_code - The product code for the product you want to work with
cache - A file system path or an object which implements the httplib2
cache API (optional)
timeout - Socket level timout in seconds (optional)
endpoint - An alternate API endpoint (optional)
'''
self.username = username
self.password = password
self.product_code = product_code
self.endpoint = endpoint or self.default_endpoint
self.cache = cache
self.timeout = timeout
super(Client, self).__init__()
def build_url(self, path, params=None):
'''
Constructs the url for a cheddar API resource
'''
url = u'%s/%s/productCode/%s' % (
self.endpoint,
path,
self.product_code,
)
if params:
for key, value in params.items():
url = u'%s/%s/%s' % (url, key, value)
return url
def format_datetime(self, to_format):
if to_format == 'now':
str_dt = to_format
else:
if getattr(to_format, 'tzinfo', None) is not None:
utc_value = to_format.astimezone(tzutc())
else:
utc_value = to_format
str_dt = utc_value.strftime('%Y-%m-%dT%H:%M:%S+00:00')
return str_dt
def format_date(self, to_format):
if to_format == 'now':
str_dt = to_format
else:
if getattr(to_format, 'tzinfo', None) is not None:
utc_value = to_format.astimezone(tzutc())
else:
utc_value = to_format
str_dt = utc_value.strftime('%Y-%m-%d')
return str_dt
def make_request(self, path, params=None, data=None, method=None):
'''
Makes a request to the cheddar api using the authentication and
configuration settings available.
'''
# Setup values
url = self.build_url(path, params)
client_log.debug('Requesting: %s' % url)
method = method or 'GET'
body = None
headers = {}
cleaned_data = None
if data:
method = 'POST'
body = urlencode(data)
headers = {
'content-type':
'application/x-www-form-urlencoded; charset=UTF-8',
}
# Clean credit card info from when the request gets logged
# (remove ccv and only show last four of card num)
cleaned_data = data.copy()
if 'subscription[ccCardCode]' in cleaned_data:
del cleaned_data['subscription[ccCardCode]']
if 'subscription[ccNumber]' in cleaned_data:
ccNum = cleaned_data['subscription[ccNumber]']
cleaned_data['subscription[ccNumber]'] = ccNum[-4:]
client_log.debug('Request Method: %s' % method)
client_log.debug('Request Body (Cleaned Data): %s' % cleaned_data)
# Setup http client
h = httplib2.Http(cache=self.cache, timeout=self.timeout)
# Skip the normal http client behavior and send auth headers
# immediately to save an http request.
headers['Authorization'] = "Basic %s" % base64.standard_b64encode(
self.username + ':' + self.password).strip()
# Make request
response, content = h.request(url, method, body=body, headers=headers)
status = response.status
client_log.debug('Response Status: %d' % status)
client_log.debug('Response Content: %s' % content)
if status != 200 and status != 302:
exception_class = CheddarError
if status == 401:
exception_class = AccessDenied
elif status == 400:
exception_class = BadRequest
elif status == 404:
exception_class = NotFound
elif status == 412:
exception_class = PreconditionFailed
elif status == 500:
exception_class = CheddarFailure
elif status == 502:
exception_class = NaughtyGateway
elif status == 422:
exception_class = UnprocessableEntity
raise exception_class(response, content)
response.content = content
return response
|
py | 1a2eaa285371140e1b57d39a53c34529b0e71209 | from fastbook import *
from fastai.vision.widgets import *
def create_dataloader(path):
print(" Creating dataloader.. ")
db = DataBlock(
blocks=(ImageBlock, CategoryBlock),
get_items=get_image_files,
splitter=RandomSplitter(valid_pct=0.2, seed=42),
get_y=parent_label,
item_tfms=Resize(128))
db = db.new(
item_tfms=RandomResizedCrop(224, min_scale=0.5),
batch_tfms=aug_transforms())
dls = db.dataloaders(path)
return dls
def train_model(dls , save_model_name = "animals_prediction.pkl"):
print(" Training Model .. ")
learn = cnn_learner(dls, resnet18, metrics=error_rate)
learn.fine_tune(4)
learn.export(save_model_name)
return learn
if __name__ == "__main__":
path = Path("DATA")
animals_path = (path/"animals")
dls = create_dataloader(animals_path)
model = train_model(dls ,"animals_prediction.pkl")
|
py | 1a2eaa6573349bf9471d42646a7167c9f0a978c9 | # -*- coding: utf-8 -*-
import argparse
def parse_opts():
parser = argparse.ArgumentParser()
parser.add_argument(
'-videos_path',
nargs='+',
type=str,
help='视频所在文件夹')
parser.add_argument(
'-target_path',
nargs='+',
type=str,
help='要写入的文件夹')
parser.add_argument(
'-cut_start',
nargs='+',
default=0,
type=int,
help='从第几帧开始截取')
parser.add_argument(
'-cut_end',
nargs='+',
default=0,
type=int,
help='截取到第几帧')
args = parser.parse_args()
return args
|
End of preview. Expand
in Dataset Viewer.
No dataset card yet
- Downloads last month
- 0