def inner(a, b):
"""
Returns the inner product of a and b for arrays of floating point types.
Like the generic NumPy equivalent the product sum is over the last dimension
of a and b.
Notes
-----
The first argument is not conjugated.
"""
fa = filled(a, 0)
fb = filled(b, 0)
if len(fa.shape) == 0:
fa.shape = (1,)
if len(fb.shape) == 0:
fb.shape = (1,)
return np.inner(fa, fb).view(MaskedArray)
python类inner()的实例源码
core.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
def find_starters(self):
"""
This function finds a pair of instances. One positive and one negative
:param clf: classifier being extracted
:return: (x+, x-) a pair of instances
"""
# perdict = 1 ? inner(x, coef) + intercept_ > 0 : 0
x_n, x_p = (None, None)
x_n_found = False
x_p_found = False
for d in self.X_test:
if x_n_found and x_p_found:
break
if self.query(d) == 1 and (not x_p_found):
x_p = d
x_p_found = True
elif self.query(d) == self.NEG and (not x_n_found):
x_n = d
x_n_found = True
return x_p, x_n
def run(self, peaks, weights=None):
"""Get smeared values.
Args:
peaks:
weights:
Weight factors for "peaks".
Now this can be one-dimeansional and multi-dimensional arrays.
The last dimension must have the same order as the "peaks".
"""
smearing_function = self._smearing_function
xs = self._xs
sigma = self._sigma
tmp = smearing_function(xs[:, None], peaks[None, :], sigma)
if weights is not None:
values = np.inner(tmp, weights)
else:
values = np.sum(tmp, axis=1)
return values
def _create_rotational_weights_for_elements(self, kpoint, transformation_matrix, vectors):
"""
Parameters
----------
kpoint : 1d array
Reciprocal space point in fractional coordinates for PC.
vectors : (..., natoms_p * ndims, nbands) array
Vectors for SC after translational projection.
"""
projected_vectors = self._rotational_projector.project_vectors(
vectors, kpoint, transformation_matrix)
nirreps, natoms_p, nelms, tmp, nbands = projected_vectors.shape
shape = (nirreps, natoms_p, nelms, natoms_p, nelms, nbands)
weights = np.zeros(shape, dtype=complex)
for i in range(nirreps):
for j in range(nbands):
weights[i, ..., j] = np.inner(
np.conj(projected_vectors[i, ..., j]), projected_vectors[i, ..., j])
return weights, projected_vectors
def test_einsum_misc(self):
# This call used to crash because of a bug in
# PyArray_AssignZero
a = np.ones((1, 2))
b = np.ones((2, 2, 1))
assert_equal(np.einsum('ij...,j...->i...', a, b), [[[2], [2]]])
# The iterator had an issue with buffering this reduction
a = np.ones((5, 12, 4, 2, 3), np.int64)
b = np.ones((5, 12, 11), np.int64)
assert_equal(np.einsum('ijklm,ijn,ijn->', a, b, b),
np.einsum('ijklm,ijn->', a, b))
# Issue #2027, was a problem in the contiguous 3-argument
# inner loop implementation
a = np.arange(1, 3)
b = np.arange(1, 5).reshape(2, 2)
c = np.arange(1, 9).reshape(4, 2)
assert_equal(np.einsum('x,yx,zx->xzy', a, b, c),
[[[1, 3], [3, 9], [5, 15], [7, 21]],
[[8, 16], [16, 32], [24, 48], [32, 64]]])
def test_TakeTransposeInnerOuter(self):
# Test of take, transpose, inner, outer products
x = arange(24)
y = np.arange(24)
x[5:6] = masked
x = x.reshape(2, 3, 4)
y = y.reshape(2, 3, 4)
assert_equal(np.transpose(y, (2, 0, 1)), transpose(x, (2, 0, 1)))
assert_equal(np.take(y, (2, 0, 1), 1), take(x, (2, 0, 1), 1))
assert_equal(np.inner(filled(x, 0), filled(y, 0)),
inner(x, y))
assert_equal(np.outer(filled(x, 0), filled(y, 0)),
outer(x, y))
y = array(['abc', 1, 'def', 2, 3], object)
y[2] = masked
t = take(y, [0, 3, 4])
assert_(t[0] == 'abc')
assert_(t[1] == 2)
assert_(t[2] == 3)
def test_testTakeTransposeInnerOuter(self):
# Test of take, transpose, inner, outer products
x = arange(24)
y = np.arange(24)
x[5:6] = masked
x = x.reshape(2, 3, 4)
y = y.reshape(2, 3, 4)
assert_(eq(np.transpose(y, (2, 0, 1)), transpose(x, (2, 0, 1))))
assert_(eq(np.take(y, (2, 0, 1), 1), take(x, (2, 0, 1), 1)))
assert_(eq(np.inner(filled(x, 0), filled(y, 0)),
inner(x, y)))
assert_(eq(np.outer(filled(x, 0), filled(y, 0)),
outer(x, y)))
y = array(['abc', 1, 'def', 2, 3], object)
y[2] = masked
t = take(y, [0, 3, 4])
assert_(t[0] == 'abc')
assert_(t[1] == 2)
assert_(t[2] == 3)
def test_4(self):
"""
Test of take, transpose, inner, outer products.
"""
x = self.arange(24)
y = np.arange(24)
x[5:6] = self.masked
x = x.reshape(2, 3, 4)
y = y.reshape(2, 3, 4)
assert self.allequal(np.transpose(y, (2, 0, 1)), self.transpose(x, (2, 0, 1)))
assert self.allequal(np.take(y, (2, 0, 1), 1), self.take(x, (2, 0, 1), 1))
assert self.allequal(np.inner(self.filled(x, 0), self.filled(y, 0)),
self.inner(x, y))
assert self.allequal(np.outer(self.filled(x, 0), self.filled(y, 0)),
self.outer(x, y))
y = self.array(['abc', 1, 'def', 2, 3], object)
y[2] = self.masked
t = self.take(y, [0, 3, 4])
assert t[0] == 'abc'
assert t[1] == 2
assert t[2] == 3
def inner(a, b):
"""
Returns the inner product of a and b for arrays of floating point types.
Like the generic NumPy equivalent the product sum is over the last dimension
of a and b.
Notes
-----
The first argument is not conjugated.
"""
fa = filled(a, 0)
fb = filled(b, 0)
if len(fa.shape) == 0:
fa.shape = (1,)
if len(fb.shape) == 0:
fb.shape = (1,)
return np.inner(fa, fb).view(MaskedArray)
def _hard_monochrome(self, sample):
"""
Return the monochrome colors corresponding to `sample`, if any.
A boolean is also returned, specifying whether or not the saturation is
sufficient for non monochrome colors.
"""
gray_proj = np.inner(sample, Name._GRAY_UNIT) * Name._GRAY_UNIT
gray_dist = norm(sample - gray_proj)
if gray_dist > 15:
return []
colors = []
luminance = np.sum(sample * Name._GRAY_COEFF)
if luminance > 45 and luminance < 170:
colors.append(self._settings['gray_name'])
if luminance <= 50:
colors.append(self._settings['black_name'])
if luminance >= 170:
colors.append(self._settings['white_name'])
return colors
# Normalized identity (BGR gray) vector.
def test_einsum_misc(self):
# This call used to crash because of a bug in
# PyArray_AssignZero
a = np.ones((1, 2))
b = np.ones((2, 2, 1))
assert_equal(np.einsum('ij...,j...->i...', a, b), [[[2], [2]]])
# The iterator had an issue with buffering this reduction
a = np.ones((5, 12, 4, 2, 3), np.int64)
b = np.ones((5, 12, 11), np.int64)
assert_equal(np.einsum('ijklm,ijn,ijn->', a, b, b),
np.einsum('ijklm,ijn->', a, b))
# Issue #2027, was a problem in the contiguous 3-argument
# inner loop implementation
a = np.arange(1, 3)
b = np.arange(1, 5).reshape(2, 2)
c = np.arange(1, 9).reshape(4, 2)
assert_equal(np.einsum('x,yx,zx->xzy', a, b, c),
[[[1, 3], [3, 9], [5, 15], [7, 21]],
[[8, 16], [16, 32], [24, 48], [32, 64]]])
def test_einsum_all_contig_non_contig_output(self):
# Issue gh-5907, tests that the all contiguous special case
# actually checks the contiguity of the output
x = np.ones((5, 5))
out = np.ones(10)[::2]
correct_base = np.ones(10)
correct_base[::2] = 5
# Always worked (inner iteration is done with 0-stride):
np.einsum('mi,mi,mi->m', x, x, x, out=out)
assert_array_equal(out.base, correct_base)
# Example 1:
out = np.ones(10)[::2]
np.einsum('im,im,im->m', x, x, x, out=out)
assert_array_equal(out.base, correct_base)
# Example 2, buffering causes x to be contiguous but
# special cases do not catch the operation before:
out = np.ones((2, 2, 2))[..., 0]
correct_base = np.ones((2, 2, 2))
correct_base[..., 0] = 2
x = np.ones((2, 2), np.float32)
np.einsum('ij,jk->ik', x, x, out=out)
assert_array_equal(out.base, correct_base)
def test_TakeTransposeInnerOuter(self):
# Test of take, transpose, inner, outer products
x = arange(24)
y = np.arange(24)
x[5:6] = masked
x = x.reshape(2, 3, 4)
y = y.reshape(2, 3, 4)
assert_equal(np.transpose(y, (2, 0, 1)), transpose(x, (2, 0, 1)))
assert_equal(np.take(y, (2, 0, 1), 1), take(x, (2, 0, 1), 1))
assert_equal(np.inner(filled(x, 0), filled(y, 0)),
inner(x, y))
assert_equal(np.outer(filled(x, 0), filled(y, 0)),
outer(x, y))
y = array(['abc', 1, 'def', 2, 3], object)
y[2] = masked
t = take(y, [0, 3, 4])
assert_(t[0] == 'abc')
assert_(t[1] == 2)
assert_(t[2] == 3)
def test_4(self):
"""
Test of take, transpose, inner, outer products.
"""
x = self.arange(24)
y = np.arange(24)
x[5:6] = self.masked
x = x.reshape(2, 3, 4)
y = y.reshape(2, 3, 4)
assert self.allequal(np.transpose(y, (2, 0, 1)), self.transpose(x, (2, 0, 1)))
assert self.allequal(np.take(y, (2, 0, 1), 1), self.take(x, (2, 0, 1), 1))
assert self.allequal(np.inner(self.filled(x, 0), self.filled(y, 0)),
self.inner(x, y))
assert self.allequal(np.outer(self.filled(x, 0), self.filled(y, 0)),
self.outer(x, y))
y = self.array(['abc', 1, 'def', 2, 3], object)
y[2] = self.masked
t = self.take(y, [0, 3, 4])
assert t[0] == 'abc'
assert t[1] == 2
assert t[2] == 3
def inner(a, b):
"""
Returns the inner product of a and b for arrays of floating point types.
Like the generic NumPy equivalent the product sum is over the last dimension
of a and b.
Notes
-----
The first argument is not conjugated.
"""
fa = filled(a, 0)
fb = filled(b, 0)
if len(fa.shape) == 0:
fa.shape = (1,)
if len(fb.shape) == 0:
fb.shape = (1,)
return np.inner(fa, fb).view(MaskedArray)
def _solve_hessian(G, Y, thY, precon, lambda_min):
N, T = Y.shape
# Compute the derivative of the score
psidY = ne.evaluate('(- thY ** 2 + 1.) / 2.') # noqa
# Build the diagonal of the Hessian, a.
Y_squared = Y ** 2
if precon == 2:
a = np.inner(psidY, Y_squared) / float(T)
elif precon == 1:
sigma2 = np.mean(Y_squared, axis=1)
psidY_mean = np.mean(psidY, axis=1)
a = psidY_mean[:, None] * sigma2[None, :]
diagonal_term = np.mean(Y_squared * psidY) + 1.
a[np.diag_indices_from(a)] = diagonal_term
else:
raise ValueError('precon should be 1 or 2')
# Compute the eigenvalues of the Hessian
eigenvalues = 0.5 * (a + a.T - np.sqrt((a - a.T) ** 2 + 4.))
# Regularize
problematic_locs = eigenvalues < lambda_min
np.fill_diagonal(problematic_locs, False)
i_pb, j_pb = np.where(problematic_locs)
a[i_pb, j_pb] += lambda_min - eigenvalues[i_pb, j_pb]
# Invert the transform
return (G * a.T - G.T) / (a * a.T - 1.)
def test_picard():
N, T = 2, 10000
rng = np.random.RandomState(42)
S = rng.laplace(size=(N, T))
A = rng.randn(N, N)
X = np.dot(A, S)
for precon in [1, 2]:
Y, W = picard(X, precon=precon, verbose=True)
# Get the final gradient norm
G = np.inner(np.tanh(Y / 2.), Y) / float(T) - np.eye(N)
assert_allclose(G, np.zeros((N, N)), atol=1e-7)
assert_equal(Y.shape, X.shape)
assert_equal(W.shape, A.shape)
WA = np.dot(W, A)
WA = get_perm(WA)[1] # Permute and scale
assert_allclose(WA, np.eye(N), rtol=1e-2, atol=1e-2)
def test_picardo():
N, T = 2, 10000
rng = np.random.RandomState(42)
S = rng.laplace(size=(N, T))
A = rng.randn(N, N)
X = np.dot(A, S)
Y, W = picardo(X, verbose=2)
# Get the final gradient norm
G = np.inner(np.tanh(Y), Y) / float(T) - np.eye(N)
G = (G - G.T) # take skew-symmetric part
assert_allclose(G, np.zeros((N, N)), atol=1e-7)
assert_equal(Y.shape, X.shape)
assert_equal(W.shape, A.shape)
WA = np.dot(W, A)
WA = get_perm(WA)[1] # Permute and scale
assert_allclose(WA, np.eye(N), rtol=1e-2, atol=1e-2)
def interpolate_learned_policy(old_policy, new_policy, interpolate, old_coeff, new_coeff, weight, method):
if method is "stack_vel_pos":
learned_trajectory = np.zeros(human.shape)
for item in inPlay:
for index in np.arange(item[0],item[0]+tao):
learned_trajectory[index] = human[index]
for index in np.arange(item[0]+tao,item[1]+1):
feature = autoreg_game_context[index,:]
for i in range(tao-1):
feature = np.append(feature, learned_trajectory[index-(i+1)] - learned_trajectory[index-(i+2)])
for i in range(tao):
feature = np.append(feature,learned_trajectory[index-(i+1)])
previous_prediction = learned_trajectory[index-tao:index].copy()
previous_prediction = previous_prediction[::-1]
old_model_predict = (old_policy.predict(feature) + np.inner(old_coeff, previous_prediction) * weight) / (1+weight)
new_model_predict = (new_policy.predict(feature) + np.inner(new_coeff, previous_prediction) * weight) / (1+weight)
#current_prediction = interpolate * new_policy.predict(feature) + (1-interpolate) * old_policy.predict(feature)
learned_trajectory[index] = interpolate * new_model_predict + (1-interpolate) * old_model_predict
return learned_trajectory
def interpolate_test_policy(old_policy, new_policy, interpolate, reference_path, context, old_coeff, new_coeff, weight, method):
Y_predict = np.zeros(reference_path.shape)
if method is "stack_vel_pos":
for i in range(len(reference_path)):
if i<tao:
Y_predict[i] = reference_path[i] #note: have the first tau frames correct
else:
feature = context[i]
for j in range(tao-1):
feature = np.hstack((feature,Y_predict[i-(j+1)]-Y_predict[i-(j+2)]))
for j in range(tao):
feature = np.hstack((feature,Y_predict[i-(j+1)]))
previous_prediction = Y_predict[i-tao:i]
previous_prediction = previous_prediction[::-1]
#current_prediction = interpolate * new_policy.predict(feature) + (1-interpolate) * old_policy.predict(feature)
old_model_predict = (old_policy.predict(feature) + np.inner(old_coeff, previous_prediction) * weight) / (1+weight)
new_model_predict = (new_policy.predict(feature) + np.inner(new_coeff, previous_prediction) * weight) / (1+weight)
#Y_predict[i] = (current_prediction + np.inner(coeff,previous_prediction)*weight)/(1+weight) # replace
Y_predict[i] = interpolate * new_model_predict + (1-interpolate) * old_model_predict
return Y_predict