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)
vert_gradients = layers_lib.conv2d_in_plane(
tf_image,
weights_initializer=init_ops.constant_initializer([1, -1]),
kernel_size=[2, 1],
padding='VALID',
activation_fn=None)
init_op = variables_lib.global_variables_initializer()
with self.test_session() as sess:
sess.run(init_op)
result = sess.run(vert_gradients)
self.assertAllClose(result, expected, rtol=1e-5, atol=1e-5)
python类asmatrix()的实例源码
layers_test.py 文件源码
项目:DeepLearning_VirtualReality_BigData_Project
作者: rashmitripathi
项目源码
文件源码
阅读 32
收藏 0
点赞 0
评论 0
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
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)
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]])
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]])
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)
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.
See Also
--------
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))
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, ())
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])
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]])
def test_scalar_indexing(self):
x = asmatrix(np.zeros((3, 2), float))
assert_equal(x[0, 0], x[0][0])
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]])
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,:])
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
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
LSFIR.py 文件源码
项目:Least-Squared-Error-Based-FIR-Filters
作者: fourier-being
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
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
LSFIR.py 文件源码
项目:Least-Squared-Error-Based-FIR-Filters
作者: fourier-being
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
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
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
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
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())