本文整理汇总了Python中numpy.core.numeric.dot函数的典型用法代码示例。如果您正苦于以下问题:Python dot函数的具体用法?Python dot怎么用?Python dot使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了dot函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __mul__
def __mul__(self, other):
if isinstance(other, (N.ndarray, list, tuple)) :
# This promotes 1-D vectors to row vectors
return N.dot(self, asmatrix(other))
if isscalar(other) or not hasattr(other, '__rmul__') :
return N.dot(self, other)
return NotImplemented
示例2: __rmul__
def __rmul__(self, other):
# ! NumPy's matrix __rmul__ uses an apparently a restrictive
# dot() function that cannot handle the multiplication of a
# scalar and of a matrix containing objects (when the
# arguments are given in this order). We go around this
# limitation:
if numeric.isscalar(other):
return numeric.dot(self, other)
else:
return numeric.dot(other, self) # The order is important
示例3: __mul__
def __mul__(self, other):
if self.shape == (1,1):
# extract scalars from singleton matrices (self)
return N.dot(self.flat[0], other)
if isinstance(other, N.ndarray) and other.shape == (1,1):
# extract scalars from singleton matrices (other)
return N.dot(self, other.flat[0])
if isinstance(other, (N.ndarray, list, tuple)) :
# This promotes 1-D vectors to row vectors
return N.dot(self, asmatrix(other))
if isscalar(other) or not hasattr(other, '__rmul__') :
return N.dot(self, other)
return NotImplemented
示例4: generate_nmf_test
def generate_nmf_test(numFactors, density):
allUsers = User.objects.all()
allBusinsses = Business.objects.all()
random.seed(666)
newP = []
for u in range(0, allUsers.count()):
if u not in newP:
newP.append([])
for k in range(0, numFactors):
rif = random.uniform(0, 1)
newP[u].append(rif)
newQ = []
for k in range(0, numFactors):
newQ.append([])
for j in range(0, allBusinsses.count()):
rif = random.uniform(0, 1)
newQ[k].append(rif)
initR = dot(newP, newQ)
i = 0
for u in allUsers:
j = 0
for b in allBusinsses:
chance = random.uniform(0, 1)
if(chance < density):
rat = Rating(business=b, username=u, rating=float(initR[i][j]))
rat.save()
j = j + 1
i = i + 1
示例5: _removeNonTracklikeClusterCenters
def _removeNonTracklikeClusterCenters(self):
'''NOTE : Much of this code is copied from LPCMImpl.followXSingleDirection (factor out?)
'''
labels = self._meanShift.labels_
labels_unique = unique(labels)
cluster_centers = self._meanShift.cluster_centers_
rsp = lpcRandomStartPoints()
cluster_representatives = []
for k in range(len(labels_unique)):
cluster_members = labels == k
cluster_center = cluster_centers[k]
cluster = self._Xi[cluster_members,:]
mean_sub = cluster - cluster_center
cov_x = dot(transpose(mean_sub), mean_sub)
eigen_cov = eigh(cov_x)
sorted_eigen_cov = zip(eigen_cov[0],map(ravel,vsplit(eigen_cov[1].transpose(),len(eigen_cov[1]))))
sorted_eigen_cov.sort(key = lambda elt: elt[0], reverse = True)
rho = sorted_eigen_cov[1][0] / sorted_eigen_cov[0][0] #Ratio of two largest eigenvalues
if rho < self._lpcParameters['rho_threshold']:
cluster_representatives.append(cluster_center)
else: #append a random element of the cluster
random_cluster_element = rsp(cluster, 1)[0]
cluster_representatives.append(random_cluster_element)
return array(cluster_representatives)
示例6: cov
def cov(m, y=None, rowvar=1, bias=0):
"""Estimate the covariance matrix.
If m is a vector, return the variance. For matrices return the
covariance matrix.
If y is given it is treated as an additional (set of)
variable(s).
Normalization is by (N-1) where N is the number of observations
(unbiased estimate). If bias is 1 then normalization is by N.
If rowvar is non-zero (default), then each row is a variable with
observations in the columns, otherwise each column
is a variable and the observations are in the rows.
"""
X = array(m, ndmin=2, dtype=float)
if X.shape[0] == 1:
rowvar = 1
if rowvar:
axis = 0
tup = (slice(None),newaxis)
else:
axis = 1
tup = (newaxis, slice(None))
if y is not None:
y = array(y, copy=False, ndmin=2, dtype=float)
X = concatenate((X,y),axis)
X -= X.mean(axis=1-axis)[tup]
if rowvar:
N = X.shape[1]
else:
N = X.shape[0]
if bias:
fact = N*1.0
else:
fact = N-1.0
if not rowvar:
return (dot(X.T, X.conj()) / fact).squeeze()
else:
return (dot(X, X.T.conj()) / fact).squeeze()
示例7: fromLoop
def fromLoop(cls, loop):
"""Returns a Model representing the loop"""
#get necessary vectors
offset_v = [loop.r_anchor[0].__dict__[c] - loop.l_anchor[0].__dict__[c] for c in 'xyz']
sse0_v = Model.__get_sse_vector(loop.l_anchor, loop.atoms[0])
sse1_v = Model.__get_sse_vector(loop.r_anchor, loop.atoms[-1])
sFrame = TransformFrame.createFromVectors(loop.l_anchor[0], transform.Vec.from_array(offset_v), transform.Vec.from_array(sse0_v))
#Theta and phi are the angles between the SSE and anchor-anchor vector
theta = arccos(dot(sse0_v, negative(offset_v)) / (norm(sse0_v) * norm(offset_v)))
phi = arccos(dot(sse1_v, offset_v) / (norm(sse1_v) * norm(offset_v)))
#Length of the vectorn
anchor_dist = norm(offset_v)
return Model([loop], [Vec.from_array(sFrame.transformInto(atom)) for atom in loop.atoms], theta, phi, anchor_dist, [loop.l_type, loop.r_type], Model.__gen_seq([loop.seq]) , 1)
示例8: _distancePointToLineSegment
def _distancePointToLineSegment(self, a, b, p):
'''
Returns tuple of minimum distance to the directed line segment AB from p, and the distance along AB of the point of intersection
'''
ab_mag2 = dot((b-a),(b-a))
pa_mag2 = dot((a-p),(a-p))
pb_mag2 = dot((b-p),(b-p))
if pa_mag2 + ab_mag2 <= pb_mag2:
return (sqrt(pa_mag2),0)
elif pb_mag2 + ab_mag2 <= pa_mag2:
return (sqrt(pb_mag2), sqrt(ab_mag2))
else:
c = cross((b-a),(p-a))
if ab_mag2 == 0:
raise ValueError, 'Division by zero magnitude line segment AB'
dist_to_line2 = dot(c,c)/ab_mag2
dist_to_line = sqrt(dist_to_line2)
dist_along_segment = sqrt(pa_mag2 - dist_to_line2)
return (dist_to_line, dist_along_segment)
示例9: create_olfaction_Ttheta
def create_olfaction_Ttheta(positions, fder):
'''
positions: 2 x n vector
f_der: n x n
'''
require_shape((2, gt(0)), positions)
n = positions.shape[1]
require_shape((n, n), fder)
results = ndarray(shape=(n, n))
for i in range(n):
J = array([ [0, -1], [1, 0]])
Js = dot(J, positions[:, i])
results[i, :] = dot(positions.transpose(), Js)
results = results * fder # it IS element by element
return results
示例10: __gradientDecent
def __gradientDecent(self,datamat,para=zeros((1,2)),learningRate=1,iterNum=500):
# optimization code goes here
__size= datamat[:,1].size;
__parameterVector= para;
print("Gradient Descent is finding optimal parameters");
for i in range (0,iterNum):
__t0= __parameterVector[0];
__t1= __parameterVector[1];
__t0= __t0 - (learningRate/__size)*(dot(datamat[i,0:2],__parameterVector)- datamat[i,2]);
__t1= __t1 - (learningRate/__size)* (dot(datamat[i,0:2],__parameterVector)- datamat[i,2])*datamat[i,1];
__parameterVector[0]=__t0;
__parameterVector[1]=__t1;
minPara= (__t0,__t1);
print("Gradient Descent is complete");
return minPara;
示例11: __computeCost
def __computeCost(self,mat,para=zeros((1,2))):
# if para is not overridden with custom initial values, use zeros
# cost computation code goes here
__cost=0.0;
__size= mat[:,1].size;
for i in mat:
__cost=__cost + (dot(mat[i,0:2],para)- mat[i,2])**2;
__cost= __cost/(2*__size);
return __cost;
示例12: transform
def transform(self, positions, R_i=None, t_i=None, s_i=None, flip=False):
"""
Return subclusters with (randomly) rotated translated and scaled
positions. If R_i, s_i or t_i is given then that part of transformation
is not random.
"""
for sub in positions:
t = t_i or rand(2)*10
s = s_i or rand()*2
if R_i is None:
th = 2*pi*rand()
# ccw
R = array([[cos(th), -sin(th)], [sin(th), cos(th)]])
else:
R = R_i
if flip:
#TODO: make R with flip
pass
for node, pos in sub.items():
sub[node] = concatenate((dot(dot(s, R), pos[:2])+t, [nan]))
示例13: matrix_power
def matrix_power(M, n):
"""
Raise a square matrix to the (integer) power `n`.
For positive integers `n`, the power is computed by repeated matrix
squarings and matrix multiplications. If ``n == 0``, the identity matrix
of the same shape as M is returned. If ``n < 0``, the inverse
is computed and then raised to the ``abs(n)``.
Parameters
----------
M : ndarray or matrix object
Matrix to be "powered." Must be square, i.e. ``M.shape == (m, m)``,
with `m` a positive integer.
n : int
The exponent can be any integer or long integer, positive,
negative, or zero.
Returns
-------
M**n : ndarray or matrix object
The return value is the same shape and type as `M`;
if the exponent is positive or zero then the type of the
elements is the same as those of `M`. If the exponent is
negative the elements are floating-point.
Raises
------
LinAlgError
If the matrix is not numerically invertible.
See Also
--------
matrix
Provides an equivalent function as the exponentiation operator
(``**``, not ``^``).
Examples
--------
>>> from numpy import linalg as LA
>>> i = np.array([[0, 1], [-1, 0]]) # matrix equiv. of the imaginary unit
>>> LA.matrix_power(i, 3) # should = -i
array([[ 0, -1],
[ 1, 0]])
>>> LA.matrix_power(np.matrix(i), 3) # matrix arg returns matrix
matrix([[ 0, -1],
[ 1, 0]])
>>> LA.matrix_power(i, 0)
array([[1, 0],
[0, 1]])
>>> LA.matrix_power(i, -3) # should = 1/(-i) = i, but w/ f.p. elements
array([[ 0., 1.],
[-1., 0.]])
Somewhat more sophisticated example
>>> q = np.zeros((4, 4))
>>> q[0:2, 0:2] = -i
>>> q[2:4, 2:4] = i
>>> q # one of the three quarternion units not equal to 1
array([[ 0., -1., 0., 0.],
[ 1., 0., 0., 0.],
[ 0., 0., 0., 1.],
[ 0., 0., -1., 0.]])
>>> LA.matrix_power(q, 2) # = -np.eye(4)
array([[-1., 0., 0., 0.],
[ 0., -1., 0., 0.],
[ 0., 0., -1., 0.],
[ 0., 0., 0., -1.]])
"""
M = asanyarray(M)
if len(M.shape) != 2 or M.shape[0] != M.shape[1]:
raise ValueError("input must be a square array")
if not issubdtype(type(n), int):
raise TypeError("exponent must be an integer")
from numpy.linalg import inv
if n==0:
M = M.copy()
M[:] = identity(M.shape[0])
return M
elif n<0:
M = inv(M)
n *= -1
result = M
if n <= 3:
for _ in range(n-1):
result=N.dot(result, M)
return result
# binary decomposition to reduce the number of Matrix
# multiplications for n > 3.
beta = binary_repr(n)
Z, q, t = M, 0, len(beta)
while beta[t-q-1] == '0':
Z = N.dot(Z, Z)
q += 1
#.........这里部分代码省略.........
示例14: __rmul__
def __rmul__(self, other):
return N.dot(other, self)
示例15: __rmul__
def __rmul__(self, other):
# extract scalars from singleton matrices
if self.shape == (1,1):
return N.dot(other, self.flat[0])
else:
return N.dot(other, self)