当前位置: 首页>>代码示例>>Python>>正文


Python numpy.shape方法代码示例

本文整理汇总了Python中numpy.shape方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.shape方法的具体用法?Python numpy.shape怎么用?Python numpy.shape使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在numpy的用法示例。


在下文中一共展示了numpy.shape方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import shape [as 别名]
def __init__(self, transform=None, target_transform=None, filename="adv_set_e_2.p", transp = False):
        """

        :param transform:
        :param target_transform:
        :param filename:
        :param transp: Set shuff= False for PGD based attacks
        :return:
        """
        self.transform = transform
        self.target_transform = target_transform
        self.adv_dict=pickle.load(open(filename,"rb"))
        self.adv_flat=self.adv_dict["adv_input"]
        self.num_adv=np.shape(self.adv_flat)[0]
        self.shuff = transp
        self.sample_num = 0 
开发者ID:StephanZheng,项目名称:neural-fingerprinting,代码行数:18,代码来源:custom_datasets.py

示例2: __init__

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import shape [as 别名]
def __init__(self, transform=None, target_transform=None, filename="adv_set_e_2.p", transp = False):
        """

        :param transform:
        :param target_transform:
        :param filename:
        :param transp: Set shuff= False for PGD based attacks
        :return:
        """
        self.transform = transform
        self.target_transform = target_transform
        self.adv_dict=pickle.load(open(filename,"rb"))
        self.adv_flat=self.adv_dict["adv_input"]
        self.num_adv=np.shape(self.adv_flat)[0]
        self.transp = transp
        self.sample_num = 0 
开发者ID:StephanZheng,项目名称:neural-fingerprinting,代码行数:18,代码来源:custom_datasets.py

示例3: binary_refinement

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import shape [as 别名]
def binary_refinement(sess,Best_X_adv,
                      X_adv, Y, ALPHA, ub, lb, model, dataset='cifar'):
    num_samples = np.shape(X_adv)[0]
    print(dataset)
    if(dataset=="mnist"):
        X_place = tf.placeholder(tf.float32, shape=[1, 1, 28, 28])
    else:
        X_place = tf.placeholder(tf.float32, shape=[1, 3, 32, 32])

    pred = model(X_place)
    for i in range(num_samples):
        logits_op = sess.run(pred,feed_dict={X_place:X_adv[i:i+1,:,:,:]})
        if(not np.argmax(logits_op) == np.argmax(Y[i,:])):
            # Success, increase alpha
            Best_X_adv[i,:,:,:] = X_adv[i,:,:,]
            lb[i] = ALPHA[i,0]
        else:
            ub[i] = ALPHA[i,0]
        ALPHA[i] = 0.5*(lb[i] + ub[i])
    return ALPHA, Best_X_adv 
开发者ID:StephanZheng,项目名称:neural-fingerprinting,代码行数:22,代码来源:adaptive_attacks.py

示例4: parse_dataobj

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import shape [as 别名]
def parse_dataobj(self, dataobj, hdat={}):
        # first, see if we have a specified shape/size
        ish = next((hdat[k] for k in ('image_size', 'image_shape', 'shape') if k in hdat), None)
        if ish is Ellipsis: ish = None
        # make a numpy array of the appropriate dtype
        dtype = self.parse_type(hdat, dataobj=dataobj)
        try:    dataobj = dataobj.dataobj
        except Exception: pass
        if   dataobj is not None: arr = np.asarray(dataobj).astype(dtype)
        elif ish:                 arr = np.zeros(ish,       dtype=dtype)
        else:                     arr = np.zeros([1,1,1,0], dtype=dtype)
        # reshape to the requested shape if need-be
        if ish and ish != arr.shape: arr = np.reshape(arr, ish)
        # then reshape to a valid (4D) shape
        sh = arr.shape
        if   len(sh) == 2: arr = np.reshape(arr, (sh[0], 1, 1, sh[1]))
        elif len(sh) == 1: arr = np.reshape(arr, (sh[0], 1, 1))
        elif len(sh) == 3: arr = np.reshape(arr, sh)
        elif len(sh) != 4: raise ValueError('Cannot convert n-dimensional array to image if n > 4')
        # and return
        return arr 
开发者ID:noahbenson,项目名称:neuropythy,代码行数:23,代码来源:images.py

示例5: image_array_to_spec

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import shape [as 别名]
def image_array_to_spec(arr):
    '''
    image_array_to_spec(arr) yields an image-spec that is appropriate for the given array. The 
      default image spec for an array is a FreeSurfer-like affine transformation with a translation
      that puts the origin at the center of the array. The upper-right 3x3 matrix for this
      transformation is [[-1,0,0], [0,0,1], [0,-1,0]].
    image_array_to_spec((i,j,k)) uses (i,j,k) as the shape of the image array.
    image_array_to_spec(image) uses the array from the given image but not the affine matrix.
    image_array_to_spec(spec) uses the image shape from the given image spec but not the affine
      matrix.
    '''
    sh   = image_shape(arr)[:3]
    (i0,j0,k0) = np.asarray(sh) * 0.5
    ijk0 = (i0, -k0, j0)
    aff  = to_affine(([[-1,0,0],[0,0,1],[0,-1,0]], ijk0), 3)
    return {'image_shape':sh, 'affine':aff} 
开发者ID:noahbenson,项目名称:neuropythy,代码行数:18,代码来源:images.py

示例6: image_reslice

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import shape [as 别名]
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) 
开发者ID:noahbenson,项目名称:neuropythy,代码行数:21,代码来源:images.py

示例7: ctimes

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import shape [as 别名]
def ctimes(*args):
    '''
    ctimes(a, b...) returns the product of all the values as a numpy array object. Like numpy's
      multiply function or a*b syntax, times will thread over the latest dimension possible; thus
      if a.shape is (4,2) and b.shape is 2, times(a,b) is a equivalent to a * b.

    Unlike numpy's multiply function, ctimes works with sparse matrices and will reify them.
    '''
    n = len(args)
    if   n == 0: return np.asarray(0)
    elif n == 1: return np.asarray(args[0])
    elif n >  2: return reduce(plus, args)
    (a,b) = args
    if   sps.issparse(a): return a.multiply(b)
    elif sps.issparse(b): return b.multiply(a)
    else:                 return np.asarray(a) * b 
开发者ID:noahbenson,项目名称:neuropythy,代码行数:18,代码来源:core.py

示例8: zdivide

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import shape [as 别名]
def zdivide(a, b, null=0):
    '''
    zdivide(a, b) returns the quotient a / b as a numpy array object. Unlike numpy's divide function
      or a/b syntax, zdivide will thread over the earliest dimension possible; thus if a.shape is
      (4,2) and b.shape is 4, zdivide(a,b) is a equivalent to [ai*zinv(bi) for (ai,bi) in zip(a,b)].

    The optional argument null (default: 0) may be given to specify that zeros in the arary b should
    instead be replaced with the given value in the result. Note that if this value is not equal to
    0, then any sparse array passed as argument b must be reified.

    The zdivide function never raises an error due to divide-by-zero; if you desire this behavior,
    use the divide function instead.

    Note that zdivide(a,b, null=z) is not quite equivalent to a*zinv(b, null=z) unless z is 0; if z
    is not zero, then the same elements that are zet to z in zinv(b, null=z) are set to z in the
    result of zdivide(a,b, null=z) rather than the equivalent element of a times z.
    '''
    (a,b) = unbroadcast(a,b)
    return czdivide(a,b, null=null) 
开发者ID:noahbenson,项目名称:neuropythy,代码行数:21,代码来源:core.py

示例9: inner

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import shape [as 别名]
def inner(a,b):
    '''
    inner(a,b) yields the dot product of a and b, doing so in a fashion that respects sparse
      matrices when encountered. This does not error check for bad dimensionality.

    If a or b are constants, then the result is just the a*b; if a and b are both vectors or both
    matrices, then the inner product is dot(a,b); if a is a vector and b is a matrix, this is
    equivalent to as if a were a matrix with 1 row; and if a is a matrix and b a vector, this is
    equivalent to as if b were a matrix with 1 column.
    '''
    if   sps.issparse(a): return a.dot(b)
    else: a = np.asarray(a)
    if len(a.shape) == 0: return a*b
    if sps.issparse(b):
        if len(a.shape) == 1: return b.T.dot(a)
        else:                 return b.T.dot(a.T).T
    else: b = np.asarray(b)
    if len(b.shape) == 0: return a*b
    if len(a.shape) == 1 and len(b.shape) == 2: return np.dot(b.T, a)
    else: return np.dot(a,b) 
开发者ID:noahbenson,项目名称:neuropythy,代码行数:22,代码来源:core.py

示例10: convert_string_to_list

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import shape [as 别名]
def convert_string_to_list(string_val):
    """Helper function to convert string to list.
     Used to convert shape attribute string to list format.
    """
    result_list = []

    list_string = string_val.split(',')
    for val in list_string:
        val = str(val.strip())
        val = val.replace("(", "")
        val = val.replace(")", "")
        val = val.replace("L", "")
        val = val.replace("[", "")
        val = val.replace("]", "")
        if val not in ("", "None"):
            result_list.append(int(val))

    return result_list 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:20,代码来源:_op_translations.py

示例11: convert_floor

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import shape [as 别名]
def convert_floor(node, **kwargs):
    """Map MXNet's floor operator attributes to onnx's Floor operator
    and return the created node.
    """
    onnx = import_onnx_modules()
    name = node["name"]
    proc_nodes = kwargs["proc_nodes"]
    inputs = node["inputs"]

    input_node_id = kwargs["index_lookup"][inputs[0][0]]
    input_node = proc_nodes[input_node_id].name

    node = onnx.helper.make_node(
        "Floor",
        [input_node],
        [name],
        name=name
    )
    return [node]

# Changing shape and type. 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:23,代码来源:_op_translations.py

示例12: test_square

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import shape [as 别名]
def test_square():
    input1 = np.random.randint(1, 10, (2, 3)).astype("float32")

    ipsym = mx.sym.Variable("input1")
    square = mx.sym.square(data=ipsym)
    model = mx.mod.Module(symbol=square, data_names=['input1'], label_names=None)
    model.bind(for_training=False, data_shapes=[('input1', np.shape(input1))], label_shapes=None)
    model.init_params()

    args, auxs = model.get_params()
    params = {}
    params.update(args)
    params.update(auxs)

    converted_model = onnx_mxnet.export_model(square, params, [np.shape(input1)], np.float32, "square.onnx")

    sym, arg_params, aux_params = onnx_mxnet.import_model(converted_model)
    result = forward_pass(sym, arg_params, aux_params, ['input1'], input1)

    numpy_op = np.square(input1)

    npt.assert_almost_equal(result, numpy_op) 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:24,代码来源:mxnet_export_test.py

示例13: labels_from_probs

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import shape [as 别名]
def labels_from_probs(probs):
  """
  Helper function: computes argmax along last dimension of array to obtain
  labels (max prob or max logit value)
  :param probs: numpy array where probabilities or logits are on last dimension
  :return: array with same shape as input besides last dimension with shape 1
          now containing the labels
  """
  # Compute last axis index
  last_axis = len(np.shape(probs)) - 1

  # Label is argmax over last dimension
  labels = np.argmax(probs, axis=last_axis)

  # Return as np.int32
  return np.asarray(labels, dtype=np.int32) 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:18,代码来源:aggregation.py

示例14: accuracy

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import shape [as 别名]
def accuracy(logits, labels):
  """
  Return accuracy of the array of logits (or label predictions) wrt the labels
  :param logits: this can either be logits, probabilities, or a single label
  :param labels: the correct labels to match against
  :return: the accuracy as a float
  """
  assert len(logits) == len(labels)

  if len(np.shape(logits)) > 1:
    # Predicted labels are the argmax over axis 1
    predicted_labels = np.argmax(logits, axis=1)
  else:
    # Input was already labels
    assert len(np.shape(logits)) == 1
    predicted_labels = logits

  # Check against correct labels to compute correct guesses
  correct = np.sum(predicted_labels == labels.reshape(len(labels)))

  # Divide by number of labels to obtain accuracy
  accuracy = float(correct) / len(labels)

  # Return float value
  return accuracy 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:27,代码来源:metrics.py

示例15: attack_single_step

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import shape [as 别名]
def attack_single_step(self, x, eta, y):
        """
        Given the original image and the perturbation computed so far, computes
        a new perturbation.

        :param x: A tensor with the original input.
        :param eta: A tensor the same shape as x that holds the perturbation.
        :param y: A tensor with the target labels or ground-truth labels.
        """
        import tensorflow as tf
        from cleverhans.utils_tf import clip_eta
        from cleverhans.loss import attack_softmax_cross_entropy

        adv_x = x + eta
        logits = self.model.get_logits(adv_x)
        loss = attack_softmax_cross_entropy(y, logits)
        if self.targeted:
            loss = -loss
        grad, = tf.gradients(loss, adv_x)
        scaled_signed_grad = self.eps_iter * tf.sign(grad)
        adv_x = adv_x + scaled_signed_grad
        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)
        eta = adv_x - x
        eta = clip_eta(eta, self.ord, self.eps)
        return eta 
开发者ID:StephanZheng,项目名称:neural-fingerprinting,代码行数:28,代码来源:attacks.py


注:本文中的numpy.shape方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。