Python numpy.asmatrix() 使用实例

The following are code examples for showing how to use . They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don’t like. You can also save this page to your account.

Example 1

```def test_approximate_range_finder(rows, cols, rank, dtype, piter_normalizer, rgen):
# only guaranteed to work for low-rank matrices
if rank is 'fullrank':
return

rf_size = rank + 10
assert min(rows, cols) > rf_size

A = mptest.random_lowrank(rows, cols, rank, randstate=rgen, dtype=dtype)
A /= np.linalg.norm(A, ord='fro')
Q = em.approx_range_finder(A, rf_size, 7, randstate=rgen,
piter_normalizer=piter_normalizer)

Q = np.asmatrix(Q)
assert Q.shape == (rows, rf_size)
normdist = np.linalg.norm(A - Q * (Q.H * A), ord='fro')
assert normdist < 1e-7 ```

Example 2

```def train(self):
eps = 1e-10
for i in range(self.epo):
if i % 1 == 0:
self.show_error()

A = np.asarray(self.A.copy())
Z = np.asarray(self.Z.copy())
start = time.time()
Z1 = np.multiply(Z, np.asarray(self.A.transpose() * self.Y))
Z = np.divide(Z1, eps + np.asarray(self.A.transpose() * self.A * self.Z)) # + eps to avoid divided by 0
self.Z = np.asmatrix(Z)
A1 = np.multiply(A, np.asarray( self.Y * self.Z.transpose()))
A = np.divide(A1, eps + np.asarray( self.A * self.Z * self.Z.transpose()))
end = time.time()
self.A = np.asmatrix(A)
self.time = self.time + end - start ```

Example 3

```def extractVecs():
t0 = time.clock()
with open(options.pretrained,'r') as f:
content = [item.rstrip().lower().split(' ') for item in f.readlines()]

globalWordFile = np.asmatrix(content,dtype = str)
globalWordTokens = globalWordFile[:,0].astype('str')
globalWordVectors = globalWordFile[:,1:].astype(np.float)
globalWordFile = None

### Pandas read_csv implementation - Broken
#globalWordVectors = globalWordFile.ix[:,1:]
#globalWordTokens = globalWordFile.ix[:,0]
#globalWordFile = None
print time.clock() - t0, " seconds taken for loading and slicing gLoVe Word Vectors"
return globalWordTokens,globalWordVectors ```

Example 4

```def random_portfolio(returns):
def rand_weights(n):
# Produces n random weights that sum to 1
k = np.random.rand(n)
return k / sum(k)

'''
Returns the mean and standard deviation of returns for a random portfolio
'''
p = np.asmatrix(np.mean(returns, axis=1))
w = np.asmatrix(rand_weights(returns.shape[0]))
C = np.asmatrix(np.cov(returns))

mu = w * p.T
sigma = np.sqrt(w * C * w.T)

# This recursion reduces outliers to keep plots pretty
if sigma > 2:
return random_portfolio(returns)
return mu, sigma ```

Example 5

```def shared_mnist():
def shared_dataset(data_xy):
data_x, data_y = data_xy
np_y = np.zeros((len(data_y), 10), dtype=theano.config.floatX)
for i in xrange(len(data_y)):
np_y[i, data_y[i]] = 1

shared_x = theano.shared(np.asmatrix(data_x, dtype=theano.config.floatX))
shared_y = theano.shared(np.asmatrix(np_y, dtype=theano.config.floatX))
return shared_x, shared_y
f = gzip.open(curr_path + "/data/mnist.pkl.gz", "rb")
f.close()

test_set_x, test_set_y = shared_dataset(test_set)
valid_set_x, valid_set_y = shared_dataset(valid_set)
train_set_x, train_set_y = shared_dataset(train_set)

return [train_set_x, train_set_y], [valid_set_x, valid_set_y], [test_set_x, test_set_y] ```

Example 6

```def testHorzConvWithVaryingImage(self):
image = np.asmatrix(('1.0 2.0 3.0;'
'1.1 2.0 4.0;'
'-4.3 0.0 8.9'))

expected = np.asmatrix(('-1.0 -1.0;'
'-0.9 -2.0;'
'-4.3 -8.9'))
expected = np.reshape(np.asarray(expected), (1, 3, 2, 1))

tf_image = tf.constant(image, shape=(1, 3, 3, 1), dtype=tf.float32)
tf_image,
weights_initializer=tf.constant_initializer([1, -1]),
kernel_size=[1, 2],
activation_fn=None)
init_op = tf.initialize_all_variables()

with self.test_session() as sess:
sess.run(init_op)

self.assertAllClose(result, expected, rtol=1e-5, atol=1e-5) ```

Example 7

```def testVertConvWithVaryingImage(self):
image = np.asmatrix(('1.0 2.0 3.0;'
'1.1 2.0 4.0;'
'-4.3 0.0 8.9'))

expected = np.asmatrix(('-0.1 0.0 -1.0;'
' 5.4 2.0 -4.9'))
expected = np.reshape(np.asarray(expected), (1, 2, 3, 1))

tf_image = tf.constant(image, shape=(1, 3, 3, 1), dtype=tf.float32)
tf_image,
weights_initializer=tf.constant_initializer([1, -1]),
kernel_size=[2, 1],
activation_fn=None)
init_op = tf.initialize_all_variables()

with self.test_session() as sess:
sess.run(init_op)

self.assertAllClose(result, expected, rtol=1e-5, atol=1e-5) ```

Example 8

```def testHorzConvWithVaryingImage(self):
image = np.asmatrix(('1.0 2.0 3.0;'
'1.1 2.0 4.0;'
'-4.3 0.0 8.9'))

expected = np.asmatrix(('-1.0 -1.0;'
'-0.9 -2.0;'
'-4.3 -8.9'))
expected = np.reshape(np.asarray(expected), (1, 3, 2, 1))

tf_image = tf.constant(image, shape=(1, 3, 3, 1), dtype=tf.float32)
tf_image,
weights_initializer=tf.constant_initializer([1, -1]),
kernel_size=[1, 2],
activation_fn=None)
init_op = tf.global_variables_initializer()

with self.test_session() as sess:
sess.run(init_op)

self.assertAllClose(result, expected, rtol=1e-5, atol=1e-5) ```

Example 9

```def testVertConvWithVaryingImage(self):
image = np.asmatrix(('1.0 2.0 3.0;'
'1.1 2.0 4.0;'
'-4.3 0.0 8.9'))

expected = np.asmatrix(('-0.1 0.0 -1.0;'
' 5.4 2.0 -4.9'))
expected = np.reshape(np.asarray(expected), (1, 2, 3, 1))

tf_image = tf.constant(image, shape=(1, 3, 3, 1), dtype=tf.float32)
tf_image,
weights_initializer=tf.constant_initializer([1, -1]),
kernel_size=[2, 1],
activation_fn=None)
init_op = tf.global_variables_initializer()

with self.test_session() as sess:
sess.run(init_op)

self.assertAllClose(result, expected, rtol=1e-5, atol=1e-5) ```

Example 10

```def fkine(self, stance, unit='rad', apply_stance=False, actor_list=None, timer=None):
"""
Calculates forward kinematics for a list of joint angles.
:param stance: stance is list of joint angles.
:param unit: unit of input angles.
:param apply_stance: If True, then applied tp actor_list.
:param actor_list: Passed to apply transformations computed by fkine.
:param timer: internal use only (for animation).
:return: homogeneous transformation matrix.
"""
if type(stance) is np.ndarray:
stance = np.asmatrix(stance)
if unit == 'deg':
stance = stance * pi / 180
if timer is None:
timer = 0
t = self.base
for i in range(self.length):
if apply_stance:
actor_list[i].SetUserMatrix(transforms.np2vtk(t))
t = t * self.links[i].A(stance[timer, i])
t = t * self.tool
if apply_stance:
actor_list[self.length].SetUserMatrix(transforms.np2vtk(t))
return t ```

Example 11

```def rotx(theta, unit="rad"):
"""
ROTX gives rotation about X axis

:param theta: angle for rotation matrix
:param unit: unit of input passed. 'rad' or 'deg'
:return: rotation matrix

rotx(THETA) is an SO(3) rotation matrix (3x3) representing a rotation
rotx(THETA, "deg") as above but THETA is in degrees
"""
check_args.unit_check(unit)
if unit == "deg":
theta = theta * math.pi / 180
ct = math.cos(theta)
st = math.sin(theta)
mat = np.matrix([[1, 0, 0], [0, ct, -st], [0, st, ct]])
mat = np.asmatrix(mat.round(15))
return mat

# ---------------------------------------------------------------------------------------# ```

Example 12

```def roty(theta, unit="rad"):
"""

:param theta: angle for rotation matrix
:param unit: unit of input passed. 'rad' or 'deg'
:return: rotation matrix

roty(THETA) is an SO(3) rotation matrix (3x3) representing a rotation
roty(THETA, "deg") as above but THETA is in degrees
"""
check_args.unit_check(unit)
if unit == "deg":
theta = theta * math.pi / 180
ct = math.cos(theta)
st = math.sin(theta)
mat = np.matrix([[ct, 0, st], [0, 1, 0], [-st, 0, ct]])
mat = np.asmatrix(mat.round(15))
return mat

# ---------------------------------------------------------------------------------------# ```

Example 13

```def trotx(theta, unit="rad", xyz=[0, 0, 0]):
"""

:param theta: rotation in radians or degrees
:param unit: "rad" or "deg" to indicate unit being used
:param xyz: the xyz translation, if blank defaults to [0,0,0]
:return: homogeneous transform matrix

trotx(THETA) is a homogeneous transformation (4x4) representing a rotation
trotx(THETA, 'deg') as above but THETA is in degrees
trotx(THETA, 'rad', [x,y,z]) as above with translation of [x,y,z]
"""
check_args.unit_check(unit)
tm = rotx(theta, unit)
tm = np.r_[tm, np.zeros((1, 3))]
mat = np.c_[tm, np.array([[xyz[0]], [xyz[1]], [xyz[2]], [1]])]
mat = np.asmatrix(mat.round(15))
return mat

# ---------------------------------------------------------------------------------------# ```

Example 14

```def troty(theta, unit="rad", xyz=[0, 0, 0]):
"""

:param theta: rotation in radians or degrees
:param unit: "rad" or "deg" to indicate unit being used
:param xyz: the xyz translation, if blank defaults to [0,0,0]
:return: homogeneous transform matrix

troty(THETA) is a homogeneous transformation (4x4) representing a rotation
troty(THETA, 'deg') as above but THETA is in degrees
troty(THETA, 'rad', [x,y,z]) as above with translation of [x,y,z]
"""
check_args.unit_check(unit)
tm = roty(theta, unit)
tm = np.r_[tm, np.zeros((1, 3))]
mat = np.c_[tm, np.array([[xyz[0]], [xyz[1]], [xyz[2]], [1]])]
mat = np.asmatrix(mat.round(15))
return mat

# ---------------------------------------------------------------------------------------# ```

Example 15

```def trotz(theta, unit="rad", xyz=[0, 0, 0]):
"""

:param theta: rotation in radians or degrees
:param unit: "rad" or "deg" to indicate unit being used
:param xyz: the xyz translation, if blank defaults to [0,0,0]
:return: homogeneous transform matrix

trotz(THETA) is a homogeneous transformation (4x4) representing a rotation
trotz(THETA, 'deg') as above but THETA is in degrees
trotz(THETA, 'rad', [x,y,z]) as above with translation of [x,y,z]
"""
check_args.unit_check(unit)
tm = rotz(theta, unit)
tm = np.r_[tm, np.zeros((1, 3))]
mat = np.c_[tm, np.array([[xyz[0]], [xyz[1]], [xyz[2]], [1]])]
mat = np.asmatrix(mat.round(15))
return mat

# ---------------------------------------------------------------------------------------# ```

Example 16

```def m8_motif(A):
B, U, G = directional_breakup(A)
W = np.zeros(G.shape)
W = np.asmatrix(W)
N = G.shape[0]
# print('U\n', U)
for i in range(N):
J = np.nonzero(U[i, :])[1]
# print(J)
for j1 in range(len(J)):
for j2 in range(j1 + 1, len(J)):
k1 = J[j1]
k2 = J[j2]
# print(k1, k2)
if A[k1, k2] == 0 and A[k2, k1] == 0:
W[i, k1] = W[i, k1] + 1
W[i, k2] = W[i, k2] + 1
W[k1, k2] = W[k1, k2] + 1

W = W + W.T

# matlab use W = sparse(W + W')
# I think it is properly use W = W+W'T

return W ```

Example 17

```def __init__(self, shape, optimizer='seq', lr=0.01, clip_min=0, clip_max=1081, is_round=True):
'''
param shape: phi_x shape
'''
self.optimizer = optimizer
self.lr = lr
self.shape = shape
self.learning_rate_decay = 0.99

# w is Mx1 column vector
self.w = np.asmatrix(self._init_weight(shape + (1,)))

# Setup model
self._setup_model()

# Setup optimizer (vary from models)
self._setup_optimizer() ```

Example 18

```def back_propagation(self,gradient):

# -----------the Negative gradient direction --------
self.weight = self.weight - self.learn_rate * self.gradient_weight
self.bias = self.bias - self.learn_rate * self.gradient_bias.T

Example 19

```def pooling(self,featuremaps,size_pooling,type='average_pool'):
#pooling process
size_map = len(featuremaps[0])
size_pooled = int(size_map/size_pooling)
featuremap_pooled = []
for i_map in range(len(featuremaps)):
map = featuremaps[i_map]
map_pooled = []
for i_focus in range(0,size_map,size_pooling):
for j_focus in range(0, size_map, size_pooling):
focus = map[i_focus:i_focus + size_pooling, j_focus:j_focus + size_pooling]
if type == 'average_pool':
#average pooling
map_pooled.append(np.average(focus))
elif type == 'max_pooling':
#max pooling
map_pooled.append(np.max(focus))
map_pooled = np.asmatrix(map_pooled).reshape(size_pooled,size_pooled)
featuremap_pooled.append(map_pooled)
return featuremap_pooled ```

Example 20

```def make_symmetric_lower(mat):
'''
Copies the matrix entries below the main diagonal to the upper triangle
half of the matrix. Leaves the diagonal unchanged. Returns a `NumPy` matrix
object.

**mat** : `numpy.matrix`
A lower diagonal matrix.

returns : `numpy.matrix`
The lower triangle matrix.
'''

# extract lower triangle from matrix (including diagonal)
tmp_mat = np.tril(mat)

# if the matrix given wasn't a lower triangle matrix, raise an error
if (mat != tmp_mat).all():
raise Exception('Matrix to symmetrize is not a lower diagonal matrix.')

# add its transpose to itself, zeroing the diagonal to avoid doubling
tmp_mat += np.triu(tmp_mat.transpose(), 1)

return np.asmatrix(tmp_mat) ```

Example 21

```def get_error_matrix(self, correlation=False):  # VIEWED TODO
'''Retrieves the parameter error matrix from iminuit.

correlation : boolean (optional, default ``False``)
If ``True``, return correlation matrix, else return
covariance matrix.

return : `numpy.matrix`
'''

# get parameter covariance matrix from iminuit

# FIX_UPSTREAM we need skip_fixed=False, but this is unsupported
#_mat = self.__iminuit.matrix(correlation, skip_fixed=False)

# ... so use skip_fixed=False instead and fill in the gaps
_mat = self.__iminuit.matrix(correlation, skip_fixed=True)
_mat = np.asmatrix(_mat)  # reshape into numpy matrix
_mat = self._fill_in_zeroes_for_fixed(_mat)  # fill in fixed par 'gaps'

return _mat ```

Example 22

```def _mvee(self, points, tolerance):
# Taken from: http://stackoverflow.com/questions/14016898/port-matlab-bounding-ellipsoid-code-to-python
points = np.asmatrix(points)
n, d = points.shape
q = np.column_stack((points, np.ones(n))).T
err = tolerance + 1.0
u = np.ones(n) / n
while err > tolerance:
# assert u.sum() == 1 # invariant
x = q * np.diag(u) * q.T
m = np.diag(q.T * la.inv(x) * q)
jdx = np.argmax(m)
step_size = (m[jdx] - d - 1.0) / ((d + 1) * (m[jdx] - 1.0))
new_u = (1 - step_size) * u
new_u[jdx] += step_size
err = la.norm(new_u - u)
u = new_u
c = u * points
a = la.inv(points.T * np.diag(u) * points - c.T * c) / d
return np.asarray(a), np.squeeze(np.asarray(c)) ```

Example 23

```def word_sequence(f_path, batch_size = 1, i2w, w2i):
test_seqs = []
lines = []
tf = {}
f = open(curr_path + "/" + f_path, "r")
for line in f:
line = line.strip('\n').lower()
words = ['<soss>']+line_x.split()+["<eoss>"]
lines.append(words)
f.close()

for i in range(0, len(lines)):
words = lines[i]
x = np.zeros((len(words), len(w2i)), dtype = theano.config.floatX)
for j in range(0, len(words)):
if words[j] in w2i:
x[j, w2i[words[j]]] = 1
test_seqs.append(np.asmatrix(x))

test_data_x = batch_sequences(test_seqs, i2w, w2i, batch_size)

return test_seqs, i2w, w2i, test_data_x ```

Example 24

```def sim(A, B, time, x0, controller):
x = np.asmatrix(x0)
prev_y = np.dot(H, x)
x_out = []
x_hat_out = []
u_out = []
time_out = []

for t in xrange(time):
x_hat = x + ((np.random.random((2,1)) - 0.5) * 0.05)
y = np.dot(H, x_hat)
u = np.clip(controller(y, prev_y), -40, 40)
x = np.dot(A, x) + np.dot(B, u)

x_out.append(x)
x_hat_out.append(x_hat)
u_out.append(u)
time_out.append(t*dt)

prev_y = np.copy(y)

return (np.asarray(time_out), np.asarray(x_out), np.asarray(x_hat_out), np.asarray(u_out)) ```

Example 25

```def _beta_cal(self,observations,c_scale):
# Calculate Beta maxtrix
num_states = self.em_prob.shape[0]
total_stages = len(observations)

# Initialize values
ob_ind = self.obs_map[ observations[total_stages-1] ]
beta = np.asmatrix(np.zeros((num_states,total_stages)))

# Handle beta base case
beta[:,total_stages-1] = c_scale[total_stages-1]

# Iteratively calculate beta(t) for all 't'
for curr_t in range(total_stages-1,0,-1):
ob_ind = self.obs_map[observations[curr_t]]
beta[:,curr_t-1] = np.multiply( beta[:,curr_t] , self.em_prob[:,ob_ind] )
beta[:,curr_t-1] = np.dot( self.trans_prob, beta[:,curr_t-1] )
beta[:,curr_t-1] = np.multiply( beta[:,curr_t-1] , c_scale[curr_t -1 ] )

# return the computed beta
return beta ```

Example 26

```def _train_emission(self,observations):
# Initialize matrix
new_em_prob = np.asmatrix(np.zeros(self.em_prob.shape))

# Indexing position of unique observations in the observation sequence
selectCols=[]
for i in range(self.em_prob.shape[1]):
selectCols.append([])
for i in range(len(observations)):
selectCols[ self.obs_map[observations[i]] ].append(i)

# Calculate delta matrix
delta = self._forward_backward(observations)

# Sum the rowise of delta matrix, which gives probability of a particular state
totalProb = np.sum(delta,axis=1)

# Re-estimate emission matrix
for i in range(self.em_prob.shape[0]):
for j in range(self.em_prob.shape[1]):
new_em_prob[i,j] = np.sum(delta[i,selectCols[j]])/totalProb[i]
return new_em_prob ```

Example 27

```def _train_transition(self,observations):
# Initialize transition matrix
new_trans_prob = np.asmatrix(np.zeros(self.trans_prob.shape))

# Find alpha and beta
alpha,c = self._alpha_cal(observations)
beta = self._beta_cal(observations,c)

# calculate transition matrix values
for t in range(len(observations)-1):
temp1 = np.multiply(alpha[:,t],beta[:,t+1].transpose())
temp1 = np.multiply(self.trans_prob,temp1)
new_trans_prob = new_trans_prob + np.multiply(temp1,self.em_prob[:,self.obs_map[observations[t+1]]].transpose())

# Normalize values so that sum of probabilities is 1
for i in range(self.trans_prob.shape[0]):
new_trans_prob[i,:] = new_trans_prob[i,:]/np.sum(new_trans_prob[i,:])

return new_trans_prob ```

Example 28

```def add_pixels(self, uv_px, img1d, weight=None):
# Lookup row & column for each in-bounds coordinate.
# Update matrix according to assigned weight.
if weight is None:
elif np.isscalar(weight):
else:
w1 = np.asmatrix(weight, dtype='float32')
w3 = w1.transpose() * np.ones((1,3))

# A panorama image made from several FisheyeImage sources.
# TODO: Add support for supersampled anti-aliasing filters. ```

Example 29

```def coherence_of_columns(A):
"""Mutual coherence of columns of A.

Parameters
----------
A : array_like
Input matrix.
p : int, optional
p-th norm.

Returns
-------
array_like
Mutual coherence of columns of A.
"""
A = np.asmatrix(A)
_, N = A.shape
A = A * np.asmatrix(np.diag(1/norm_of_columns(A)))
Gram_A = A.H*A
for j in range(N):
Gram_A[j, j] = 0
return np.max(np.abs(Gram_A)) ```

Example 30

```def testHorzConvWithVaryingImage(self):
image = np.asmatrix(('1.0 2.0 3.0;' '1.1 2.0 4.0;' '-4.3 0.0 8.9'))

expected = np.asmatrix(('-1.0 -1.0;' '-0.9 -2.0;' '-4.3 -8.9'))
expected = np.reshape(np.asarray(expected), (1, 3, 2, 1))

tf_image = constant_op.constant(
image, shape=(1, 3, 3, 1), dtype=dtypes.float32)
tf_image,
weights_initializer=init_ops.constant_initializer([1, -1]),
kernel_size=[1, 2],
activation_fn=None)
init_op = variables_lib.global_variables_initializer()

with self.test_session() as sess:
sess.run(init_op)

self.assertAllClose(result, expected, rtol=1e-5, atol=1e-5) ```

Example 31

```def testVertConvWithVaryingImage(self):
image = np.asmatrix(('1.0 2.0 3.0;' '1.1 2.0 4.0;' '-4.3 0.0 8.9'))

expected = np.asmatrix(('-0.1 0.0 -1.0;' ' 5.4 2.0 -4.9'))
expected = np.reshape(np.asarray(expected), (1, 2, 3, 1))

tf_image = constant_op.constant(
image, shape=(1, 3, 3, 1), dtype=dtypes.float32)
tf_image,
weights_initializer=init_ops.constant_initializer([1, -1]),
kernel_size=[2, 1],
activation_fn=None)
init_op = variables_lib.global_variables_initializer()

with self.test_session() as sess:
sess.run(init_op)

self.assertAllClose(result, expected, rtol=1e-5, atol=1e-5) ```

Example 32

```def improve_admm(x0, prob, *args, **kwargs):
num_iters = kwargs.get('num_iters', 1000)
viol_lim = kwargs.get('viol_lim', 1e4)
tol = kwargs.get('tol', 1e-2)
rho = kwargs.get('rho', None)
phase1 = kwargs.get('phase1', True)

if rho is not None:
lmb0, P0Q = map(np.asmatrix, LA.eigh(prob.f0.P.todense()))
lmb_min = np.min(lmb0)
if lmb_min + prob.m*rho < 0:
logging.error("rho parameter is too small, z-update not convex.")
logging.error("Minimum possible value of rho: %.3f\n", -lmb_min/prob.m)
logging.error("Given value of rho: %.3f\n", rho)
raise Exception("rho parameter is too small, need at least %.3f." % rho)

# TODO: find a reasonable auto parameter
if rho is None:
lmb0, P0Q = map(np.asmatrix, LA.eigh(prob.f0.P.todense()))
lmb_min = np.min(lmb0)
lmb_max = np.max(lmb0)
if lmb_min < 0: rho = 2.*(1.-lmb_min)/prob.m
else: rho = 1./prob.m
rho *= 50.
logging.warning("Automatically setting rho to %.3f", rho)

if phase1:
x1 = prob.better(x0, admm_phase1(x0, prob, tol, num_iters))
else:
x1 = x0
x2 = prob.better(x1, admm_phase2(x1, prob, rho, tol, num_iters, viol_lim))
return x2 ```

Example 33

```def dot(X, Y):
if sparse.isspmatrix(X) and sparse.isspmatrix(Y):
return X * Y
elif sparse.isspmatrix(X) or sparse.isspmatrix(Y):
return sparse.csr_matrix(X) * sparse.csr_matrix(Y)

return np.asmatrix(X) * np.asmatrix(Y) ```

Example 34

```def transformPoint2D(pt, M):
"""
Transform point in 2D coordinates
:param pt: point coordinates
:param M: transformation matrix
:return: transformed point
"""
pt2 = numpy.asmatrix(M.reshape((3, 3))) * numpy.matrix([pt[0], pt[1], 1]).T
return numpy.array([pt2[0] / pt2[2], pt2[1] / pt2[2]]) ```

Example 35

```def transformPoint3D(pt, M):
"""
Transform point in 3D coordinates
:param pt: point coordinates
:param M: transformation matrix
:return: transformed point
"""
pt3 = numpy.asmatrix(M.reshape((4, 4))) * numpy.matrix([pt[0], pt[1], pt[2], 1]).T
return numpy.array([pt3[0] / pt3[3], pt3[1] / pt3[3], pt3[2] / pt3[3]]) ```

Example 36

```def test_matrix_fancy(self):
# The matrix class messes with the shape. While this is always
# weird (getitem is not used, it does not have setitem nor knows
# about fancy indexing), this tests gh-3110
m = np.matrix([[1, 2], [3, 4]])

assert_(isinstance(m[[0,1,0], :], np.matrix))

# gh-3110. Note the transpose currently because matrices do *not*
# support dimension fixing for fancy indexing correctly.
x = np.asmatrix(np.arange(50).reshape(5,10))
assert_equal(x[:2, np.array(-1)], x[:2, -1].T) ```

Example 37

```def eye(n,M=None, k=0, dtype=float):
"""
Return a matrix with ones on the diagonal and zeros elsewhere.

Parameters
----------
n : int
Number of rows in the output.
M : int, optional
Number of columns in the output, defaults to `n`.
k : int, optional
Index of the diagonal: 0 refers to the main diagonal,
a positive value refers to an upper diagonal,
and a negative value to a lower diagonal.
dtype : dtype, optional
Data-type of the returned matrix.

Returns
-------
I : matrix
A `n` x `M` matrix where all elements are equal to zero,
except for the `k`-th diagonal, whose values are equal to one.

--------
numpy.eye : Equivalent array function.
identity : Square identity matrix.

Examples
--------
>>> import numpy.matlib
>>> np.matlib.eye(3, k=1, dtype=float)
matrix([[ 0.,  1.,  0.],
[ 0.,  0.,  1.],
[ 0.,  0.,  0.]])

"""
return asmatrix(np.eye(n, M, k, dtype)) ```

Example 38

```def test_matrix_std_argmax(self,level=rlevel):
# Ticket #83
x = np.asmatrix(np.random.uniform(0, 1, (3, 3)))
self.assertEqual(x.std().shape, ())
self.assertEqual(x.argmax().shape, ()) ```

Example 39

```def test_asmatrix(self):
A = np.arange(100).reshape(10, 10)
mA = asmatrix(A)
A[0, 0] = -10
assert_(A[0, 0] == mA[0, 0]) ```

Example 40

```def test_basic(self):
x = asmatrix(np.zeros((3, 2), float))
y = np.zeros((3, 1), float)
y[:, 0] = [0.8, 0.2, 0.3]
x[:, 1] = y > 0.5
assert_equal(x, [[0, 1], [0, 0], [0, 0]]) ```

Example 41

```def test_scalar_indexing(self):
x = asmatrix(np.zeros((3, 2), float))
assert_equal(x[0, 0], x[0][0]) ```

Example 42

```def test_row_column_indexing(self):
x = asmatrix(np.eye(2))
assert_array_equal(x[0,:], [[1, 0]])
assert_array_equal(x[1,:], [[0, 1]])
assert_array_equal(x[:, 0], [[1], [0]])
assert_array_equal(x[:, 1], [[0], [1]]) ```

Example 43

```def test_list_indexing(self):
A = np.arange(6)
A.shape = (3, 2)
x = asmatrix(A)
assert_array_equal(x[:, [1, 0]], x[:, ::-1])
assert_array_equal(x[[2, 1, 0],:], x[::-1,:]) ```

Example 44

```def lms(x1: numpy.array, x2: numpy.array, N: int):
# Verify argument shape.
s1, s2 = x1.shape, x2.shape
if len(s1) != 1 or len(s2) != 1 or s1[0] != s2[0]:
raise Exception("Argument shape invalid, in 'lms' function")
l = s1[0]

# Coefficient matrix
W = numpy.mat(numpy.zeros([1, 2 * N + 1]))
# Coefficient (time) matrix
Wt = numpy.mat(numpy.zeros([l, 2 * N + 1]))
# Feedback (time) matrix
y = numpy.mat(numpy.zeros([l, 1]))
# Error (time) matrix
e = numpy.mat(numpy.zeros([l, 1]))

# Traverse channel data
for i in range(N, l-N):
x1_vec = numpy.asmatrix(x1[i-N:i+N+1])
y[i] = x1_vec * numpy.transpose(W)
e[i] = x2[i] - y[i]
W += mu * e[i] * x1_vec
Wt[i] = W

# Find the coefficient matrix which has max maximum.
Wt_maxs = numpy.max(Wt, axis=1)
row_idx = numpy.argmax(Wt_maxs)
max_W = Wt[row_idx]
delay_count = numpy.argmax(max_W) - N

plot(l, x1, x2, y, e)

return delay_count ```

Example 45

```def evaluate_portefolio(wei, returns_vec):
""" Given a repartition, compute expected return and risk from a portefolio

:param wei: Weights for each currency
:type wei: ndarray of float
:return: expected return and risk
:rtype: (float, float)
"""
p = np.asmatrix(np.mean(returns_vec, axis=1))
w = np.asmatrix(wei)
c = np.asmatrix(np.cov(returns_vec))
mu = w * p.T
sigma = np.sqrt(w * c * w.T)
return mu, sigma ```

Example 46

```def lpfls2notch(N,wp,ws,wn1,wn2,W):
M = (N-1)/2
nq = np.arange(0,2*M+1)
nb = np.arange(0,M+1)
q = (wp/np.pi)*np.sinc((wp/np.pi)*nq) - W*(ws/np.pi)*np.sinc((ws/np.pi)*nq)
b = (wp/np.pi)*np.sinc((wp/np.pi)*nb)
q[0] = wp/np.pi + W*(1-ws/np.pi) # since sin(pi*n)/pi*n = 1, not 0
b = np.asmatrix(b)
b = b.transpose()

Q1 = ln.toeplitz(q[0:M+1])
Q2 = ln.hankel(q[0:M+1],q[M:])
Q = Q1+Q2

G1 = np.cos(wn1*nb)
G2 = np.cos(wn2*nb)
G = np.matrix([G1,G2])

d = np.array([0,0])
d = np.asmatrix(d)
d = d.transpose()

c = np.asmatrix(ln.solve(Q,b))

mu = ln.solve(G*ln.inv(Q)*G.transpose(),G*c - d)

a = c - ln.solve(Q,G.transpose()*mu)
h = np.zeros(N)
for i in nb:
h[i] = 0.5*a[M-i]
h[N-1-i] = h[i]
h[M] = 2*h[M]
hmax = max(np.absolute(h))
for i in nq:
h[i] = (8191/hmax)*h[i]
return h ```

Example 47

```def lpfls1notch(N,wp,ws,wn1,W):
M = (N-1)/2
nq = np.arange(0,2*M+1)
nb = np.arange(0,M+1)
q = (wp/np.pi)*np.sinc((wp/np.pi)*nq) - W*(ws/np.pi)*np.sinc((ws/np.pi)*nq)
b = (wp/np.pi)*np.sinc((wp/np.pi)*nb)
q[0] = wp/np.pi + W*(1-ws/np.pi) # since sin(pi*n)/pi*n = 1, not 0
b = np.asmatrix(b)
b = b.transpose()

Q1 = ln.toeplitz(q[0:M+1])
Q2 = ln.hankel(q[0:M+1],q[M:])
Q = Q1+Q2

G1 = np.cos(wn1*nb)
G = np.matrix([G1])

d = np.array([0])
d = np.asmatrix(d)

c = np.asmatrix(ln.solve(Q,b))

mu = ln.solve(G*ln.inv(Q)*G.transpose(),G*c - d)

a = c - ln.solve(Q,G.transpose()*mu)
h = np.zeros(N)
for i in nb:
h[i] = 0.5*a[M-i]
h[N-1-i] = h[i]
h[M] = 2*h[M]
hmax = max(np.absolute(h))
for i in nq:
h[i] = (8191/hmax)*h[i]
return h ```

Example 48

```def decoding(self):
D = self.A_true.shape[1]
num_doc = self.Y.shape[1]
Z = np.asmatrix(np.zeros((D, num_doc)))
A = np.asarray(self.A.copy())
Y = np.asarray(self.Y.copy())
for i in range(num_doc):
Yi = np.array(Y[:, i]).flatten()
t, bla = nnls(A, Yi)
Z[:, i] = np.asmatrix(t).transpose()
Z = np.asmatrix(Z)
return Z ```

Example 49

```def decoding(self):
D = self.A_true.shape[1]
num_doc = self.Y.shape[1]
Z = np.asmatrix(np.zeros((D, num_doc)))
for i in range(num_doc):
Yi = np.array(self.Y[:, i].copy()).flatten()
A = np.asarray(self.A.copy())
t, bla = nnls(A, Yi)
Z[:, i] = np.asmatrix(t).transpose()
Z = np.asmatrix(Z)
return Z ```

Example 50

```def train(self):
D = self.A_true.shape[1]
for i in range(20):
self.show_error()

start = time.time()
prior = self.sparsity / np.float(self.A_true.shape[1])
lda = LDA(n_topics=D, random_state=0, doc_topic_prior = prior, max_iter=i)
lda.fit(self.Y.transpose())
end = time.time()
self.time = end - start
self.A = np.asmatrix(lda.components_.transpose()) ```