本文整理汇总了Python中numpy.float_方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.float_方法的具体用法?Python numpy.float_怎么用?Python numpy.float_使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.float_方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: fenics_to_numpy
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import float_ [as 别名]
def fenics_to_numpy(fenics_var):
"""Convert FEniCS variable to numpy array"""
if isinstance(fenics_var, (fenics.Constant, fenics_adjoint.Constant)):
return fenics_var.values()
if isinstance(fenics_var, (fenics.Function, fenics_adjoint.Constant)):
np_array = fenics_var.vector().get_local()
n_sub = fenics_var.function_space().num_sub_spaces()
# Reshape if function is multi-component
if n_sub != 0:
np_array = np.reshape(np_array, (len(np_array) // n_sub, n_sub))
return np_array
if isinstance(fenics_var, fenics.GenericVector):
return fenics_var.get_local()
if isinstance(fenics_var, fenics_adjoint.AdjFloat):
return np.array(float(fenics_var), dtype=np.float_)
raise ValueError('Cannot convert ' + str(type(fenics_var)))
示例2: approx
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import float_ [as 别名]
def approx(a, b, fill_value=True, rtol=1e-5, atol=1e-8):
"""
Returns true if all components of a and b are equal to given tolerances.
If fill_value is True, masked values considered equal. Otherwise,
masked values are considered unequal. The relative error rtol should
be positive and << 1.0 The absolute error atol comes into play for
those elements of b that are very small or zero; it says how small a
must be also.
"""
m = mask_or(getmask(a), getmask(b))
d1 = filled(a)
d2 = filled(b)
if d1.dtype.char == "O" or d2.dtype.char == "O":
return np.equal(d1, d2).ravel()
x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
d = np.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y))
return d.ravel()
示例3: test_nan
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import float_ [as 别名]
def test_nan(self):
# nans should be passed through, not converted to infs
ps = [None, 1, -1, 2, -2, 'fro']
p_pos = [None, 1, 2, 'fro']
A = np.ones((2, 2))
A[0,1] = np.nan
for p in ps:
c = linalg.cond(A, p)
assert_(isinstance(c, np.float_))
assert_(np.isnan(c))
A = np.ones((3, 2, 2))
A[1,0,1] = np.nan
for p in ps:
c = linalg.cond(A, p)
assert_(np.isnan(c[1]))
if p in p_pos:
assert_(c[0] > 1e15)
assert_(c[2] > 1e15)
else:
assert_(not np.isnan(c[0]))
assert_(not np.isnan(c[2]))
示例4: test_fromValue
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import float_ [as 别名]
def test_fromValue(self, datetime_series):
nans = Series(np.NaN, index=datetime_series.index)
assert nans.dtype == np.float_
assert len(nans) == len(datetime_series)
strings = Series('foo', index=datetime_series.index)
assert strings.dtype == np.object_
assert len(strings) == len(datetime_series)
d = datetime.now()
dates = Series(d, index=datetime_series.index)
assert dates.dtype == 'M8[ns]'
assert len(dates) == len(datetime_series)
# GH12336
# Test construction of categorical series from value
categorical = Series(0, index=datetime_series.index, dtype="category")
expected = Series(0, index=datetime_series.index).astype("category")
assert categorical.dtype == 'category'
assert len(categorical) == len(datetime_series)
tm.assert_series_equal(categorical, expected)
示例5: testFrexp
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import float_ [as 别名]
def testFrexp(self):
t1 = ones((3, 4, 5), chunk_size=2)
t2 = empty((3, 4, 5), dtype=np.float_, chunk_size=2)
op_type = type(t1.op)
o1, o2 = frexp(t1)
self.assertIs(o1.op, o2.op)
self.assertNotEqual(o1.dtype, o2.dtype)
o1, o2 = frexp(t1, t1)
self.assertIs(o1, t1)
self.assertIsNot(o1.inputs[0], t1)
self.assertIsInstance(o1.inputs[0].op, op_type)
self.assertIsNot(o2.inputs[0], t1)
o1, o2 = frexp(t1, t2, where=t1 > 0)
op_type = type(t2.op)
self.assertIs(o1, t2)
self.assertIsNot(o1.inputs[0], t1)
self.assertIsInstance(o1.inputs[0].op, op_type)
self.assertIsNot(o2.inputs[0], t1)
示例6: testArrayProtocol
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import float_ [as 别名]
def testArrayProtocol(self):
arr = mt.ones((10, 20))
result = np.asarray(arr)
np.testing.assert_array_equal(result, np.ones((10, 20)))
arr2 = mt.ones((10, 20))
result = np.asarray(arr2, mt.bool_)
np.testing.assert_array_equal(result, np.ones((10, 20), dtype=np.bool_))
arr3 = mt.ones((10, 20)).sum()
result = np.asarray(arr3)
np.testing.assert_array_equal(result, np.asarray(200))
arr4 = mt.ones((10, 20)).sum()
result = np.asarray(arr4, dtype=np.float_)
np.testing.assert_array_equal(result, np.asarray(200, dtype=np.float_))
示例7: almost
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import float_ [as 别名]
def almost(a, b, decimal=6, fill_value=True):
"""
Returns True if a and b are equal up to decimal places.
If fill_value is True, masked values considered equal. Otherwise,
masked values are considered unequal.
"""
m = mask_or(getmask(a), getmask(b))
d1 = filled(a)
d2 = filled(b)
if d1.dtype.char == "O" or d2.dtype.char == "O":
return np.equal(d1, d2).ravel()
x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)
return d.ravel()
示例8: test_empty_tuple_index
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import float_ [as 别名]
def test_empty_tuple_index(self):
# Empty tuple index creates a view
a = np.array([1, 2, 3])
assert_equal(a[()], a)
assert_(a[()].base is a)
a = np.array(0)
assert_(isinstance(a[()], np.int_))
# Regression, it needs to fall through integer and fancy indexing
# cases, so need the with statement to ignore the non-integer error.
with warnings.catch_warnings():
warnings.filterwarnings('ignore', '', DeprecationWarning)
a = np.array([1.])
assert_(isinstance(a[0.], np.float_))
a = np.array([np.array(1)], dtype=object)
assert_(isinstance(a[0.], np.ndarray))
示例9: create_data
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import float_ [as 别名]
def create_data(qubit_num, measurement_num, sample_num, file_name=None):
measurements = np.empty([sample_num, measurement_num], dtype=np.float_)
states = np.empty([sample_num, 2**qubit_num], dtype=np.complex_)
projectors = [random_state(qubit_num) for _ in range(measurement_num)]
for i in range(sample_num):
sample = random_state(qubit_num)
states[i] = sample
measurements[i] = np.array([projection(p, sample) for p in projectors])
result = (measurements, states, projectors)
if file_name is not None:
f = gzip.open(io.data_path + file_name + ".plk.gz", 'wb')
cPickle.dump(result, f, protocol=2)
f.close()
return result
示例10: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import float_ [as 别名]
def __init__(self, obj):
if isinstance(obj, SolutionPool):
self._P = obj.P
self._objvals = obj.objvals
self._solutions = obj.solutions
elif isinstance(obj, int):
assert obj >= 1
self._P = int(obj)
self._objvals = np.empty(0)
self._solutions = np.empty(shape = (0, self._P))
elif isinstance(obj, dict):
assert len(obj) == 2
objvals = np.copy(obj['objvals']).flatten().astype(dtype = np.float_)
solutions = np.copy(obj['solutions'])
n = objvals.size
if solutions.ndim == 2:
assert n in solutions.shape
if solutions.shape[1] == n and solutions.shape[0] != n:
solutions = np.transpose(solutions)
elif solutions.ndim == 1:
assert n == 1
solutions = np.reshape(solutions, (1, solutions.size))
else:
raise ValueError('solutions has more than 2 dimensions')
self._P = solutions.shape[1]
self._objvals = objvals
self._solutions = solutions
else:
raise ValueError('cannot initialize SolutionPool using %s object' % type(obj))
示例11: objvals
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import float_ [as 别名]
def objvals(self, objvals):
if hasattr(objvals, "__len__"):
if len(objvals) > 0:
self._objvals = np.copy(list(objvals)).flatten().astype(dtype = np.float_)
elif len(objvals) == 0:
self._objvals = np.empty(0)
else:
self._objvals = float(objvals)
示例12: add
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import float_ [as 别名]
def add(self, new_objvals, new_solutions):
if isinstance(new_objvals, (np.ndarray, list)):
n = len(new_objvals)
self._objvals = np.append(self._objvals, np.array(new_objvals).astype(dtype = np.float_).flatten())
else:
n = 1
self._objvals = np.append(self._objvals, float(new_objvals))
new_solutions = np.reshape(new_solutions, (n, self._P))
self._solutions = np.append(self._solutions, new_solutions, axis = 0)
示例13: setup_objective_functions
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import float_ [as 别名]
def setup_objective_functions(compute_loss, L0_reg_ind, C_0_nnz):
get_objval = lambda rho: compute_loss(rho) + np.sum(C_0_nnz * (rho[L0_reg_ind] != 0.0))
get_L0_norm = lambda rho: np.count_nonzero(rho[L0_reg_ind])
get_L0_penalty = lambda rho: np.sum(C_0_nnz * (rho[L0_reg_ind] != 0.0))
get_alpha = lambda rho: np.array(abs(rho[L0_reg_ind]) > 0.0, dtype = np.float_)
get_L0_penalty_from_alpha = lambda alpha: np.sum(C_0_nnz * alpha)
return (get_objval, get_L0_norm, get_L0_penalty, get_alpha, get_L0_penalty_from_alpha)
示例14: __iter__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import float_ [as 别名]
def __iter__(self):
lengths = np.array(
[(-l[0], -l[1], np.random.random()) for l in self.lengths],
dtype=[('l1', np.int_), ('l2', np.int_), ('rand', np.float_)]
)
indices = np.argsort(lengths, order=('l1', 'l2', 'rand'))
batches = [indices[i:i + self.batch_size]
for i in range(0, len(indices), self.batch_size)]
if self.shuffle:
np.random.shuffle(batches)
return iter([i for batch in batches for i in batch])
示例15: numpy_to_fenics
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import float_ [as 别名]
def numpy_to_fenics(numpy_array, fenics_var_template):
"""Convert numpy array to FEniCS variable"""
if isinstance(fenics_var_template, (fenics.Constant, fenics_adjoint.Constant)):
if numpy_array.shape == (1,):
return type(fenics_var_template)(numpy_array[0])
else:
return type(fenics_var_template)(numpy_array)
if isinstance(fenics_var_template, (fenics.Function, fenics_adjoint.Function)):
np_n_sub = numpy_array.shape[-1]
np_size = np.prod(numpy_array.shape)
function_space = fenics_var_template.function_space()
u = type(fenics_var_template)(function_space)
fenics_size = u.vector().local_size()
fenics_n_sub = function_space.num_sub_spaces()
if (fenics_n_sub != 0 and np_n_sub != fenics_n_sub) or np_size != fenics_size:
err_msg = 'Cannot convert numpy array to Function:' \
' Wrong shape {} vs {}'.format(numpy_array.shape, u.vector().get_local().shape)
raise ValueError(err_msg)
if numpy_array.dtype != np.float_:
err_msg = 'The numpy array must be of type {}, ' \
'but got {}'.format(np.float_, numpy_array.dtype)
raise ValueError(err_msg)
u.vector().set_local(np.reshape(numpy_array, fenics_size))
u.vector().apply('insert')
return u
if isinstance(fenics_var_template, fenics_adjoint.AdjFloat):
return fenics_adjoint.AdjFloat(numpy_array)
err_msg = 'Cannot convert numpy array to {}'.format(fenics_var_template)
raise ValueError(err_msg)