python类__name__()的实例源码

topology.py 文件源码 项目:keras 作者: GeekLiB 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def create_input_layer(self, batch_input_shape,
                           input_dtype=None, name=None):
        if not name:
            prefix = self.__class__.__name__.lower() + '_input_'
            name = prefix + str(K.get_uid(prefix))
        if not input_dtype:
            input_dtype = K.floatx()

        self.batch_input_shape = batch_input_shape
        self.input_dtype = input_dtype

        # Instantiate the input layer.
        x = Input(batch_shape=batch_input_shape,
                  dtype=input_dtype, name=name)
        # This will build the current layer
        # and create the node connecting the current layer
        # to the input layer we just created.
        self(x)
topology.py 文件源码 项目:keras 作者: GeekLiB 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def to_json(self, **kwargs):
        '''Returns a JSON string containing the network configuration.

        To load a network from a JSON save file, use
        `keras.models.model_from_json(json_string, custom_objects={})`.
        '''
        import json

        def get_json_type(obj):
            # If obj is any numpy type
            if type(obj).__module__ == np.__name__:
                return obj.item()

            # If obj is a python 'type'
            if type(obj).__name__ == type.__name__:
                return obj.__name__

            raise TypeError('Not JSON Serializable:', obj)

        model_config = self._updated_config()
        return json.dumps(model_config, default=get_json_type, **kwargs)
models.py 文件源码 项目:keras 作者: GeekLiB 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def get_config(self):
        '''Returns the model configuration
        as a Python list.
        '''
        config = []
        if isinstance(self.layers[0], Merge):
            assert hasattr(self.layers[0], 'layers')
            layers = []
            for layer in self.layers[0].layers:
                layer_config = {'class_name': layer.__class__.__name__,
                                'config': layer.get_config()}
                layers.append(layer_config)
            merge_config = self.layers[0].get_config()
            merge_config['layers'] = layers
            config.append({'class_name': 'Merge', 'config': merge_config})
        else:
            config.append({'class_name': self.layers[0].__class__.__name__,
                           'config': self.layers[0].get_config()})
        for layer in self.layers[1:]:
            config.append({'class_name': layer.__class__.__name__,
                           'config': layer.get_config()})
        return copy.deepcopy(config)
test_utils.py 文件源码 项目:supvisors 作者: julien6387 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def test_linear_regression_numpy(self):
        """ Test the linear regression using numpy (if installed). """
        # test that numpy is installed
        try:
            import numpy
            numpy.__name__
        except ImportError:
            raise unittest.SkipTest('cannot test as optional numpy is not installed')
        # perform the test with numpy
        from supvisors.utils import get_linear_regression, get_simple_linear_regression
        xdata = [2, 4, 6, 8, 10, 12]
        ydata = [3, 4, 5, 6, 7, 8]
        # test linear regression
        a, b = get_linear_regression(xdata, ydata)
        self.assertAlmostEqual(0.5, a)
        self.assertAlmostEqual(2.0, b)
        # test simple linear regression
        a, b = get_simple_linear_regression(ydata)
        self.assertAlmostEqual(1.0, a)
        self.assertAlmostEqual(3.0, b)
topology.py 文件源码 项目:deep-learning-keras-projects 作者: jasmeetsb 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def create_input_layer(self, batch_input_shape,
                           input_dtype=None, name=None):
        if not name:
            prefix = self.__class__.__name__.lower() + '_input_'
            name = prefix + str(K.get_uid(prefix))
        if not input_dtype:
            input_dtype = K.floatx()

        self.batch_input_shape = batch_input_shape
        self.input_dtype = input_dtype

        # Instantiate the input layer.
        x = Input(batch_shape=batch_input_shape,
                  dtype=input_dtype, name=name)
        # This will build the current layer
        # and create the node connecting the current layer
        # to the input layer we just created.
        self(x)
topology.py 文件源码 项目:deep-learning-keras-projects 作者: jasmeetsb 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def to_json(self, **kwargs):
        """Returns a JSON string containing the network configuration.

        To load a network from a JSON save file, use
        `keras.models.model_from_json(json_string, custom_objects={})`.
        """
        import json

        def get_json_type(obj):
            # If obj is any numpy type
            if type(obj).__module__ == np.__name__:
                return obj.item()

            # If obj is a python 'type'
            if type(obj).__name__ == type.__name__:
                return obj.__name__

            raise TypeError('Not JSON Serializable:', obj)

        model_config = self._updated_config()
        return json.dumps(model_config, default=get_json_type, **kwargs)
models.py 文件源码 项目:deep-learning-keras-projects 作者: jasmeetsb 项目源码 文件源码 阅读 101 收藏 0 点赞 0 评论 0
def get_config(self):
        """Returns the model configuration
        as a Python list.
        """
        config = []
        if isinstance(self.layers[0], Merge):
            assert hasattr(self.layers[0], 'layers')
            layers = []
            for layer in self.layers[0].layers:
                layer_config = {'class_name': layer.__class__.__name__,
                                'config': layer.get_config()}
                layers.append(layer_config)
            merge_config = self.layers[0].get_config()
            merge_config['layers'] = layers
            config.append({'class_name': 'Merge', 'config': merge_config})
        else:
            config.append({'class_name': self.layers[0].__class__.__name__,
                           'config': self.layers[0].get_config()})
        for layer in self.layers[1:]:
            config.append({'class_name': layer.__class__.__name__,
                           'config': layer.get_config()})
        return copy.deepcopy(config)
data.py 文件源码 项目:tfnn 作者: MorvanZhou 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def __init__(self, xs, ys, name=None):
        """
        Input data sets.
        :param xs: data, shape(n_samples, n_xs), accept numpy, pandas, list
        :param ys: labels, shape(n_samples, n_ys), accept numpy, pandas, list
        """
        if (type(xs).__module__ == np.__name__) & (type(ys).__module__ == np.__name__):
            self.module = 'numpy_data'
        elif ('pandas' in type(xs).__module__) & ('pandas' in type(ys).__module__):
            xs, ys = np.asarray(xs), np.asarray(ys)
        elif (type(xs) == list) & (type(ys) == list):
            xs, ys = np.asarray(xs), np.asarray(ys)
        else:
            raise TypeError('all data type must be numpy or pandas')
        if ys.ndim < 2:
            ys = ys[:, np.newaxis]
        if xs.ndim < 2:
            xs = xs[:, np.newaxis]

        self.n_xfeatures = xs.shape[-1]     # col for 2 dims, channel for 3 dims
        self.n_yfeatures = ys.shape[-1]     # col for 2 dims,
        self.data = np.hstack((xs, ys))
        self.n_samples = ys.shape[0]
        self.name = name
sklearn_utils.py 文件源码 项目:SPHERE-HyperStream 作者: IRC-SPHERE 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def serialise_dict(dd):
    out = {}

    for kk, vv in dd.iteritems():
        if isinstance(vv, type):
            continue

        try:
            if vv is None:
                out[kk] = None

            elif type(vv).__module__ == numpy_name:
                out[kk] = vv.tolist()

            elif isinstance(vv, dict):
                out[kk] = serialise_dict(vv)

            elif isinstance(vv, (str, list, bool, int, float)):
                out[kk] = vv

        except Exception as ex:
            raise ex

    return out
tf-keras-skeleton.py 文件源码 项目:LIE 作者: EmbraceLife 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def get(identifier):
      if identifier is None:
        return linear
      if isinstance(identifier, six.string_types):
        identifier = str(identifier)
        return deserialize(identifier)
      elif callable(identifier):
        if isinstance(identifier, Layer):
          logging.warning(
              'Do not pass a layer instance (such as {identifier}) as the '
              'activation argument of another layer. Instead, advanced '
              'activation layers should be used just like any other '
              'layer in a model.'.format(identifier=identifier.__class__.__name__))
        return identifier
      else:
        raise ValueError('Could not interpret '
                         'activation function identifier:', identifier)

## backend.py
tf-keras-skeleton.py 文件源码 项目:LIE 作者: EmbraceLife 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def count_params(self):
            """Count the total number of scalars composing the weights.

            Returns:
                An integer count.

            Raises:
                RuntimeError: if the layer isn't yet built
                    (in which case its weights aren't yet defined).
            """
            if not self.built:
              if self.__class__.__name__ == 'Sequential':
                self.build()  # pylint: disable=no-value-for-parameter
              else:
                raise RuntimeError('You tried to call `count_params` on ' + self.name +
                                   ', but the layer isn\'t built. '
                                   'You can build it manually via: `' + self.name +
                                   '.build(batch_input_shape)`.')
            return sum([K.count_params(p) for p in self.weights])
tf-keras-skeleton.py 文件源码 项目:LIE 作者: EmbraceLife 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def _updated_config(self):
            """Util hared between different serialization methods.

            Returns:
                Model config with Keras version information added.
            """
            from tensorflow.contrib.keras.python.keras import __version__ as keras_version  # pylint: disable=g-import-not-at-top

            config = self.get_config()
            model_config = {
                'class_name': self.__class__.__name__,
                'config': config,
                'keras_version': keras_version,
                'backend': K.backend()
            }
            return model_config
topology.py 文件源码 项目:keras-customized 作者: ambrite 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def create_input_layer(self, batch_input_shape,
                           input_dtype=None, name=None):
        if not name:
            prefix = self.__class__.__name__.lower() + '_input_'
            name = prefix + str(K.get_uid(prefix))
        if not input_dtype:
            input_dtype = K.floatx()

        self.batch_input_shape = batch_input_shape
        self.input_dtype = input_dtype

        # Instantiate the input layer.
        x = Input(batch_shape=batch_input_shape,
                  dtype=input_dtype, name=name)
        # This will build the current layer
        # and create the node connecting the current layer
        # to the input layer we just created.
        self(x)
topology.py 文件源码 项目:keras-customized 作者: ambrite 项目源码 文件源码 阅读 61 收藏 0 点赞 0 评论 0
def to_json(self, **kwargs):
        '''Returns a JSON string containing the network configuration.

        To load a network from a JSON save file, use
        `keras.models.model_from_json(json_string, custom_objects={})`.
        '''
        import json

        def get_json_type(obj):
            # If obj is any numpy type
            if type(obj).__module__ == np.__name__:
                return obj.item()

            # If obj is a python 'type'
            if type(obj).__name__ == type.__name__:
                return obj.__name__

            raise TypeError('Not JSON Serializable:', obj)

        model_config = self._updated_config()
        return json.dumps(model_config, default=get_json_type, **kwargs)
models.py 文件源码 项目:keras-customized 作者: ambrite 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def get_config(self):
        '''Returns the model configuration
        as a Python list.
        '''
        config = []
        if isinstance(self.layers[0], Merge):
            assert hasattr(self.layers[0], 'layers')
            layers = []
            for layer in self.layers[0].layers:
                layer_config = {'class_name': layer.__class__.__name__,
                                'config': layer.get_config()}
                layers.append(layer_config)
            merge_config = self.layers[0].get_config()
            merge_config['layers'] = layers
            config.append({'class_name': 'Merge', 'config': merge_config})
        else:
            config.append({'class_name': self.layers[0].__class__.__name__,
                           'config': self.layers[0].get_config()})
        for layer in self.layers[1:]:
            config.append({'class_name': layer.__class__.__name__,
                           'config': layer.get_config()})
        return copy.deepcopy(config)
imdb3.py 文件源码 项目:lstm_tensorflow_imdb 作者: AaronZhouQian 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def binary_one_hot(x):
    try:
        if type(x).__module__ == np.__name__:
            dim0 = x.shape[0]
        elif isinstance(x, list):
            dim0 = len(x)
        else:
            raise TypeError
    except TypeError:
        print("Expecting input type to be one of {list, numpy.ndarray}. Received %s" % type(x))

    dim1 = 2
    output = np.zeros((dim0, dim1))
    for i in range(dim0):
        output[i, x[i]] = 1
    return output
imdb2.py 文件源码 项目:lstm_tensorflow_imdb 作者: AaronZhouQian 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def binary_one_hot(x):
    try:
        if type(x).__module__ == np.__name__:
            dim0 = x.shape[0]
        elif isinstance(x, list):
            dim0 = len(x)
        else:
            raise TypeError
    except TypeError:
        print("Expecting input type to be one of {list, numpy.ndarray}. Received %s" % type(x))

    dim1 = 2
    output = np.zeros((dim0, dim1))
    for i in range(dim0):
        output[i, x[i]] = 1
    return output
imdb.py 文件源码 项目:lstm_tensorflow_imdb 作者: AaronZhouQian 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def binary_one_hot(x):
    try:
        if type(x).__module__ == np.__name__:
            dim0 = x.shape[0]
        elif isinstance(x, list):
            dim0 = len(x)
        else:
            raise TypeError
    except TypeError:
        print("Expecting input type to be one of {list, numpy.ndarray}. Received %s" % type(x))

    dim1 = 2
    output = np.zeros((dim0, dim1))
    for i in range(dim0):
        output[i, x[i]] = 1
    return output
topology.py 文件源码 项目:keras 作者: NVIDIA 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def create_input_layer(self, batch_input_shape,
                           input_dtype=None, name=None):
        if not name:
            prefix = self.__class__.__name__.lower() + '_input_'
            name = prefix + str(K.get_uid(prefix))
        if not input_dtype:
            input_dtype = K.floatx()

        self.batch_input_shape = batch_input_shape
        self.input_dtype = input_dtype

        # Instantiate the input layer.
        x = Input(batch_shape=batch_input_shape,
                  dtype=input_dtype, name=name)
        # This will build the current layer
        # and create the node connecting the current layer
        # to the input layer we just created.
        self(x)
topology.py 文件源码 项目:keras 作者: NVIDIA 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def to_json(self, **kwargs):
        """Returns a JSON string containing the network configuration.

        To load a network from a JSON save file, use
        `keras.models.model_from_json(json_string, custom_objects={})`.
        """
        import json

        def get_json_type(obj):
            # If obj is any numpy type
            if type(obj).__module__ == np.__name__:
                return obj.item()

            # If obj is a python 'type'
            if type(obj).__name__ == type.__name__:
                return obj.__name__

            raise TypeError('Not JSON Serializable:', obj)

        model_config = self._updated_config()
        return json.dumps(model_config, default=get_json_type, **kwargs)
models.py 文件源码 项目:keras 作者: NVIDIA 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def get_config(self):
        """Returns the model configuration
        as a Python list.
        """
        config = []
        if isinstance(self.layers[0], Merge):
            assert hasattr(self.layers[0], 'layers')
            layers = []
            for layer in self.layers[0].layers:
                layer_config = {'class_name': layer.__class__.__name__,
                                'config': layer.get_config()}
                layers.append(layer_config)
            merge_config = self.layers[0].get_config()
            merge_config['layers'] = layers
            config.append({'class_name': 'Merge', 'config': merge_config})
        else:
            config.append({'class_name': self.layers[0].__class__.__name__,
                           'config': self.layers[0].get_config()})
        for layer in self.layers[1:]:
            config.append({'class_name': layer.__class__.__name__,
                           'config': layer.get_config()})
        return copy.deepcopy(config)
topology.py 文件源码 项目:keras_superpixel_pooling 作者: parag2489 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def compute_output_shape(self, input_shape):
        """Computes the output shape of the layer.

        Assumes that the layer will be built
        to match that input shape provided.

        # Arguments
            input_shape: Shape tuple (tuple of integers)
                or list of shape tuples (one per output tensor of the layer).
                Shape tuples can include None for free dimensions,
                instead of an integer.

        # Returns
            An input shape tuple.
        """
        if hasattr(self, 'get_output_shape_for'):
            msg = "Class `{}.{}` defines `get_output_shape_for` but does not override `compute_output_shape`. " + \
                  "If this is a Keras 1 layer, please implement `compute_output_shape` to support Keras 2."
            warnings.warn(msg.format(type(self).__module__, type(self).__name__), stacklevel=2)
        return input_shape
topology.py 文件源码 项目:keras_superpixel_pooling 作者: parag2489 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def count_params(self):
        """Count the total number of scalars composing the weights.

        # Returns
            An integer count.

        # Raises
            RuntimeError: if the layer isn't yet built
                (in which case its weights aren't yet defined).
        """
        if not self.built:
            if self.__class__.__name__ == 'Sequential':
                self.build()
            else:
                raise RuntimeError('You tried to call `count_params` on ' +
                                   self.name + ', but the layer isn\'t built. '
                                   'You can build it manually via: `' +
                                   self.name + '.build(batch_input_shape)`.')
        return sum([K.count_params(p) for p in self.weights])
topology.py 文件源码 项目:keras_superpixel_pooling 作者: parag2489 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _updated_config(self):
        """Util hared between different serialization methods.

        # Returns
            Model config with Keras version information added.
        """
        from .. import __version__ as keras_version

        config = self.get_config()
        model_config = {
            'class_name': self.__class__.__name__,
            'config': config,
            'keras_version': keras_version,
            'backend': K.backend()
        }
        return model_config
runner.py 文件源码 项目:GPOF 作者: matt-42 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def run_impl(self, params):

        # Convert numpy types.
        for k in list(params.keys()):
            a = params[k]
            if type(a).__module__ == np.__name__:
                params[k] = a.item()

        # Check if the paramset has not already run.
        run = self.runset.find_run(params)
        if run:
            return run

        # Run the function.
        r = self.to_optimise(params)

        if r is not None:
            # Merge params and result dicts.
            run = params.copy()
            run.update(r)

        return run
topology.py 文件源码 项目:InnerOuterRNN 作者: Chemoinformatics 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def create_input_layer(self, batch_input_shape,
                           input_dtype=None, name=None):
        if not name:
            prefix = self.__class__.__name__.lower() + '_input_'
            name = prefix + str(K.get_uid(prefix))
        if not input_dtype:
            input_dtype = K.floatx()

        self.batch_input_shape = batch_input_shape
        self.input_dtype = input_dtype

        # instantiate the input layer
        x = Input(batch_shape=batch_input_shape,
                  dtype=input_dtype, name=name)
        # this will build the current layer
        # and create the node connecting the current layer
        # to the input layer we just created.
        self(x)
topology.py 文件源码 项目:InnerOuterRNN 作者: Chemoinformatics 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def to_json(self, **kwargs):
        '''Returns a JSON string containing the network configuration.

        To load a network from a JSON save file, use
        `keras.models.model_from_json(json_string, custom_objects={})`.
        '''
        import json

        def get_json_type(obj):
            # if obj is any numpy type
            if type(obj).__module__ == np.__name__:
                return obj.item()

            # if obj is a python 'type'
            if type(obj).__name__ == type.__name__:
                return obj.__name__

            raise TypeError('Not JSON Serializable:', obj)

        model_config = self._updated_config()
        return json.dumps(model_config, default=get_json_type, **kwargs)
models.py 文件源码 项目:InnerOuterRNN 作者: Chemoinformatics 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def get_config(self):
        '''Returns the model configuration
        as a Python list.
        '''
        config = []
        if self.layers[0].__class__.__name__ == 'Merge':
            assert hasattr(self.layers[0], 'layers')
            layers = []
            for layer in self.layers[0].layers:
                layer_config = {'class_name': layer.__class__.__name__,
                                'config': layer.get_config()}
                layers.append(layer_config)
            merge_config = self.layers[0].get_config()
            merge_config['layers'] = layers
            config.append({'class_name': 'Merge', 'config': merge_config})
        else:
            config.append({'class_name': self.layers[0].__class__.__name__,
                           'config': self.layers[0].get_config()})
        for layer in self.layers[1:]:
            config.append({'class_name': layer.__class__.__name__,
                           'config': layer.get_config()})
        return copy.deepcopy(config)
StateClass.py 文件源码 项目:simple_rl 作者: david-abel 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __hash__(self):
        if type(self.data).__module__ == np.__name__:
            # Numpy arrays
            return hash(str(self.data))
        elif self.data.__hash__ is None:
            return hash(tuple(self.data))
        else:
            return hash(self.data)
util.py 文件源码 项目:compresso 作者: VCG 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def get_size(variable):
        '''Get bytes of variable
        '''
        if type(variable).__module__ == np.__name__:
            variable = variable.tobytes()
        elif type(variable) is str:
            assert (all(ord(c) < 256) for c in variable)
        else:
            raise ValueError('Data type not supported')

        # checking the length of a bytestring is more accurate
        return len(variable)


问题


面经


文章

微信
公众号

扫码关注公众号