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


Python numpy.asfarray方法代码示例

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


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

示例1: __init__

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import asfarray [as 别名]
def __init__(self, x, y):
        if len(x) != len(y):
            raise IndexError('x and y must be equally sized.')
        self.x = np.asfarray(x)
        self.y = np.asfarray(y)

        # Closes the polygon if were open
        x1, y1 = x[0], y[0]
        xn, yn = x[-1], y[-1]
        if x1 != xn or y1 != yn:
            self.x = np.concatenate((self.x, [x1]))
            self.y = np.concatenate((self.y, [y1]))

        # Anti-clockwise coordinates
        if _det(self.x, self.y) < 0:
            self.x = self.x[::-1]
            self.y = self.y[::-1] 
开发者ID:lofar-astron,项目名称:prefactor,代码行数:19,代码来源:make_clean_mask.py

示例2: _asfarray

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import asfarray [as 别名]
def _asfarray(x):
    """Like numpy asfarray, except that it does not modify x dtype if x is
    already an array with a float dtype, and do not cast complex types to
    real."""
    if hasattr(x, "dtype") and x.dtype.char in numpy.typecodes["AllFloat"]:
        # 'dtype' attribute does not ensure that the
        # object is an ndarray (e.g. Series class
        # from the pandas library)
        if x.dtype == numpy.half:
            # no half-precision routines, so convert to single precision
            return numpy.asarray(x, dtype=numpy.float32)
        return numpy.asarray(x, dtype=x.dtype)
    else:
        # We cannot use asfarray directly because it converts sequences of
        # complex to sequence of real
        ret = numpy.asarray(x)
        if ret.dtype == numpy.half:
            return numpy.asarray(ret, dtype=numpy.float32)
        elif ret.dtype.char not in numpy.typecodes["AllFloat"]:
            return numpy.asfarray(x)
        return ret 
开发者ID:ryfeus,项目名称:lambda-packs,代码行数:23,代码来源:basic.py

示例3: _load_bg_data

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import asfarray [as 别名]
def _load_bg_data(d, bg_calc_kwargs, h5file):
    """Load background data from a HDF5 file."""
    group_name = bg_to_signature(d, **bg_calc_kwargs)
    if group_name not in h5file.root.background:
        msg = 'Group "%s" not found in the HDF5 file.' % group_name
        raise ValueError(msg)
    bg_auto_th_us0 = None
    bg_group = h5file.get_node('/background/', group_name)

    pprint('\n - Loading bakground data: ')
    bg = {}
    for node in bg_group._f_iter_nodes():
        if node._v_name.startswith('BG_'):
            ph_sel = Ph_sel.from_str(node._v_name[len('BG_'):])
            bg[ph_sel] = [np.asfarray(b) for b in node.read()]

    Lim = bg_group.Lim.read()
    Ph_p = bg_group.Ph_p.read()
    if 'bg_auto_th_us0' in bg_group:
        bg_auto_th_us0 = bg_group.bg_auto_th_us0.read()
    return bg, Lim, Ph_p, bg_auto_th_us0 
开发者ID:tritemio,项目名称:FRETBursts,代码行数:23,代码来源:bg_cache.py

示例4: LinearB

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import asfarray [as 别名]
def LinearB(Xi, Yi):
    X = np.asfarray(Xi)
    Y = np.asfarray(Yi)

    # we want a function y = m * x + b
    def fp(v, x):
        return x * v[0] + v[1]

    # the error of the function e = x - y
    def e(v, x, y):
        return (fp(v, x) - y)

    # the initial value of m, we choose 1, because we thought YODA would
    # have chosen 1
    v0 = np.array([1.0, 1.0])

    vr, _success = leastsq(e, v0, args=(X, Y))

    # compute the R**2 (sqrt of the mean of the squares of the errors)
    err = np.sqrt(sum(np.square(e(vr, X, Y))) / (len(X) * len(X)))

#    print vr, success, err
    return vr, err 
开发者ID:EMVA1288,项目名称:emva1288,代码行数:25,代码来源:routines.py

示例5: next_batch

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import asfarray [as 别名]
def next_batch(self, batch_size=10):

        datas = np.empty((0, self._height, self._width, self._dimension), int)
        labels = np.empty((0, self._class_len), int)


        for idx in range(batch_size):
            random.randint(0, len(self._datas)-1)
            tmp_img = scipy.misc.imread(self._datas[idx])
            tmp_img = scipy.misc.imresize(tmp_img, (self._height, self._width))
            tmp_img = tmp_img.reshape(1, self._height, self._width, self._dimension)

            datas = np.append(datas, tmp_img, axis=0)
            labels = np.append(labels, np.eye(self._class_len)[int(np.asfarray(self._labels[idx]))].reshape(1, self._class_len), axis=0)


        return datas, labels 
开发者ID:YeongHyeon,项目名称:CNN_Own_Dataset,代码行数:19,代码来源:constructor.py

示例6: log_norm_low_concentration

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import asfarray [as 别名]
def log_norm_low_concentration(scale, dimension):
        """ Calculates logarithm of pdf function.
        Good at very low concentrations but starts to drop of at 20.
        """
        scale = np.asfarray(scale)
        shape = scale.shape
        scale = scale.ravel()

        # Mardia1999Watson Equation 4, Taylor series
        b_range = range(dimension, dimension + 20 - 1 + 1)
        b_range = np.asarray(b_range)[None, :]

        return (
            np.log(2)
            + dimension * np.log(np.pi)
            - np.log(math.factorial(dimension - 1))
            + np.log(1 + np.sum(np.cumprod(scale[:, None] / b_range, -1), -1))
        ).reshape(shape) 
开发者ID:fgnt,项目名称:pb_bss,代码行数:20,代码来源:complex_watson.py

示例7: load_embeddings

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import asfarray [as 别名]
def load_embeddings(filename, a2i, emb_size=DEFAULT_EMBEDDING_DIM):
    """
    loads embeddings for synsets ("atoms") from existing file,
    or initializes them to uniform random
    """
    atom_to_embed = {}
    if filename is not None:
        if filename.endswith('npy'):
            return np.load(filename)
        with codecs.open(filename, "r", "utf-8") as f:
            for line in f:
                split = line.split()
                if len(split) > 2:
                    atom = split[0]
                    vec = split[1:]
                    atom_to_embed[atom] = np.asfarray(vec)
        embedding_dim = len(atom_to_embed[list(atom_to_embed.keys())[0]])
    else:
        embedding_dim = emb_size
    out = np.random.uniform(-0.8, 0.8, (len(a2i), embedding_dim))
    if filename is not None:
        for atom, embed in list(atom_to_embed.items()):
            if atom in a2i:
                out[a2i[atom]] = np.array(embed)
    return out 
开发者ID:yuvalpinter,项目名称:m3gm,代码行数:27,代码来源:io_utils.py

示例8: dcg_at_k

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import asfarray [as 别名]
def dcg_at_k(r, k, method=1):
    """Score is discounted cumulative gain (dcg)
    Relevance is positive real values.  Can use binary
    as the previous methods.
    Returns:
        Discounted cumulative gain
    """
    r = np.asfarray(r)[:k]
    if r.size:
        if method == 0:
            return r[0] + np.sum(r[1:] / np.log2(np.arange(2, r.size + 1)))
        elif method == 1:
            return np.sum(r / np.log2(np.arange(2, r.size + 2)))
        else:
            raise ValueError('method must be 0 or 1.')
    return 0. 
开发者ID:xiangwang1223,项目名称:knowledge_graph_attention_network,代码行数:18,代码来源:metrics.py

示例9: _estimate_centroids_via_quadratic

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import asfarray [as 别名]
def _estimate_centroids_via_quadratic(self, aperture_mask):
        """Estimate centroids by fitting a 2D quadratic to the brightest pixels;
        this is a helper method for `estimate_centroids()`."""
        aperture_mask = self._parse_aperture_mask(aperture_mask)
        col_centr, row_centr = [], []
        for idx in range(len(self.time)):
            col, row = centroid_quadratic(self.flux[idx], mask=aperture_mask)
            col_centr.append(col)
            row_centr.append(row)
        # Finally, we add .5 to the result bellow because the convention is that
        # pixels are centered at .5, 1.5, 2.5, ...
        col_centr = np.asfarray(col_centr) + self.column + .5
        row_centr = np.asfarray(row_centr) + self.row + .5
        col_centr = Quantity(col_centr, unit='pixel')
        row_centr = Quantity(row_centr, unit='pixel')
        return col_centr, row_centr 
开发者ID:KeplerGO,项目名称:lightkurve,代码行数:18,代码来源:targetpixelfile.py

示例10: complex_array

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import asfarray [as 别名]
def complex_array(real, imag):
    """
    Combine two real ndarrays into a complex array.

    Parameters
    ----------
    real, imag : array_like
        Real and imaginary parts of a complex array.
    
    Returns
    -------
    complex : `~numpy.ndarray`
        Complex array.
    """
    real, imag = np.asfarray(real), np.asfarray(imag)
    comp = real.astype(np.complex)
    comp += 1j * imag
    return comp 
开发者ID:LaurentRDC,项目名称:scikit-ued,代码行数:20,代码来源:array_utils.py

示例11: train_transform

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import asfarray [as 别名]
def train_transform(self, rgb, depth):
        t = [Resize(240.0 / iheight)] # this is for computational efficiency, since rotation can be slow
        if self.rotate:
            angle = np.random.uniform(-5.0, 5.0) # random rotation degrees
            t.append(Rotate(angle))
        if self.scale:
            s = np.random.uniform(1.0, 1.5) # random scaling
            depth = depth / s
            t.append(Resize(s))
        if self.crop:
            slide = np.random.uniform(0.0, 1.0)
            t.append(RandomCrop(self.input_size, slide))
        else: # center crop
            t.append(CenterCrop(self.input_size))
        if self.flip:
            do_flip = np.random.uniform(0.0, 1.0) < 0.5 # random horizontal flip
            t.append(HorizontalFlip(do_flip))
        # perform 1st step of data augmentation
        transform = Compose(t)
        rgb_np = transform(rgb)
        if self.jitter:
            color_jitter = ColorJitter(0.4, 0.4, 0.4)
            rgb_np = color_jitter(rgb_np) # random color jittering
        rgb_np = np.asfarray(rgb_np, dtype='float') / 255
        depth_np = transform(depth)
        return rgb_np, depth_np 
开发者ID:miraiaroha,项目名称:ACAN,代码行数:28,代码来源:nyu_dataloader.py

示例12: val_transform

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import asfarray [as 别名]
def val_transform(self, rgb, depth):
        transform = Compose([Resize(240.0 / iheight),
                             CenterCrop(self.input_size),
                            ])
        rgb_np = transform(rgb)
        rgb_np = np.asfarray(rgb_np, dtype='float') / 255
        depth_np = transform(depth)
        return rgb_np, depth_np 
开发者ID:miraiaroha,项目名称:ACAN,代码行数:10,代码来源:nyu_dataloader.py

示例13: train_transform

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import asfarray [as 别名]
def train_transform(self, rgb, depth):
        t = [Crop(130, 10, 240, 1200), 
             Resize(180 / 240)] # this is for computational efficiency, since rotation can be slow
        if self.rotate:
            angle = np.random.uniform(-5.0, 5.0) # random rotation degrees
            t.append(Rotate(angle))
        if self.scale:
            s = np.random.uniform(1.0, 1.5) # random scaling
            depth = depth / s
            t.append(Resize(s))
        if self.crop: # random crop
            slide = np.random.uniform(0.0, 1.0)
            t.append(RandomCrop(self.input_size, slide))
        else: # center crop
            t.append(CenterCrop(self.input_size))
        if self.flip:
            do_flip = np.random.uniform(0.0, 1.0) < 0.5 # random horizontal flip
            t.append(HorizontalFlip(do_flip))
        # perform 1st step of data augmentation
        transform = Compose(t)
        rgb_np = transform(rgb)
        if self.jitter:
            color_jitter = ColorJitter(0.4, 0.4, 0.4)
            rgb_np = color_jitter(rgb_np) # random color jittering
        rgb_np = np.asfarray(rgb_np, dtype='float') / 255
        # Scipy affine_transform produced RuntimeError when the depth map was
        # given as a 'numpy.ndarray'
        depth_np = np.asfarray(depth, dtype='float32')
        depth_np = transform(depth_np)
        return rgb_np, depth_np 
开发者ID:miraiaroha,项目名称:ACAN,代码行数:32,代码来源:kitti_dataloader.py

示例14: val_transform

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import asfarray [as 别名]
def val_transform(self, rgb, depth):
        transform = Compose([Crop(130, 10, 240, 1200),
                             Resize(180 / 240),
                             CenterCrop(self.input_size),
                            ])
        rgb_np = transform(rgb)
        rgb_np = np.asfarray(rgb_np, dtype='float') / 255
        depth_np = np.asfarray(depth, dtype='float32')
        depth_np = transform(depth_np)
        return rgb_np, depth_np 
开发者ID:miraiaroha,项目名称:ACAN,代码行数:12,代码来源:kitti_dataloader.py

示例15: success

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import asfarray [as 别名]
def success(self, x, tol=1.e-5):
        """
        Tests if a candidate solution at the global minimum.
        The default test is

        Parameters
        ----------
        x : sequence
            The candidate vector for testing if the global minimum has been
            reached. Must have ``len(x) == self.N``
        tol : float
            The evaluated function and known global minimum must differ by less
            than this amount to be at a global minimum.

        Returns
        -------
        bool : is the candidate vector at the global minimum?
        """
        val = self.fun(asarray(x))
        if abs(val - self.fglob) < tol:
            return True

        # the solution should still be in bounds, otherwise immediate fail.
        if np.any(x > np.asfarray(self.bounds)[:, 1]):
            return False
        if np.any(x < np.asfarray(self.bounds)[:, 0]):
            return False

        # you found a lower global minimum.  This shouldn't happen.
        if val < self.fglob:
            raise ValueError("Found a lower global minimum",
                             x,
                             val,
                             self.fglob)

        return False 
开发者ID:msu-coinlab,项目名称:pymoo,代码行数:38,代码来源:go_benchmark.py


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