本文整理汇总了Python中autograd.numpy.ndarray方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.ndarray方法的具体用法?Python numpy.ndarray怎么用?Python numpy.ndarray使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类autograd.numpy
的用法示例。
在下文中一共展示了numpy.ndarray方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_isinstance
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import ndarray [as 别名]
def test_isinstance():
def checker(ex, type_, truthval):
assert isinstance(ex, type_) == truthval
return 1.
examples = [
[list, [[]], [()]],
[np.ndarray, [np.zeros(1)], [[]]],
[(tuple, list), [[], ()], [np.zeros(1)]],
]
for type_, positive_examples, negative_examples in examples:
for ex in positive_examples:
checker(ex, type_, True)
grad(checker)(ex, type_, True)
for ex in negative_examples:
checker(ex, type_, False)
grad(checker)(ex, type_, False)
示例2: optimize
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import ndarray [as 别名]
def optimize(self, angles0, target):
"""Calculate an optimum argument of an objective function."""
def new_objective(angles):
a = angles - angles0
if isinstance(self.smooth_factor, (np.ndarray, list)):
if len(a) == len(self.smooth_factor):
return (self.f(angles, target) +
np.sum(self.smooth_factor * np.power(a, 2)))
else:
raise ValueError('len(smooth_factor) != number of joints')
else:
return (self.f(angles, target) +
self.smooth_factor * np.sum(np.power(a, 2)))
return scipy.optimize.minimize(
new_objective,
angles0,
**self.optimizer_opt).x
示例3: __init__
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import ndarray [as 别名]
def __init__(self, tokens, optimizer=ScipyOptimizer()):
"""Create an actuator from specified link lengths and joint axes."""
components = []
for t in tokens:
if isinstance(t, Number):
components.append(Link([t, 0., 0.]))
elif isinstance(t, list) or isinstance(t, np.ndarray):
components.append(Link(t))
elif isinstance(t, str) and t in {'x', 'y', 'z'}:
components.append(Joint(t))
else:
raise ValueError(
'the arguments need to be '
'link length or joint axis: {}'.format(t)
)
self.fk = FKSolver(components)
self.ik = IKSolver(self.fk, optimizer)
self.angles = [0.] * len(
[c for c in components if isinstance(c, Joint)]
)
self.components = components
示例4: __init__
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import ndarray [as 别名]
def __init__(self, tokens, optimizer=ScipyOptimizer()):
"""Create an actuator from specified link lengths and joint axes."""
components = []
for t in tokens:
if isinstance(t, Number):
components.append(Link([t, 0., 0.]))
elif isinstance(t, list) or isinstance(t, np.ndarray):
components.append(Link(t))
elif isinstance(t, str) and t in {'x', 'y', 'z'}:
components.append(Joint(t))
else:
raise ValueError(
'the arguments need to be '
'link length or joint axis: {}'.format(t)
)
self._fk = FKSolver(components)
self._ik = IKSolver(self._fk, optimizer)
self.angles = [0.] * len(
[c for c in components if isinstance(c, Joint)]
)
示例5: _data
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import ndarray [as 别名]
def _data(self):
return self.view(np.ndarray)
# autograd needs to consider Parameter a class that in can compute gradients for
# in that regard, it behaves like an ordinary ndarray
示例6: add_data
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import ndarray [as 别名]
def add_data(self, S, F=None):
"""
Add a data set to the list of observations.
First, filter the data with the impulse response basis,
then instantiate a set of parents for this data set.
:param S: a TxK matrix of of event counts for each time bin
and each process.
"""
assert isinstance(S, np.ndarray) and S.ndim == 2 and S.shape[1] == self.K \
and np.amin(S) >= 0 and S.dtype == np.int, \
"Data must be a TxK array of event counts"
T = S.shape[0]
if F is None:
# Filter the data into a TxKxB array
Ftens = self.basis.convolve_with_basis(S)
# Flatten this into a T x (KxB) matrix
# [F00, F01, F02, F10, F11, ... F(K-1)0, F(K-1)(B-1)]
F = Ftens.reshape((T, self.K * self.B))
assert np.allclose(F[:,0], Ftens[:,0,0])
if self.B > 1:
assert np.allclose(F[:,1], Ftens[:,0,1])
if self.K > 1:
assert np.allclose(F[:,self.B], Ftens[:,1,0])
# Prepend a column of ones
F = np.hstack((np.ones((T,1)), F))
for k,node in enumerate(self.nodes):
node.add_data(F, S[:,k])
示例7: __new__
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import ndarray [as 别名]
def __new__(cls, input_array, *args, requires_grad=True, **kwargs):
obj = _np.array(input_array, *args, **kwargs)
if isinstance(obj, _np.ndarray):
obj = obj.view(cls)
obj.requires_grad = requires_grad
return obj
示例8: _iscomplex
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import ndarray [as 别名]
def _iscomplex(x):
""" Checks if x is complex-valued or not """
if isinstance(x, npa.ndarray):
if x.dtype == npa.complex128:
return True
if isinstance(x, complex):
return True
return False
示例9: _convert_bounds
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import ndarray [as 别名]
def _convert_bounds(bounds, shapes):
output_bounds = []
for shape, bound in zip(shapes, bounds):
# Check is the bound is already parsable by scipy.optimize
b = bound[0]
if isinstance(b, (list, tuple, np.ndarray)):
output_bounds += bound
else:
output_bounds += [bound, ] * np.prod(shape)
return output_bounds
示例10: match
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import ndarray [as 别名]
def match(self, model_frame, diff_kernels=None, convolution="fft"):
"""Match the frame of `Blend` to the frame of this observation.
The method sets up the mappings in spectral and spatial coordinates,
which includes a spatial selection, computing PSF difference kernels
and filter transformations.
Parameters
---------
model_frame: a `scarlet.Frame` instance
The frame of `Blend` to match
diff_kernels: array
The difference kernel for each band.
If `diff_kernels` is `None` then they are
calculated automatically.
convolution: str
The type of convolution to use.
- `real`: Use a real space convolution and gradient
- `fft`: Use a DFT to do the convolution and gradient
Returns
-------
None
"""
self.model_frame = model_frame
if model_frame.channels is not None and self.frame.channels is not None:
channel_origin = list(model_frame.channels).index(self.frame.channels[0])
self.frame.origin = (channel_origin, *self.frame.origin[1:])
slices = overlapped_slices(self.frame, model_frame)
self.slices_for_images = slices[0] # Slice of images to match the model
self.slices_for_model = slices[1] # Slice of model that overlaps with the observation
# check dtype consistency
if self.frame.dtype != model_frame.dtype:
self.frame.dtype = model_frame.dtype
self.images = self.images.copy().astype(model_frame.dtype)
if type(self.weights) is np.ndarray:
self.weights = self.weights.copy().astype(model_frame.dtype)
# constrcut diff kernels
if diff_kernels is None:
self._diff_kernels = None
if self.frame.psf is not model_frame.psf:
assert self.frame.psf is not None and model_frame.psf is not None
psf = fft.Fourier(self.frame.psf.update_dtype(model_frame.dtype).image)
model_psf = fft.Fourier(
model_frame.psf.update_dtype(model_frame.dtype).image
)
self._diff_kernels = fft.match_psfs(psf, model_psf)
else:
if not isinstance(diff_kernels, fft.Fourier):
diff_kernels = fft.Fourier(diff_kernels)
self._diff_kernels = diff_kernels
# initialize the filter window
assert convolution in ["real", "fft"], "`convolution` must be either 'real' or 'fft'"
self.convolution = convolution
return self
示例11: tensor_wrapper
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import ndarray [as 别名]
def tensor_wrapper(obj):
"""Decorator that wraps callable objects and classes so that they both accept
a ``requires_grad`` keyword argument, as well as returning a PennyLane
:class:`~.tensor`.
Only if the decorated object returns an ``ndarray`` is the
output converted to a :class:`~.tensor`; this avoids superfluous conversion
of scalars and other native-Python types.
Args:
obj: a callable object or class
"""
@functools.wraps(obj)
def _wrapped(*args, **kwargs):
"""Wrapped NumPy function"""
tensor_kwargs = {}
if "requires_grad" in kwargs:
tensor_kwargs["requires_grad"] = kwargs.pop("requires_grad")
else:
tensor_args = list(extract_tensors(args))
if tensor_args:
# Unless the user specifies otherwise, if all tensors in the argument
# list are non-trainable, the output is also non-trainable.
# Equivalently: if any tensor is trainable, the output is also trainable.
# NOTE: Use of Python's ``any`` results in an infinite recursion,
# and I'm not sure why. Using ``np.any`` works fine.
tensor_kwargs["requires_grad"] = _np.any([i.requires_grad for i in tensor_args])
# evaluate the original object
res = obj(*args, **kwargs)
if isinstance(res, _np.ndarray):
# only if the output of the object is a ndarray,
# then convert to a PennyLane tensor
res = tensor(res, **tensor_kwargs)
return res
return _wrapped
示例12: _get_dot_func
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import ndarray [as 别名]
def _get_dot_func(interface, x=None):
"""Helper function for :func:`~.dot` to determine
the correct dot product function depending on the QNodeCollection
interface.
Args:
interface (str): the interface to get the dot product function for
x (Sequence): A non-QNodeCollection sequence. If it isn't the correct
type for the interface, it is automatically converted.
Returns:
tuple[callable, Sequence or torch.Tensor or tf.Variable]: a tuple
containing the required dot product function, as well as the
(potentially converted) sequence.
"""
if interface == "tf":
import tensorflow as tf
if x is not None and not isinstance(x, (tf.Tensor, tf.Variable)):
x = tf.Variable(x, dtype=tf.float64)
return lambda a, b: tf.tensordot(a, b, 1), x
if interface == "torch":
import torch
if x is not None and not isinstance(x, torch.Tensor):
x = torch.tensor(x, dtype=torch.float64)
return torch.matmul, x
if interface in ("autograd", "numpy"):
from autograd import numpy as np
if x is not None and not isinstance(x, np.ndarray):
x = np.array(x)
return np.dot, x
if interface is None:
import numpy as np
return np.dot, x
raise ValueError("Unknown interface {}".format(interface))