本文整理汇总了Python中numpy.matrix方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.matrix方法的具体用法?Python numpy.matrix怎么用?Python numpy.matrix使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.matrix方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: set_state
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import matrix [as 别名]
def set_state(self, new_state):
'''
Set Hipster's new type.
This comes from evaling the env.
Args:
new_state: the agent's new state
Returns:
None
'''
old_type = self.ntype
self.state = new_state
self.ntype = STATE_MAP[new_state]
self.env.change_agent_type(self, old_type, self.ntype)
# Unlike the forest fire model, we don't here update environment's cell's
# transition matrices. This is because the cell's transition matrix depends
# on all the agents near it, not just one.
示例2: get_pre
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import matrix [as 别名]
def get_pre(self, agent, n_census):
trans_str = ""
d, total = self.dir_info(agent)
if type(agent) == Zombie:
trans_str += self.zombie_trans(d, total)
else:
trans_str += self.human_trans(d, total)
trans_matrix = markov.from_matrix(np.matrix(trans_str))
return trans_matrix
# Finds out which direction (NORTH, SOUTH, EAST, WEST) as more of the
# opposite agent type depending on what agent we are dealing with
# CAN'T GET RID OF OLD METHOD OF MOVEMENT DUE TO ERRORS
# IN OTHER SCRIPTS
示例3: predict_all
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import matrix [as 别名]
def predict_all(X, all_theta):
rows = X.shape[0]
params = X.shape[1]
num_labels = all_theta.shape[0]
# same as before, insert ones to match the shape
X = np.insert(X, 0, values=np.ones(rows), axis=1)
# convert to matrices
X = np.matrix(X)
all_theta = np.matrix(all_theta)
# compute the class probability for each class on each training instance
h = sigmoid(X * all_theta.T)
# create array of the index with the maximum probability
h_argmax = np.argmax(h, axis=1)
# because our array was zero-indexed we need to add one for the true label prediction
h_argmax = h_argmax + 1
return h_argmax
示例4: cost0
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import matrix [as 别名]
def cost0(params, input_size, hidden_size, num_labels, X, y, learning_rate):
m = X.shape[0]
X = np.matrix(X)
y = np.matrix(y)
# reshape the parameter array into parameter matrices for each layer
theta1 = np.matrix(np.reshape(params[:hidden_size * (input_size + 1)], (hidden_size, (input_size + 1))))
theta2 = np.matrix(np.reshape(params[hidden_size * (input_size + 1):], (num_labels, (hidden_size + 1))))
# run the feed-forward pass
a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)
# compute the cost
J = 0
for i in range(m):
first_term = np.multiply(-y[i,:], np.log(h[i,:]))
second_term = np.multiply((1 - y[i,:]), np.log(1 - h[i,:]))
J += np.sum(first_term - second_term)
J = J / m
return J
示例5: cost
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import matrix [as 别名]
def cost(params, Y, R, num_features):
Y = np.matrix(Y) # (1682, 943)
R = np.matrix(R) # (1682, 943)
num_movies = Y.shape[0]
num_users = Y.shape[1]
# reshape the parameter array into parameter matrices
X = np.matrix(np.reshape(params[:num_movies * num_features], (num_movies, num_features))) # (1682, 10)
Theta = np.matrix(np.reshape(params[num_movies * num_features:], (num_users, num_features))) # (943, 10)
# initializations
J = 0
# compute the cost
error = np.multiply((X * Theta.T) - Y, R) # (1682, 943)
squared_error = np.power(error, 2) # (1682, 943)
J = (1. / 2) * np.sum(squared_error)
return J
示例6: gradientReg
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import matrix [as 别名]
def gradientReg(theta, X, y, learningRate):
theta = np.matrix(theta)
X = np.matrix(X)
y = np.matrix(y)
parameters = int(theta.ravel().shape[1])
grad = np.zeros(parameters)
error = sigmoid(X * theta.T) - y
for i in range(parameters):
term = np.multiply(error, X[:,i])
if (i == 0):
grad[i] = np.sum(term) / len(X)
else:
grad[i] = (np.sum(term) / len(X)) + ((learningRate / len(X)) * theta[:,i])
return grad
示例7: _icp_find_rigid_transform
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import matrix [as 别名]
def _icp_find_rigid_transform(p_from, p_target):
######### flag = 1 for SVD
######### flag = 2 for Gaussian
A, B = np.copy(p_from), np.copy(p_target)
centroid_A = np.mean(A, axis=0)
centroid_B = np.mean(B, axis=0)
A -= centroid_A # 500x3
B -= centroid_B # 500x3
H = np.dot(A.T, B) # 3x3
# print(H)
U, S, Vt = np.linalg.svd(H)
# H_new = U*np.matrix(np.diag(S))*Vt
# print(H_new)
R = np.dot(Vt.T, U.T)
# special reflection case
if np.linalg.det(R) < 0:
Vt[2,:] *= -1
R = np.dot(Vt.T, U.T)
t = np.dot(-R, centroid_A) + centroid_B
return R, t
示例8: controller_lqr_discrete_from_continuous_time
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import matrix [as 别名]
def controller_lqr_discrete_from_continuous_time(A, B, Q, R, dt):
"""Solve the discrete time LQR controller for a continuous time system.
A and B are system matrices, describing the systems dynamics:
dx/dt = A x + B u
The controller minimizes the infinite horizon quadratic cost function:
cost = integral (x.T*Q*x + u.T*R*u) dt
where Q is a positive semidefinite matrix, and R is positive definite matrix.
The controller is implemented to run at discrete times, at a rate given by
onboard_dt,
i.e. u[k] = -K*x(k*t)
Discretization is done by zero order hold.
Returns K, X, eigVals:
Returns gain the optimal gain K, the solution matrix X, and the closed loop system eigenvalues.
The optimal input is then computed as:
input: u = -K*x
"""
#ref Bertsekas, p.151
Ad, Bd = analysis.discretise_time(A, B, dt)
return controller_lqr_discrete_time(Ad, Bd, Q, R)
示例9: heston_construct_correlated_path
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import matrix [as 别名]
def heston_construct_correlated_path(params: ModelParameters,
brownian_motion_one: np.array):
"""
This method is a simplified version of the Cholesky decomposition method
for just two assets. It does not make use of matrix algebra and is therefore
quite easy to implement.
Arguments:
params : ModelParameters
The parameters for the stochastic model.
brownian_motion_one : np.array
(Not filled)
Returns:
A correlated brownian motion path.
"""
# We do not multiply by sigma here, we do that in the Heston model
sqrt_delta = np.sqrt(params.all_delta)
# Construct a path correlated to the first path
brownian_motion_two = []
for i in range(params.all_time - 1):
term_one = params.cir_rho * brownian_motion_one[i]
term_two = np.sqrt(1 - pow(params.cir_rho, 2)) * random.normalvariate(0, sqrt_delta)
brownian_motion_two.append(term_one + term_two)
return np.array(brownian_motion_one), np.array(brownian_motion_two)
示例10: add_pixels
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import matrix [as 别名]
def add_pixels(self, uv_px, img1d, weight=None):
# Lookup row & column for each in-bounds coordinate.
mask = self.get_mask(uv_px)
xx = uv_px[0,mask]
yy = uv_px[1,mask]
# Update matrix according to assigned weight.
if weight is None:
img1d[mask] = self.img[yy,xx]
elif np.isscalar(weight):
img1d[mask] += self.img[yy,xx] * weight
else:
w1 = np.asmatrix(weight, dtype='float32')
w3 = w1.transpose() * np.ones((1,3))
img1d[mask] += np.multiply(self.img[yy,xx], w3[mask])
# A panorama image made from several FisheyeImage sources.
# TODO: Add support for supersampled anti-aliasing filters.
示例11: render_cubemap
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import matrix [as 别名]
def render_cubemap(self, out_size, mode='blend'):
# Create coordinate arrays.
cvec = np.arange(out_size, dtype='float32') - out_size/2 # Coordinate range [-S/2, S/2)
vec0 = np.ones(out_size*out_size, dtype='float32') * out_size/2 # Constant vector +S/2
vec1 = np.repeat(cvec, out_size) # Increment every N steps
vec2 = np.tile(cvec, out_size) # Sweep N times
# Create XYZ coordinate vectors and render each cubemap face.
render = lambda(xyz): self._render(xyz, out_size, out_size, mode)
xm = render(np.matrix([-vec0, vec1, vec2])) # -X face
xp = render(np.matrix([vec0, vec1, -vec2])) # +X face
ym = render(np.matrix([-vec1, -vec0, vec2])) # -Y face
yp = render(np.matrix([vec1, vec0, vec2])) # +Y face
zm = render(np.matrix([-vec2, vec1, -vec0])) # -Z face
zp = render(np.matrix([vec2, vec1, vec0])) # +Z face
# Concatenate the individual faces in canonical order:
# https://en.wikipedia.org/wiki/Cube_mapping#Memory_Addressing
img_mat = np.concatenate([zp, zm, ym, yp, xm, xp], axis=0)
return Image.fromarray(img_mat)
# Get XYZ vectors for an equirectangular render, in raster order.
# (Each row left to right, with rows concatenates from top to bottom.)
示例12: _get_equirectangular_raster
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import matrix [as 别名]
def _get_equirectangular_raster(self, out_size):
# Set image size (2x1 aspect ratio)
rows = out_size
cols = 2*out_size
# Calculate longitude of each column.
theta_x = np.linspace(-pi, pi, cols, endpoint=False, dtype='float32')
cos_x = np.cos(theta_x).reshape(1,cols)
sin_x = np.sin(theta_x).reshape(1,cols)
# Calculate lattitude of each row.
ystep = pi / rows
theta_y = np.linspace(-pi/2 + ystep/2, pi/2 - ystep/2, rows, dtype='float32')
cos_y = np.cos(theta_y).reshape(rows,1)
sin_y = np.sin(theta_y).reshape(rows,1)
# Calculate X, Y, and Z coordinates for each output pixel.
x = cos_y * cos_x
y = sin_y * np.ones((1,cols), dtype='float32')
z = cos_y * sin_x
# Vectorize the coordinates in raster order.
xyz = np.matrix([x.ravel(), y.ravel(), z.ravel()])
return [xyz, rows, cols]
# Convert all lens parameters to a state vector. See also: optimize()
示例13: create_iden_matrix
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import matrix [as 别名]
def create_iden_matrix(n):
"""
Create a dim1 * dim2 identity matrix.
Returns: the new matrix.
"""
matrix_init = [[] for i in range(n)]
for i in range(0, n):
for j in range(0, n):
if i == j:
matrix_init[i].append(1)
else:
matrix_init[i].append(0)
return np.matrix(matrix_init)
示例14: state_vector
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import matrix [as 别名]
def state_vector(vlen, init_state):
vals = ""
for i in range(vlen):
if i == init_state:
vals = vals + "1 "
else:
vals = vals + "0 "
return np.matrix(vals)
示例15: from_matrix
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import matrix [as 别名]
def from_matrix(m):
"""
Takes an numpy matrix and returns a prehension.
"""
pre = MarkovPre("")
pre.matrix = m
return pre