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 kwargs: See `parse_params`
518611
def generate(self, x, **kwargs):
    
    assert self.sess is not None, \
        'Cannot use `generate` when no `sess` was provided'
    self.parse_params(**kwargs)

    if self.y_target is None:
      self.y_target, nb_classes = self.get_or_guess_labels(x, kwargs)
      self.targeted_attack = False
    else:
      _, nb_classes = self.get_or_guess_labels(x, kwargs)
      self.targeted_attack = True

    attack = LBFGS_impl(
        self.sess, x, self.model.get_logits(x),
        self.y_target, self.targeted_attack,
        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):
      """
      Wrapper creating TensorFlow interface for use with py_func
      """
      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
49550
def gen_psi(self, x):
        
   
        if isinstance(x, np.ndarray):
            x = x[:,None]
        return np.exp(-self.h * (x - self.c)**2)
770637
def get_predicted_class(self, x, **kwargs):
    
    return tf.argmax(self.get_logits(x, **kwargs), axis=1)
814544
def build(self, x, h, mask=None):
        '''
        
        '''
        xw = tf.split(tf.matmul(x, self.w_matrix) + self.bias, 3, 1)
        hu = tf.split(tf.matmul(h, self.U), 3, 1)
        r = tf.sigmoid(xw[0] + hu[0])
        z = tf.sigmoid(xw[1] + hu[1])
        h1 = tf.tanh(xw[2] + r * hu[2])
        next_h = h1 * (1 - z) + h * z
        if mask is not None:
            next_h = next_h * mask + h * (1 - mask)
        return next_h
910063
def forward_tensor(self, x):
        
        fwd = vec_to_tri(x, self.N)
        return tf.squeeze(fwd, axis=0) if self.squeeze else fwd
594882
def random(self, shape, tf_fn, kwargs):
    
    slice_shape = self.slice_shape(shape)
    op_seed = random.random()
    def my_fn(pnum):
      # seeds are necessary to make sure that slices that should have the
      # same values actually do have the same values.
      seed = hash("%s,%s" % (op_seed, self.slice_begin(shape, pnum)))
      return tf_fn(slice_shape, seed=seed, **kwargs)
    return self.slicewise(my_fn, self.laid_out_pnum())
967163
def xarray_derivative_wrap(func):
    
    @functools.wraps(func)
    def wrapper(f, **kwargs):
        if 'x' in kwargs or 'delta' in kwargs:
            # Use the usual DataArray to pint.Quantity preprocessing wrapper
            return preprocess_xarray(func)(f, **kwargs)
        elif isinstance(f, xr.DataArray):
            # Get axis argument, defaulting to first dimension
            axis = f.metpy.find_axis_name(kwargs.get('axis', 0))

            # Initialize new kwargs with the axis number
            new_kwargs = {'axis': f.get_axis_num(axis)}

            if f[axis].attrs.get('_metpy_axis') == 'T':
                # Time coordinate, need to convert to seconds from datetimes
                new_kwargs['x'] = f[axis].metpy.as_timestamp().metpy.unit_array
            elif CFConventionHandler.check_axis(f[axis], 'lon'):
                # Longitude coordinate, need to get grid deltas
                new_kwargs['delta'], _ = grid_deltas_from_dataarray(f)
            elif CFConventionHandler.check_axis(f[axis], 'lat'):
                # Latitude coordinate, need to get grid deltas
                _, new_kwargs['delta'] = grid_deltas_from_dataarray(f)
            else:
                # General coordinate, use as is
                new_kwargs['x'] = f[axis].metpy.unit_array

            # Calculate and return result as a DataArray
            result = func(f.metpy.unit_array, **new_kwargs)
            return xr.DataArray(result.magnitude,
                                coords=f.coords,
                                dims=f.dims,
                                attrs={'units': str(result.units)})
        else:
            # Error
            raise ValueError('Must specify either "x" or "delta" for value positions when "f" '
                             'is not a DataArray.')
    return wrapper
274472
def forward(self, x):
        
        if not self.training or not self.p:
            return x
        x = x.clone()
        mask = x.new_empty(1, x.size(1), x.size(2), requires_grad=False).bernoulli_(1 - self.p)
        mask = mask.div_(1 - self.p)
        mask = mask.expand_as(x)
        return x * mask
135447
def preprocess_xarray(func):
    
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        args = tuple(a.metpy.unit_array if isinstance(a, xr.DataArray) else a for a in args)
        kwargs = {name: (v.metpy.unit_array if isinstance(v, xr.DataArray) else v)
                  for name, v in kwargs.items()}
        return func(*args, **kwargs)
    return wrapper
211118
def Dropout(x, *args, **kwargs):
    
    if 'is_training' in kwargs:
        kwargs['training'] = kwargs.pop('is_training')
    if len(args) > 0:
        if args[0] != 0.5:
            logger.warn(
                "The first positional argument to tensorpack.Dropout is the probability to keep, rather than to drop. "
                "This is different from the rate argument in tf.layers.Dropout due to historical reasons. "
                "To mimic tf.layers.Dropout, explicitly use keyword argument 'rate' instead")
        rate = 1 - args[0]
    elif 'keep_prob' in kwargs:
        assert 'rate' not in kwargs, "Cannot set both keep_prob and rate!"
        rate = 1 - kwargs.pop('keep_prob')
    elif 'rate' in kwargs:
        rate = kwargs.pop('rate')
    else:
        rate = 0.5

    if kwargs.get('training', None) is None:
        kwargs['training'] = get_current_tower_context().is_training

    if get_tf_version_tuple() <= (1, 12):
        return tf.layers.dropout(x, rate=rate, **kwargs)
    else:
        return tf.nn.dropout(x, rate=rate if kwargs['training'] else 0.)
261178
def transform(self, X):
        

        extracted = []
        for columns, transformer in self.mapping:
            if transformer is not None:
                feature = transformer.transform(self._get_columns(X, columns))
            else:
                feature = self._get_columns(X, columns)

            if hasattr(feature, 'toarray'):
                # sparse arrays should be converted to regular arrays for hstack.
                feature = feature.toarray()

            if len(feature.shape) == 1:
                feature = np.array([feature]).T
            extracted.append(feature)

        # combine the feature outputs into one array.
        # at this point we lose track of which features
        # were created from which input columns, so it's
        # assumed that that doesn't matter to the model.
        return np.hstack(extracted)
1127767
def generate(self, x, **kwargs):
    
    # Parse and save attack-specific parameters
    assert self.parse_params(**kwargs)

    labels, _nb_classes = self.get_or_guess_labels(x, kwargs)

    return fgm(
        x,
        self.model.get_logits(x),
        y=labels,
        eps=self.eps,
        ord=self.ord,
        clip_min=self.clip_min,
        clip_max=self.clip_max,
        targeted=(self.y_target is not None),
        sanity_checks=self.sanity_checks)
812034
def transform(self, X):
        
        assert np.shape(X)[0] == len(self._weights), (
            'BlendingOptimizer: Number of models to blend its predictions and weights does not match: '
            'n_models={}, weights_len={}'.format(np.shape(X)[0], len(self._weights)))
        blended_predictions = np.average(np.power(X, self._power),
                                         weights=self._weights,
                                         axis=0) ** (1.0 / self._power)

        return {'y_pred': blended_predictions}
16129
def encode(x, x_space, hparams, name):
  """"""
  with tf.variable_scope(name):
    (encoder_input, encoder_self_attention_bias,
     ed) = transformer.transformer_prepare_encoder(x, x_space, hparams)
    encoder_input = tf.nn.dropout(encoder_input, 1.0 - hparams.dropout)
    return transformer.transformer_encoder(
        encoder_input, encoder_self_attention_bias, hparams), ed
1033862
def gen_tensor_data():
    
    X, y = toy_interaction(return_X_y=True, n=10000)

    gam = LinearGAM(te(0, 1,lam=0.1)).fit(X, y)

    XX = gam.generate_X_grid(term=0, meshgrid=True)
    Z = gam.partial_dependence(term=0, meshgrid=True)

    fig = plt.figure(figsize=(9,6))
    ax = plt.axes(projection='3d')
    ax.dist = 7.5
    ax.plot_surface(XX[0], XX[1], Z, cmap='viridis')
    ax.set_axis_off()
    fig.tight_layout()
    plt.savefig('imgs/pygam_tensor.png', transparent=True, dpi=300)
662653
def linear(self, x):
    
    with tf.name_scope("presoftmax_linear"):
      batch_size = tf.shape(x)[0]
      length = tf.shape(x)[1]

      x = tf.reshape(x, [-1, self.hidden_size])
      logits = tf.matmul(x, self.shared_weights, transpose_b=True)

      return tf.reshape(logits, [batch_size, length, self.vocab_size])
1163639
def load_batch(self, fn_batch):
        

        # TODO Assumes targets are available, which is how its distinct from
        # utils.load_batch_x(). These functions need to change names to be
        # clearer.

        inverse = list(zip(*fn_batch))
        feat_fn_batch = inverse[0]
        target_fn_batch = inverse[1]

        batch_inputs, batch_inputs_lens = utils.load_batch_x(feat_fn_batch,
                                                             flatten=False)
        batch_targets_list = []
        for targets_path in target_fn_batch:
            with open(targets_path, encoding=ENCODING) as targets_f:
                target_indices = self.corpus.labels_to_indices(targets_f.readline().split())
                batch_targets_list.append(target_indices)
        batch_targets = utils.target_list_to_sparse_tensor(batch_targets_list)

        return batch_inputs, batch_inputs_lens, batch_targets