本文整理匯總了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]
示例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
示例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
示例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
示例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
示例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)
示例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
示例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.
示例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
示例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
示例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
示例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
示例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
示例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
示例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