Python numpy.dtype() Examples

The following are 30 code examples for showing how to use numpy.dtype(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: kimotion.py    License: MIT License 6 votes vote down vote up
def __init__(self, server):
        super().__init__()
        self.setDaemon(True)
        self._stop = threading.Event()
        self._reading = thread_lock()
        self.dt = np.dtype(np.uint16)
        self.dt = self.dt.newbyteorder('<')
        self._data = [np.zeros(WS_FRAME_SIZE, self.dt),
                      np.zeros(WS_FRAME_SIZE, self.dt)]
        self._buf = False
        self.ws = create_connection("ws://{}/".format(server)) 
Example 2
Project: disentangling_conditional_gans   Author: zalandoresearch   File: dataset.py    License: MIT License 6 votes vote down vote up
def __init__(self, resolution=1024, num_channels=3, dtype='uint8', dynamic_range=[0,255], label_size=0, label_dtype='float32'):
        self.resolution         = resolution
        self.resolution_log2    = int(np.log2(resolution))
        self.shape              = [num_channels, resolution, resolution]
        self.dtype              = dtype
        self.dynamic_range      = dynamic_range
        self.label_size         = label_size
        self.label_dtype        = label_dtype
        self._tf_minibatch_var  = None
        self._tf_lod_var        = None
        self._tf_minibatch_np   = None
        self._tf_labels_np      = None

        assert self.resolution == 2 ** self.resolution_log2
        with tf.name_scope('Dataset'):
            self._tf_minibatch_var = tf.Variable(np.int32(0), name='minibatch_var')
            self._tf_lod_var = tf.Variable(np.int32(0), name='lod_var') 
Example 3
Project: dustmaps   Author: gregreen   File: json_serializers.py    License: GNU General Public License v2.0 6 votes vote down vote up
def serialize_dtype(o):
    """
    Serializes a :obj:`numpy.dtype`.

    Args:
        o (:obj:`numpy.dtype`): :obj:`dtype` to be serialized.

    Returns:
        A dictionary that can be passed to :obj:`json.dumps`.
    """
    if len(o) == 0:
        return dict(
            _type='np.dtype',
            descr=str(o))
    return dict(
        _type='np.dtype',
        descr=o.descr)
    # res = []
    # for k in range(len(o)):
    #     res.append((o.names[k], str(o[k])))
    # return dict(
    #     _type='np.dtype',
    #     desc=res) 
Example 4
Project: dustmaps   Author: gregreen   File: json_serializers.py    License: GNU General Public License v2.0 6 votes vote down vote up
def deserialize_dtype(d):
    """
    Deserializes a JSONified :obj:`numpy.dtype`.

    Args:
        d (:obj:`dict`): A dictionary representation of a :obj:`dtype` object.

    Returns:
        A :obj:`dtype` object.
    """
    if isinstance(d['descr'], six.string_types):
        return np.dtype(d['descr'])
    descr = []
    for col in d['descr']:
        col_descr = []
        for c in col:
            if isinstance(c, six.string_types):
                col_descr.append(str(c))
            elif type(c) is list:
                col_descr.append(tuple(c))
            else:
                col_descr.append(c)
        descr.append(tuple(col_descr))
    return np.dtype(descr) 
Example 5
Project: dustmaps   Author: gregreen   File: json_serializers.py    License: GNU General Public License v2.0 6 votes vote down vote up
def serialize_ndarray_b64(o):
    """
    Serializes a :obj:`numpy.ndarray` in a format where the datatype and shape are
    human-readable, but the array data itself is binary64 encoded.

    Args:
        o (:obj:`numpy.ndarray`): :obj:`ndarray` to be serialized.

    Returns:
        A dictionary that can be passed to :obj:`json.dumps`.
    """
    if o.flags['C_CONTIGUOUS']:
        o_data = o.data
    else:
        o_data = np.ascontiguousarray(o).data
    data_b64 = base64.b64encode(o_data)
    return dict(
        _type='np.ndarray',
        data=data_b64.decode('utf-8'),
        dtype=o.dtype,
        shape=o.shape) 
Example 6
Project: dustmaps   Author: gregreen   File: json_serializers.py    License: GNU General Public License v2.0 6 votes vote down vote up
def deserialize_ndarray(d):
    """
    Deserializes a JSONified :obj:`numpy.ndarray`. Can handle arrays serialized
    using any of the methods in this module: :obj:`"npy"`, :obj:`"b64"`,
    :obj:`"readable"`.

    Args:
        d (`dict`): A dictionary representation of an :obj:`ndarray` object.

    Returns:
        An :obj:`ndarray` object.
    """
    if 'data' in d:
        x = np.fromstring(
            base64.b64decode(d['data']),
            dtype=d['dtype'])
        x.shape = d['shape']
        return x
    elif 'value' in d:
        return np.array(d['value'], dtype=d['dtype'])
    elif 'npy' in d:
        return deserialize_ndarray_npy(d)
    else:
        raise ValueError('Malformed np.ndarray encoding.') 
Example 7
Project: neural-fingerprinting   Author: StephanZheng   File: attacks_tfe.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, model, dtypestr='float32'):
        """
        :param model: An instance of the cleverhans.model.Model class.
        :param back: The backend to use. Inherited from AttackBase class.
        :param dtypestr: datatype of the input data samples and crafted
                        adversarial attacks.
        """
        # Validate the input arguments.
        if dtypestr != 'float32' and dtypestr != 'float64':
            raise ValueError("Unexpected input for argument dtypestr.")
        import tensorflow as tf
        tfe = tf.contrib.eager
        self.tf_dtype = tf.as_dtype(dtypestr)
        self.np_dtype = np.dtype(dtypestr)

        if not isinstance(model, Model):
            raise ValueError("The model argument should be an instance of"
                             " the cleverhans.model.Model class.")
        # Prepare attributes
        self.model = model
        self.dtypestr = dtypestr 
Example 8
Project: neuropythy   Author: noahbenson   File: images.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def image_reslice(image, spec, method=None, fill=0, dtype=None, weights=None, image_type=None):
    '''
    image_reslice(image, spec) yields a duplicate of the given image resliced to have the voxels
      indicated by the given image spec. Note that spec may be an image itself.

    Optional arguments that can be passed to image_interpolate() (asside from affine) are allowed
    here and are passed through.
    '''
    if image_type is None and is_image(image): image_type = to_image_type(image)
    spec = to_image_spec(spec)
    image = to_image(image)
    # we make a big mesh and interpolate at these points...
    imsh = spec['image_shape']
    (args, kw) = ([np.arange(n) for n in imsh[:3]], {'indexing': 'ij'})
    ijk = np.asarray([u.flatten() for u in np.meshgrid(*args, **kw)])
    ijk = np.dot(spec['affine'], np.vstack([ijk, np.ones([1,ijk.shape[1]])]))[:3]
    # interpolate here...
    u = image_interpolate(image, ijk, method=method, fill=fill, dtype=dtype, weights=weights)
    return to_image((np.reshape(u, imsh), spec), image_type=image_type) 
Example 9
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: sparse.py    License: Apache License 2.0 6 votes vote down vote up
def astype(self, dtype, copy=True):
        """Returns a copy of the array after casting to a specified type.
        Parameters
        ----------
        dtype : numpy.dtype or str
            The type of the returned array.
        copy : bool
            Default `True`. By default, astype always returns a newly
            allocated ndarray on the same context. If this is set to
            `False`, and the dtype requested is the same as the ndarray's
            dtype, the ndarray is returned instead of a copy.
        Examples
        --------
        >>> x = mx.nd.sparse.zeros('row_sparse', (2,3), dtype='float32')
        >>> y = x.astype('int32')
        >>> y.dtype
        <type 'numpy.int32'>
        """
        if not copy and np.dtype(dtype) == self.dtype:
            return self

        res = zeros(shape=self.shape, ctx=self.context,
                    dtype=dtype, stype=self.stype)
        self.copyto(res)
        return res 
Example 10
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: sparse.py    License: Apache License 2.0 6 votes vote down vote up
def asscipy(self):
        """Returns a ``scipy.sparse.csr.csr_matrix`` object with value copied from this array

        Examples
        --------
        >>> x = mx.nd.sparse.zeros('csr', (2,3))
        >>> y = x.asscipy()
        >>> type(y)
        <type 'scipy.sparse.csr.csr_matrix'>
        >>> y
        <2x3 sparse matrix of type '<type 'numpy.float32'>'
        with 0 stored elements in Compressed Sparse Row format>
        """
        data = self.data.asnumpy()
        indices = self.indices.asnumpy()
        indptr = self.indptr.asnumpy()
        if not spsp:
            raise ImportError("scipy is not available. \
                               Please check if the scipy python bindings are installed.")
        return spsp.csr_matrix((data, indices, indptr), shape=self.shape, dtype=self.dtype)

# pylint: disable=abstract-method 
Example 11
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: ndarray.py    License: Apache License 2.0 6 votes vote down vote up
def _new_alloc_handle(shape, ctx, delay_alloc, dtype=mx_real_t):
    """Return a new handle with specified shape and context.

    Empty handle is only used to hold results.

    Returns
    -------
    handle
        A new empty `NDArray` handle.
    """
    hdl = NDArrayHandle()
    check_call(_LIB.MXNDArrayCreateEx(
        c_array_buf(mx_uint, native_array('I', shape)),
        mx_uint(len(shape)),
        ctypes.c_int(ctx.device_typeid),
        ctypes.c_int(ctx.device_id),
        ctypes.c_int(int(delay_alloc)),
        ctypes.c_int(int(_DTYPE_NP_TO_MX[np.dtype(dtype).type])),
        ctypes.byref(hdl)))
    return hdl 
Example 12
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: ndarray.py    License: Apache License 2.0 6 votes vote down vote up
def _prepare_value_nd(self, value, vshape):
        """Given value and vshape, create an `NDArray` from value with the same
        context and dtype as the current one and broadcast it to vshape."""
        if isinstance(value, numeric_types):
            value_nd = full(shape=vshape, val=value, ctx=self.context, dtype=self.dtype)
        elif isinstance(value, NDArray):
            value_nd = value.as_in_context(self.context)
            if value_nd.dtype != self.dtype:
                value_nd = value_nd.astype(self.dtype)
        else:
            try:
                value_nd = array(value, ctx=self.context, dtype=self.dtype)
            except:
                raise TypeError('NDArray does not support assignment with non-array-like'
                                ' object %s of type %s' % (str(value), str(type(value))))
        if value_nd.shape != vshape:
            value_nd = value_nd.broadcast_to(vshape)
        return value_nd 
Example 13
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: ndarray.py    License: Apache License 2.0 6 votes vote down vote up
def dtype(self):
        """Data-type of the array's elements.

        Returns
        -------
        numpy.dtype
            This NDArray's data type.

        Examples
        --------
        >>> x = mx.nd.zeros((2,3))
        >>> x.dtype
        <type 'numpy.float32'>
        >>> y = mx.nd.zeros((2,3), dtype='int32')
        >>> y.dtype
        <type 'numpy.int32'>
        """
        mx_dtype = ctypes.c_int()
        check_call(_LIB.MXNDArrayGetDType(
            self.handle, ctypes.byref(mx_dtype)))
        return _DTYPE_MX_TO_NP[mx_dtype.value] 
Example 14
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: ndarray.py    License: Apache License 2.0 6 votes vote down vote up
def T(self):
        """Returns a copy of the array with axes transposed.

        Equivalent to ``mx.nd.transpose(self)`` except that
        self is returned if ``self.ndim < 2``.

        Unlike ``numpy.ndarray.T``, this function returns a copy
        rather than a view of the array unless ``self.ndim < 2``.

        Examples
        --------
        >>> x = mx.nd.arange(0,6).reshape((2,3))
        >>> x.asnumpy()
        array([[ 0.,  1.,  2.],
               [ 3.,  4.,  5.]], dtype=float32)
        >>> x.T.asnumpy()
        array([[ 0.,  3.],
               [ 1.,  4.],
               [ 2.,  5.]], dtype=float32)

        """
        if len(self.shape) < 2:
            return self
        return op.transpose(self)
    # pylint: enable= invalid-name, undefined-variable 
Example 15
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: ndarray.py    License: Apache License 2.0 6 votes vote down vote up
def asnumpy(self):
        """Returns a ``numpy.ndarray`` object with value copied from this array.

        Examples
        --------
        >>> x = mx.nd.ones((2,3))
        >>> y = x.asnumpy()
        >>> type(y)
        <type 'numpy.ndarray'>
        >>> y
        array([[ 1.,  1.,  1.],
               [ 1.,  1.,  1.]], dtype=float32)
        >>> z = mx.nd.ones((2,3), dtype='int32')
        >>> z.asnumpy()
        array([[1, 1, 1],
               [1, 1, 1]], dtype=int32)
        """
        data = np.empty(self.shape, dtype=self.dtype)
        check_call(_LIB.MXNDArraySyncCopyToCPU(
            self.handle,
            data.ctypes.data_as(ctypes.c_void_p),
            ctypes.c_size_t(data.size)))
        return data 
Example 16
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: ndarray.py    License: Apache License 2.0 6 votes vote down vote up
def asscalar(self):
        """Returns a scalar whose value is copied from this array.

        This function is equivalent to ``self.asnumpy()[0]``. This NDArray must have shape (1,).

        Examples
        --------
        >>> x = mx.nd.ones((1,), dtype='int32')
        >>> x.asscalar()
        1
        >>> type(x.asscalar())
        <type 'numpy.int32'>
        """
        if self.shape != (1,):
            raise ValueError("The current array is not a scalar")
        return self.asnumpy()[0] 
Example 17
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: ndarray.py    License: Apache License 2.0 6 votes vote down vote up
def copy(self):
        """Makes a copy of this ``NDArray``, keeping the same context.

        Returns
        -------
        NDArray, CSRNDArray or RowSparseNDArray
            The copied array

        Examples
        --------
        >>> x = mx.nd.ones((2,3))
        >>> y = x.copy()
        >>> y.asnumpy()
        array([[ 1.,  1.,  1.],
               [ 1.,  1.,  1.]], dtype=float32)
        """
        return self.copyto(self.context) 
Example 18
Project: indras_net   Author: gcallah   File: markov.py    License: GNU General Public License v3.0 5 votes vote down vote up
def to_json(self):
        safe_fields = {}
        safe_fields["matrix"] = [str(self.matrix.dtype), base64.b64encode(self.matrix.A).decode('utf-8'), self.matrix.shape]
        
        return safe_fields 
Example 19
Project: indras_net   Author: gcallah   File: markov.py    License: GNU General Public License v3.0 5 votes vote down vote up
def from_json(self, json_input):
        # get the encoded json dump
        enc = json_input["matrix"]
        
        # build the numpy data type
        dataType = np.dtype(enc[0])
        
        # decode the base64 encoded numpy array data and create a new numpy array with this data & type
        dataArray = np.frombuffer(base64.decodestring(enc[1].encode('utf-8')), dataType)
        
        # if the array had more than one data set it has to be reshaped
        if len(enc) > 2:
             dataArray = dataArray.reshape(enc[2]) # return the reshaped numpy array containing several data sets
             
        self.matrix = np.matrix(dataArray) 
Example 20
Project: indras_net   Author: gcallah   File: vector_space.py    License: GNU General Public License v3.0 5 votes vote down vote up
def to_json(self):
        safe_fields = {}
        safe_fields["vector"] = [str(self.vector.dtype), base64.b64encode(self.vector).decode('utf-8')]
        
        return safe_fields 
Example 21
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: kimotion.py    License: MIT License 5 votes vote down vote up
def run(self):
        while not self.stopped():
            d = self.ws.recv()
            d = np.frombuffer(d, dtype=self.dt)
            self._reading.wait()
            self._data[1 if self._buf else 0] = d
            self._buf = not self._buf
        self.ws.close() 
Example 22
Project: disentangling_conditional_gans   Author: zalandoresearch   File: dataset.py    License: MIT License 5 votes vote down vote up
def get_random_labels_tf(self, minibatch_size): # => labels
        if self.label_size > 0:
            return tf.gather(self._tf_labels_var, tf.random_uniform([minibatch_size], 0, self._np_labels.shape[0], dtype=tf.int32))
        else:
            return tf.zeros([minibatch_size, 0], self.label_dtype)

    # Get random labels as NumPy array. 
Example 23
Project: disentangling_conditional_gans   Author: zalandoresearch   File: dataset.py    License: MIT License 5 votes vote down vote up
def _generate_images(self, minibatch, lod, shape): # to be overridden by subclasses
        return tf.zeros([minibatch] + shape, self.dtype) 
Example 24
Project: dustmaps   Author: gregreen   File: json_serializers.py    License: GNU General Public License v2.0 5 votes vote down vote up
def serialize_ndarray_readable(o):
    """
    Serializes a :obj:`numpy.ndarray` in a human-readable format.

    Args:
        o (:obj:`numpy.ndarray`): :obj:`ndarray` to be serialized.

    Returns:
        A dictionary that can be passed to :obj:`json.dumps`.
    """
    return dict(
        _type='np.ndarray',
        dtype=o.dtype,
        value=hint_tuples(o.tolist())) 
Example 25
Project: neural-fingerprinting   Author: StephanZheng   File: attacks.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate(self, x, **kwargs):
        """
        Return a tensor that constructs adversarial examples for the given
        input. Generate uses tf.py_func in order to operate over tensors.

        :param x: (required) A tensor with the inputs.
        :param y_target: (required) A tensor with the one-hot target labels.
        :param batch_size: The number of inputs to include in a batch and
                           process simultaneously.
        :param binary_search_steps: The number of times we perform binary
                                    search to find the optimal tradeoff-
                                    constant between norm of the purturbation
                                    and cross-entropy loss of classification.
        :param max_iterations: The maximum number of iterations.
        :param initial_const: The initial tradeoff-constant to use to tune the
                              relative importance of size of the perturbation
                              and cross-entropy loss of the classification.
        :param clip_min: (optional float) Minimum input component value
        :param clip_max: (optional float) Maximum input component value
        """
        import tensorflow as tf
        from .attacks_tf import LBFGS_attack
        self.parse_params(**kwargs)

        _, nb_classes = self.get_or_guess_labels(x, kwargs)

        attack = LBFGS_attack(
            self.sess, x, self.model.get_probs(x), self.y_target,
            self.binary_search_steps, self.max_iterations, self.initial_const,
            self.clip_min, self.clip_max, nb_classes, self.batch_size)

        def lbfgs_wrap(x_val, y_val):
            return np.array(attack.attack(x_val, y_val), dtype=self.np_dtype)

        wrap = tf.py_func(lbfgs_wrap, [x, self.y_target], self.tf_dtype)
        wrap.set_shape(x.get_shape())

        return wrap 
Example 26
Project: neural-fingerprinting   Author: StephanZheng   File: attacks.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def attack(self, x, y):
        """
        This method creates a symbolic graph that given an input image,
        first randomly perturbs the image. The
        perturbation is bounded to an epsilon ball. Then multiple steps of
        gradient descent is performed to increase the probability of a target
        label or decrease the probability of the ground-truth label.

        :param x: A tensor with the input image.
        """
        import tensorflow as tf
        from cleverhans.utils_tf import clip_eta

        if self.rand_init:
            eta = tf.random_uniform(
                tf.shape(x), -self.eps, self.eps, dtype=self.tf_dtype)
            eta = clip_eta(eta, self.ord, self.eps)
        else:
            eta = tf.zeros_like(x)

        def cond(i, _):
            return tf.less(i, self.nb_iter)

        def body(i, e):
            new_eta = self.attack_single_step(x, e, y)
            return i + 1, new_eta

        _, eta = tf.while_loop(cond, body, [tf.zeros([]), eta], back_prop=True)

        adv_x = x + eta
        if self.clip_min is not None and self.clip_max is not None:
            adv_x = tf.clip_by_value(adv_x, self.clip_min, self.clip_max)

        return adv_x 
Example 27
Project: neural-fingerprinting   Author: StephanZheng   File: attacks_tf.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def vatm(model,
         x,
         logits,
         eps,
         num_iterations=1,
         xi=1e-6,
         clip_min=None,
         clip_max=None,
         scope=None):
    """
    Tensorflow implementation of the perturbation method used for virtual
    adversarial training: https://arxiv.org/abs/1507.00677
    :param model: the model which returns the network unnormalized logits
    :param x: the input placeholder
    :param logits: the model's unnormalized output tensor (the input to
                   the softmax layer)
    :param eps: the epsilon (input variation parameter)
    :param num_iterations: the number of iterations
    :param xi: the finite difference parameter
    :param clip_min: optional parameter that can be used to set a minimum
                    value for components of the example returned
    :param clip_max: optional parameter that can be used to set a maximum
                    value for components of the example returned
    :param seed: the seed for random generator
    :return: a tensor for the adversarial example
    """
    with tf.name_scope(scope, "virtual_adversarial_perturbation"):
        d = tf.random_normal(tf.shape(x), dtype=tf_dtype)
        for i in range(num_iterations):
            d = xi * utils_tf.l2_batch_normalize(d)
            logits_d = model.get_logits(x + d)
            kl = utils_tf.kl_with_logits(logits, logits_d)
            Hd = tf.gradients(kl, d)[0]
            d = tf.stop_gradient(Hd)
        d = eps * utils_tf.l2_batch_normalize(d)
        adv_x = x + d
        if (clip_min is not None) and (clip_max is not None):
            adv_x = tf.clip_by_value(adv_x, clip_min, clip_max)
        return adv_x 
Example 28
Project: neural-fingerprinting   Author: StephanZheng   File: attacks_tf.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def jacobian(sess, x, grads, target, X, nb_features, nb_classes, feed=None):
    """
    TensorFlow implementation of the foward derivative / Jacobian
    :param x: the input placeholder
    :param grads: the list of TF gradients returned by jacobian_graph()
    :param target: the target misclassification class
    :param X: numpy array with sample input
    :param nb_features: the number of features in the input
    :return: matrix of forward derivatives flattened into vectors
    """
    # Prepare feeding dictionary for all gradient computations
    feed_dict = {x: X}
    if feed is not None:
        feed_dict.update(feed)

    # Initialize a numpy array to hold the Jacobian component values
    jacobian_val = np.zeros((nb_classes, nb_features), dtype=np_dtype)

    # Compute the gradients for all classes
    for class_ind, grad in enumerate(grads):
        run_grad = sess.run(grad, feed_dict)
        jacobian_val[class_ind] = np.reshape(run_grad, (1, nb_features))

    # Sum over all classes different from the target class to prepare for
    # saliency map computation in the next step of the attack
    other_classes = utils.other_classes(nb_classes, target)
    grad_others = np.sum(jacobian_val[other_classes, :], axis=0)

    return jacobian_val[target], grad_others 
Example 29
Project: neural-fingerprinting   Author: StephanZheng   File: attacks_tf.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_delta(self, x, delta):
        x_shape = x.get_shape().as_list()
        delta_x = delta * tf.sign(
            tf.random_uniform(
                [self._num_samples] + x_shape[1:],
                minval=-1.,
                maxval=1.,
                dtype=tf_dtype))
        return delta_x 
Example 30
Project: neural-fingerprinting   Author: StephanZheng   File: attacks.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate(self, x, **kwargs):
        """
        Return a tensor that constructs adversarial examples for the given
        input. Generate uses tf.py_func in order to operate over tensors.

        :param x: (required) A tensor with the inputs.
        :param y_target: (required) A tensor with the one-hot target labels.
        :param batch_size: The number of inputs to include in a batch and
                           process simultaneously.
        :param binary_search_steps: The number of times we perform binary
                                    search to find the optimal tradeoff-
                                    constant between norm of the purturbation
                                    and cross-entropy loss of classification.
        :param max_iterations: The maximum number of iterations.
        :param initial_const: The initial tradeoff-constant to use to tune the
                              relative importance of size of the perturbation
                              and cross-entropy loss of the classification.
        :param clip_min: (optional float) Minimum input component value
        :param clip_max: (optional float) Maximum input component value
        """
        import tensorflow as tf
        from .attacks_tf import LBFGS_attack
        self.parse_params(**kwargs)

        _, nb_classes = self.get_or_guess_labels(x, kwargs)

        attack = LBFGS_attack(
            self.sess, x, self.model.get_probs(x), self.y_target,
            self.binary_search_steps, self.max_iterations, self.initial_const,
            self.clip_min, self.clip_max, nb_classes, self.batch_size)

        def lbfgs_wrap(x_val, y_val):
            return np.array(attack.attack(x_val, y_val), dtype=self.np_dtype)

        wrap = tf.py_func(lbfgs_wrap, [x, self.y_target], self.tf_dtype)
        wrap.set_shape(x.get_shape())

        return wrap