本文整理匯總了Python中numpy.asfarray方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.asfarray方法的具體用法?Python numpy.asfarray怎麽用?Python numpy.asfarray使用的例子?那麽恭喜您, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在模塊numpy的用法示例。
在下文中一共展示了numpy.asfarray方法的24個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於我們的係統推薦出更棒的Python代碼示例。
示例1: __init__
點讚 6
# 需要導入模塊: 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,
示例2: _asfarray
點讚 6
# 需要導入模塊: 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,
示例3: _load_bg_data
點讚 6
# 需要導入模塊: 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,
示例4: LinearB
點讚 6
# 需要導入模塊: 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,
示例5: next_batch
點讚 6
# 需要導入模塊: 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,
示例6: log_norm_low_concentration
點讚 6
# 需要導入模塊: 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,
示例7: load_embeddings
點讚 6
# 需要導入模塊: 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,
示例8: dcg_at_k
點讚 6
# 需要導入模塊: 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,
示例9: _estimate_centroids_via_quadratic
點讚 6
# 需要導入模塊: 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,
示例10: complex_array
點讚 6
# 需要導入模塊: 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,
示例11: train_transform
點讚 5
# 需要導入模塊: 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,
示例12: val_transform
點讚 5
# 需要導入模塊: 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,
示例13: train_transform
點讚 5
# 需要導入模塊: 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,
示例14: val_transform
點讚 5
# 需要導入模塊: 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,
示例15: success
點讚 5
# 需要導入模塊: 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,
示例16: dcg_at_k
點讚 5
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import asfarray [as 別名]
def dcg_at_k(r, k):
"""
Args:
r: Relevance scores (list or numpy) in rank order
(first element is the first item)
k: Number of results to consider
Returns:
Discounted cumulative gain
"""
r = np.asfarray(r)[:k]
if r.size:
return np.sum(r / np.log2(np.arange(2, r.size + 2)))
return 0.
開發者ID:sergiooramas,項目名稱:tartarus,代碼行數:15,
示例17: test_asfarray_none
點讚 5
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import asfarray [as 別名]
def test_asfarray_none(self):
# Test for changeset r5065
assert_array_equal(np.array([np.nan]), np.asfarray([None]))
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:5,
示例18: test_asfarray_none
點讚 5
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import asfarray [as 別名]
def test_asfarray_none(self, level=rlevel):
# Test for changeset r5065
assert_array_equal(np.array([np.nan]), np.asfarray([None]))
開發者ID:ryfeus,項目名稱:lambda-packs,代碼行數:5,
示例19: _compute_gradient
點讚 5
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import asfarray [as 別名]
def _compute_gradient(x,
x_shape,
dx,
y,
y_shape,
dy,
x_init_value=None,
delta=1e-3,
extra_feed_dict=None):
"""Computes the theoretical and numerical jacobian."""
t = dtypes.as_dtype(x.dtype)
allowed_types = [dtypes.float16, dtypes.float32, dtypes.float64,
dtypes.complex64, dtypes.complex128]
assert t.base_dtype in allowed_types, "Don't support type %s for x" % t.name
t2 = dtypes.as_dtype(y.dtype)
assert t2.base_dtype in allowed_types, "Don't support type %s for y" % t2.name
if x_init_value is not None:
i_shape = list(x_init_value.shape)
assert(list(x_shape) == i_shape), "x_shape = %s, init_data shape = %s" % (
x_shape, i_shape)
x_data = x_init_value
else:
if t == dtypes.float16:
dtype = np.float16
elif t == dtypes.float32:
dtype = np.float32
else:
dtype = np.float64
x_data = np.asfarray(np.random.random_sample(x_shape), dtype=dtype)
jacob_t = _compute_theoretical_jacobian(
x, x_shape, x_data, dy, y_shape, dx, extra_feed_dict=extra_feed_dict)
jacob_n = _compute_numeric_jacobian(
x, x_shape, x_data, y, y_shape, delta, extra_feed_dict=extra_feed_dict)
return jacob_t, jacob_n
開發者ID:abhisuri97,項目名稱:auto-alt-text-lambda-api,代碼行數:38,
示例20: __read_from_file
點讚 5
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import asfarray [as 別名]
def __read_from_file(self, filename: str):
"""
This function reads a Knapsack Problem instance from a file.
It expects the following format:
num_of_items (dimension)
capacity of the knapsack
num_of_items-tuples of weight-profit
:param filename: File which describes the instance.
:type filename: str.
"""
if filename is None:
raise FileNotFoundError('Filename can not be None')
with open(filename) as file:
lines = file.readlines()
data = [line.split() for line in lines if len(line.split()) >= 1]
self.number_of_bits = int(data[0][0])
self.capacity = float(data[1][0])
weights_and_profits = np.asfarray(data[2:], dtype=np.float32)
self.weights = weights_and_profits[:, 0]
self.profits = weights_and_profits[:, 1]
開發者ID:jMetal,項目名稱:jMetalPy,代碼行數:29,
示例21: init_population_array
點讚 5
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import asfarray [as 別名]
def init_population_array(self, init):
"""
Initialises the population with a user specified population.
Parameters
----------
init : np.ndarray
Array specifying subset of the initial population. The array should
have shape (M, len(x)), where len(x) is the number of parameters.
The population is clipped to the lower and upper `bounds`.
"""
# make sure you're using a float array
popn = np.asfarray(init)
if (np.size(popn, 0) < 5 or
popn.shape[1] != self.parameter_count or
len(popn.shape) != 2):
raise ValueError("The population supplied needs to have shape"
" (M, len(x)), where M > 4.")
# scale values and clip to bounds, assigning to population
self.population = np.clip(self._unscale_parameters(popn), 0, 1)
self.num_population_members = np.size(self.population, 0)
self.population_shape = (self.num_population_members,
self.parameter_count)
# reset population energies
self.population_energies = (np.ones(self.num_population_members) *
np.inf)
# reset number of function evaluations counter
self._nfev = 0
開發者ID:DSE-MSU,項目名稱:DeepRobust,代碼行數:35,
示例22: test_asfarray_none
點讚 5
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import asfarray [as 別名]
def test_asfarray_none(self, level=rlevel):
"""Test for changeset r5065"""
assert_array_equal(np.array([np.nan]), np.asfarray([None]))
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:5,
示例23: _asfarray
點讚 5
# 需要導入模塊: 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"]:
return x
else:
# We cannot use asfarray directly because it converts sequences of
# complex to sequence of real
ret = numpy.asarray(x)
if not ret.dtype.char in numpy.typecodes["AllFloat"]:
return numpy.asfarray(x)
return ret
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:15,
示例24: wavread
點讚 5
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import asfarray [as 別名]
def wavread(filename):
"""Read in audio data from a wav file. Return d, sr."""
# Read in wav file.
samplerate, wave_data = wav.read(filename)
# Normalize short ints to floats in range [-1..1).
data = np.asfarray(wave_data) / 32768.0
return data, samplerate
開發者ID:dpwe,項目名稱:audfprint,代碼行數:9,
注:本文中的numpy.asfarray方法示例整理自Github/MSDocs等源碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。