本文整理匯總了Python中numpy.ufunc方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.ufunc方法的具體用法?Python numpy.ufunc怎麽用?Python numpy.ufunc使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.ufunc方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_module_functions
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ufunc [as 別名]
def get_module_functions(modules):
"""Finds functions that do not have implemented derivatives.
Args:
modules: A list of Python modules. Functions contained in these modules
will be checked for membership in 'implemented', and if not found,
will be added to an 'unimplemented' set
implemented: A Python object containing implemented derivatives. A function
should be checkable for membership using the `fn in implemented` syntax.
Returns:
module_fns: A set of functions, builtins or ufuncs in `modules`.
"""
module_fns = set()
for module in modules:
for key in dir(module):
attr = getattr(module, key)
if isinstance(
attr, (types.BuiltinFunctionType, types.FunctionType, numpy.ufunc)):
module_fns.add(attr)
return module_fns
示例2: __init__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ufunc [as 別名]
def __init__(self, scalar_op, inplace_pattern=None, name=None,
nfunc_spec=None, openmp=None):
if inplace_pattern is None:
inplace_pattern = {}
self.name = name
self.scalar_op = scalar_op
self.inplace_pattern = inplace_pattern
self.destroy_map = dict((o, [i]) for o, i in inplace_pattern.items())
self.ufunc = None
self.nfunc = None
if nfunc_spec is None:
nfunc_spec = getattr(scalar_op, 'nfunc_spec', None)
self.nfunc_spec = nfunc_spec
if nfunc_spec:
self.nfunc = getattr(numpy, nfunc_spec[0])
# precompute the hash of this node
self._rehash()
super(Elemwise, self).__init__(openmp=openmp)
示例3: set_ufunc
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ufunc [as 別名]
def set_ufunc(self, scalar_op):
# This is probably a speed up of the implementation
if isinstance(scalar_op, theano.scalar.basic.Add):
self.ufunc = numpy.add
elif isinstance(scalar_op, theano.scalar.basic.Mul):
self.ufunc = numpy.multiply
elif isinstance(scalar_op, theano.scalar.basic.Maximum):
self.ufunc = numpy.maximum
elif isinstance(scalar_op, theano.scalar.basic.Minimum):
self.ufunc = numpy.minimum
elif isinstance(scalar_op, theano.scalar.basic.AND):
self.ufunc = numpy.bitwise_and
elif isinstance(scalar_op, theano.scalar.basic.OR):
self.ufunc = numpy.bitwise_or
elif isinstance(scalar_op, theano.scalar.basic.XOR):
self.ufunc = numpy.bitwise_xor
else:
self.ufunc = numpy.frompyfunc(scalar_op.impl, 2, 1)
示例4: _get_ufuncs
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ufunc [as 別名]
def _get_ufuncs():
ufuncs = []
ufunc_names = []
for name in sorted(sc.__dict__):
obj = sc.__dict__[name]
if not isinstance(obj, np.ufunc):
continue
msg = KNOWNFAILURES.get(obj)
if msg is None:
ufuncs.append(obj)
ufunc_names.append(name)
else:
fail = pytest.mark.xfail(run=False, reason=msg)
ufuncs.append(pytest.param(obj, marks=fail))
ufunc_names.append(name)
return ufuncs, ufunc_names
示例5: __ua_convert__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ufunc [as 別名]
def __ua_convert__(value, dispatch_type, coerce):
if dispatch_type is ufunc:
return getattr(np, value.name)
if value is None:
return None
if dispatch_type is ndarray:
if not coerce:
if not isinstance(value, sparse.SparseArray):
return NotImplemented
if isinstance(value, sparse.SparseArray):
return value
return sparse.as_coo(np.asarray(value))
return value
示例6: __ua_convert__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ufunc [as 別名]
def __ua_convert__(value, dispatch_type, coerce):
if dispatch_type is ufunc and hasattr(fn, value.name):
return getattr(fn, value.name)
if value is None:
return None
if dispatch_type is ndarray:
if not coerce and not isinstance(value, xnd.xnd):
return NotImplemented
return convert(value, coerce=coerce)
if dispatch_type is dtype:
return ndt(str(value))
return NotImplemented
示例7: astype
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ufunc [as 別名]
def astype(self, dtype, copy=True):
"""
Copy of the array, cast to a specified type.
See also
--------
scipy.sparse.coo_matrix.astype : SciPy sparse equivalent function
numpy.ndarray.astype : NumPy equivalent ufunc.
:obj:`COO.elemwise`: Apply an arbitrary element-wise function to one or two
arguments.
"""
# this matches numpy's behavior
if self.dtype == dtype and not copy:
return self
return self.__array_ufunc__(
np.ndarray.astype, "__call__", self, dtype=dtype, copy=copy
)
示例8: _transform_batch
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ufunc [as 別名]
def _transform_batch(self, func, return_schema):
from databricks.koalas.series import Series
from databricks import koalas as ks
if isinstance(func, np.ufunc):
f = func
func = lambda *args, **kwargs: f(*args, **kwargs)
if return_schema is None:
# TODO: In this case, it avoids the shortcut for now (but only infers schema)
# because it returns a series from a different DataFrame and it has a different
# anchor. We should fix this to allow the shortcut or only allow to infer
# schema.
limit = ks.get_option("compute.shortcut_limit")
pser = self._kser.head(limit)._to_internal_pandas()
transformed = pser.transform(func)
kser = Series(transformed)
spark_return_type = kser.spark.data_type
else:
spark_return_type = return_schema
pudf = pandas_udf(func, returnType=spark_return_type, functionType=PandasUDFType.SCALAR)
return self._kser._with_new_scol(scol=pudf(self._kser.spark.column)).rename(self._kser.name)
示例9: __array_prepare__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ufunc [as 別名]
def __array_prepare__(self, result, context=None):
"""
Gets called prior to a ufunc
"""
# nice error message for non-ufunc types
if context is not None and not isinstance(self._values, np.ndarray):
obj = context[1][0]
raise TypeError("{obj} with dtype {dtype} cannot perform "
"the numpy op {op}".format(
obj=type(obj).__name__,
dtype=getattr(obj, 'dtype', None),
op=context[0].__name__))
return result
# complex
示例10: test_coverage
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ufunc [as 別名]
def test_coverage(self):
"""Test that we cover all ufunc's"""
all_np_ufuncs = set([ufunc for ufunc in np.core.umath.__dict__.values()
if isinstance(ufunc, np.ufunc)])
all_q_ufuncs = (qh.UNSUPPORTED_UFUNCS |
set(qh.UFUNC_HELPERS.keys()))
# Check that every numpy ufunc is covered.
assert all_np_ufuncs - all_q_ufuncs == set()
# Check that all ufuncs we cover come from numpy or erfa.
# (Since coverage for erfa is incomplete, we do not check
# this the other way).
all_erfa_ufuncs = set([ufunc for ufunc in erfa_ufunc.__dict__.values()
if isinstance(ufunc, np.ufunc)])
assert (all_q_ufuncs - all_np_ufuncs - all_erfa_ufuncs == set())
示例11: __array_wrap__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ufunc [as 別名]
def __array_wrap__(self, result, context=None):
"""
Gets called after a ufunc. Needs additional handling as
PeriodIndex stores internal data as int dtype
Replace this to __numpy_ufunc__ in future version
"""
if isinstance(context, tuple) and len(context) > 0:
func = context[0]
if func is np.add:
pass
elif func is np.subtract:
name = self.name
left = context[1][0]
right = context[1][1]
if (isinstance(left, PeriodIndex) and
isinstance(right, PeriodIndex)):
name = left.name if left.name == right.name else None
return Index(result, name=name)
elif isinstance(left, Period) or isinstance(right, Period):
return Index(result, name=name)
elif isinstance(func, np.ufunc):
if 'M->M' not in func.types:
msg = "ufunc '{0}' not supported for the PeriodIndex"
# This should be TypeError, but TypeError cannot be raised
# from here because numpy catches.
raise ValueError(msg.format(func.__name__))
if is_bool_dtype(result):
return result
# the result is object dtype array of Period
# cannot pass _simple_new as it is
return type(self)(result, freq=self.freq, name=self.name)
示例12: __array_wrap__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ufunc [as 別名]
def __array_wrap__(self, result, context=None):
"""
Gets called after a ufunc.
"""
return self._constructor(result, index=self.index,
copy=False).__finalize__(self)
示例13: _infer_df_func_returns
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ufunc [as 別名]
def _infer_df_func_returns(self, in_dtypes, dtypes, index):
if isinstance(self._func, np.ufunc):
output_type, new_dtypes, index_value, new_elementwise = \
OutputType.dataframe, None, 'inherit', True
else:
output_type, new_dtypes, index_value, new_elementwise = None, None, None, False
try:
empty_df = build_empty_df(in_dtypes, index=pd.RangeIndex(2))
with np.errstate(all='ignore'):
infer_df = empty_df.apply(self._func, axis=self._axis, raw=self._raw,
result_type=self._result_type, args=self.args, **self.kwds)
if index_value is None:
if infer_df.index is empty_df.index:
index_value = 'inherit'
else:
index_value = parse_index(pd.RangeIndex(-1))
if isinstance(infer_df, pd.DataFrame):
output_type = output_type or OutputType.dataframe
new_dtypes = new_dtypes or infer_df.dtypes
else:
output_type = output_type or OutputType.series
new_dtypes = new_dtypes or infer_df.dtype
new_elementwise = False if new_elementwise is None else new_elementwise
except: # noqa: E722 # nosec
pass
self.output_types = [output_type] if not self.output_types else self.output_types
dtypes = new_dtypes if dtypes is None else dtypes
index_value = index_value if index is None else parse_index(index)
self._elementwise = new_elementwise if self._elementwise is None else self._elementwise
return dtypes, index_value
示例14: __getstate__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ufunc [as 別名]
def __getstate__(self):
d = copy(self.__dict__)
d.pop('ufunc')
d.pop('nfunc')
d.pop('__epydoc_asRoutine', None)
d.pop('_hashval')
return d
示例15: __setstate__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ufunc [as 別名]
def __setstate__(self, d):
super(Elemwise, self).__setstate__(d)
self.ufunc = None
self.nfunc = None
if getattr(self, 'nfunc_spec', None):
self.nfunc = getattr(numpy, self.nfunc_spec[0])
elif 0 < self.scalar_op.nin < 32:
self.ufunc = numpy.frompyfunc(self.scalar_op.impl,
self.scalar_op.nin,
self.scalar_op.nout)
self._rehash()