本文整理汇总了Python中numpy.linalg.lstsq方法的典型用法代码示例。如果您正苦于以下问题:Python linalg.lstsq方法的具体用法?Python linalg.lstsq怎么用?Python linalg.lstsq使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy.linalg
的用法示例。
在下文中一共展示了linalg.lstsq方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_future_rcond
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import lstsq [as 别名]
def test_future_rcond(self):
a = np.array([[0., 1., 0., 1., 2., 0.],
[0., 2., 0., 0., 1., 0.],
[1., 0., 1., 0., 0., 4.],
[0., 0., 0., 2., 3., 0.]]).T
b = np.array([1, 0, 0, 0, 0, 0])
with suppress_warnings() as sup:
w = sup.record(FutureWarning, "`rcond` parameter will change")
x, residuals, rank, s = linalg.lstsq(a, b)
assert_(rank == 4)
x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
assert_(rank == 4)
x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
assert_(rank == 3)
# Warning should be raised exactly once (first command)
assert_(len(w) == 1)
示例2: do
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import lstsq [as 别名]
def do(self, a, b):
arr = np.asarray(a)
m, n = arr.shape
u, s, vt = linalg.svd(a, 0)
x, residuals, rank, sv = linalg.lstsq(a, b)
if m <= n:
assert_almost_equal(b, dot(a, x))
assert_equal(rank, m)
else:
assert_equal(rank, n)
assert_almost_equal(sv, sv.__array_wrap__(s))
if rank == n and m > n:
expect_resids = (
np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
expect_resids = np.asarray(expect_resids)
if len(np.asarray(b).shape) == 1:
expect_resids.shape = (1,)
assert_equal(residuals.shape, expect_resids.shape)
else:
expect_resids = np.array([]).view(type(x))
assert_almost_equal(residuals, expect_resids)
assert_(np.issubdtype(residuals.dtype, np.floating))
assert_(imply(isinstance(b, matrix), isinstance(x, matrix)))
assert_(imply(isinstance(b, matrix), isinstance(residuals, matrix)))
示例3: do
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import lstsq [as 别名]
def do(self, a, b):
arr = np.asarray(a)
m, n = arr.shape
u, s, vt = linalg.svd(a, 0)
x, residuals, rank, sv = linalg.lstsq(a, b)
if m <= n:
assert_almost_equal(b, dot(a, x))
assert_equal(rank, m)
else:
assert_equal(rank, n)
assert_almost_equal(sv, sv.__array_wrap__(s))
if rank == n and m > n:
expect_resids = (np.asarray(abs(np.dot(a, x) - b))**2).sum(axis=0)
expect_resids = np.asarray(expect_resids)
if len(np.asarray(b).shape) == 1:
expect_resids.shape = (1,)
assert_equal(residuals.shape, expect_resids.shape)
else:
expect_resids = type(x)([])
assert_almost_equal(residuals, expect_resids)
assert_(np.issubdtype(residuals.dtype, np.floating))
assert_(imply(isinstance(b, matrix), isinstance(x, matrix)))
assert_(imply(isinstance(b, matrix), isinstance(residuals, matrix)))
示例4: solve_lms
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import lstsq [as 别名]
def solve_lms(all_tags, all_bits, segdata, bias=0.0):
"""
Solves using direct least square solution (NumPy)
Parameters
----------
all_tags:
List of considered tags.
all_bits:
List of considered bits.
segdata:
List of segdata used.
bias:
T.B.D.
"""
# Build matrices
A, B = build_matrices(all_tags, all_bits, segdata, bias)
# Solve
X, res, r, s = linalg.lstsq(A, B, rcond=None)
return X, compute_error(A, B, X)
示例5: _compute_affine_transform_cvpy
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import lstsq [as 别名]
def _compute_affine_transform_cvpy(refpoints, points, w = None): # Copied from the book
if w == None:
w = [1] * (len(points) * 2)
assert(len(w) == 2*len(points))
y = []
for n, p in enumerate(refpoints):
y += [p[0]/w[n*2], p[1]/w[n*2+1]]
A = []
for n, p in enumerate(points):
A.extend([ [p[0]/w[n*2], p[1]/w[n*2], 0, 0, 1/w[n*2], 0], [0, 0, p[0]/w[n*2+1], p[1]/w[n*2+1], 0, 1/w[n*2+1]] ])
lstsq = linalg.lstsq(A,y)
h11, h12, h21, h22, dx, dy = lstsq[0]
err = lstsq[1]
R = np.array([[h11, h12, dx], [h21, h22, dy]])
return R, err
示例6: _compute_affine_transform_ocvlsq
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import lstsq [as 别名]
def _compute_affine_transform_ocvlsq(refpoints, points, w = None):
if w == None:
w = [1] * (len(points) * 2)
assert(len(w) == 2*len(points))
y = []
for n, p in enumerate(refpoints):
y += [p[0]/w[n*2], p[1]/w[n*2+1]]
A = []
for n, p in enumerate(points):
A.extend([ [p[0]/w[n*2], p[1]/w[n*2], 0, 0, 1/w[n*2], 0], [0, 0, p[0]/w[n*2+1], p[1]/w[n*2+1], 0, 1/w[n*2+1]] ])
lstsq = cv2.solve(np.array(A), np.array(y), flags=cv2.DECOMP_SVD)
h11, h12, h21, h22, dx, dy = lstsq[1]
err = 0#lstsq[1]
#R = np.array([[h11, h12, dx], [h21, h22, dy]])
# The row above works too - but creates a redundant dimension
R = np.array([[h11[0], h12[0], dx[0]], [h21[0], h22[0], dy[0]]])
return R, err
示例7: sigmoid_adjust
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import lstsq [as 别名]
def sigmoid_adjust(xs, ys):
ys_max = np.max(ys) + 0.1
ys_min = np.min(ys) - 0.1
# normalize to [0, 1]
ys = list((np.array(ys) - ys_min) / (ys_max - ys_min))
zs = -np.log(1.0 / np.array(ys).T - 1.0)
Y_mtx = np.matrix((np.ones(len(ys)), zs)).T
x_vec = np.matrix(xs).T
a_b = lstsq(Y_mtx, x_vec, rcond=1)[0]
a = a_b.item(0)
b = a_b.item(1)
xs = 1.0 / (1.0 + np.exp(- (np.array(xs) - a) / b))
# denormalize
xs = xs * (ys_max - ys_min) + ys_min
return xs
示例8: hfd
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import lstsq [as 别名]
def hfd(X, Kmax):
""" Compute Hjorth Fractal Dimension of a time series X, kmax
is an HFD parameter
"""
L = [];
x = []
N = len(X)
for k in xrange(1,Kmax):
Lk = []
for m in xrange(0,k):
Lmk = 0
for i in xrange(1,int(floor((N-m)/k))):
Lmk += abs(X[m+i*k] - X[m+i*k-k])
Lmk = Lmk*(N - 1)/floor((N - m) / float(k)) / k
Lk.append(Lmk)
L.append(log(mean(Lk)))
x.append([log(float(1) / k), 1])
(p, r1, r2, s)=lstsq(x, L)
return p[0]
示例9: do
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import lstsq [as 别名]
def do(self, a, b):
arr = np.asarray(a)
m, n = arr.shape
u, s, vt = linalg.svd(a, 0)
x, residuals, rank, sv = linalg.lstsq(a, b)
if m <= n:
assert_almost_equal(b, dot(a, x))
assert_equal(rank, m)
else:
assert_equal(rank, n)
assert_almost_equal(sv, sv.__array_wrap__(s))
if rank == n and m > n:
expect_resids = (np.asarray(abs(np.dot(a, x) - b))**2).sum(axis=0)
expect_resids = np.asarray(expect_resids)
if len(np.asarray(b).shape) == 1:
expect_resids.shape = (1,)
assert_equal(residuals.shape, expect_resids.shape)
else:
expect_resids = np.array([]).view(type(x))
assert_almost_equal(residuals, expect_resids)
assert_(np.issubdtype(residuals.dtype, np.floating))
assert_(imply(isinstance(b, matrix), isinstance(x, matrix)))
assert_(imply(isinstance(b, matrix), isinstance(residuals, matrix)))
示例10: error
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import lstsq [as 别名]
def error(self, start, end):
"""Return the approximation cost on the segment [start:end].
Args:
start (int): start of the segment
end (int): end of the segment
Returns:
float: segment cost
Raises:
NotEnoughPoints: when the segment is too short (less than ``'min_size'`` samples).
"""
if end - start < self.min_size:
raise NotEnoughPoints
y, X = self.signal[start:end], self.covar[start:end]
_, residual, _, _ = lstsq(X, y, rcond=None)
return residual.sum()
示例11: do
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import lstsq [as 别名]
def do(self, a, b, tags):
arr = np.asarray(a)
m, n = arr.shape
u, s, vt = linalg.svd(a, 0)
x, residuals, rank, sv = linalg.lstsq(a, b, rcond=-1)
if m == 0:
assert_((x == 0).all())
if m <= n:
assert_almost_equal(b, dot(a, x))
assert_equal(rank, m)
else:
assert_equal(rank, n)
assert_almost_equal(sv, sv.__array_wrap__(s))
if rank == n and m > n:
expect_resids = (
np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
expect_resids = np.asarray(expect_resids)
if np.asarray(b).ndim == 1:
expect_resids.shape = (1,)
assert_equal(residuals.shape, expect_resids.shape)
else:
expect_resids = np.array([]).view(type(x))
assert_almost_equal(residuals, expect_resids)
assert_(np.issubdtype(residuals.dtype, np.floating))
assert_(consistent_subclass(x, b))
assert_(consistent_subclass(residuals, b))
示例12: test_empty_a_b
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import lstsq [as 别名]
def test_empty_a_b(self, m, n, n_rhs):
a = np.arange(m * n).reshape(m, n)
b = np.ones((m, n_rhs))
x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
if m == 0:
assert_((x == 0).all())
assert_equal(x.shape, (n, n_rhs))
assert_equal(residuals.shape, ((n_rhs,) if m > n else (0,)))
if m > n and n_rhs > 0:
# residuals are exactly the squared norms of b's columns
r = b - np.dot(a, x)
assert_almost_equal(residuals, (r * r).sum(axis=-2))
assert_equal(rank, min(m, n))
assert_equal(s.shape, (min(m, n),))
示例13: test_incompatible_dims
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import lstsq [as 别名]
def test_incompatible_dims(self):
# use modified version of docstring example
x = np.array([0, 1, 2, 3])
y = np.array([-1, 0.2, 0.9, 2.1, 3.3])
A = np.vstack([x, np.ones(len(x))]).T
with assert_raises_regex(LinAlgError, "Incompatible dimensions"):
linalg.lstsq(A, y, rcond=None)
示例14: test_lstsq_complex_larger_rhs
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import lstsq [as 别名]
def test_lstsq_complex_larger_rhs(self):
# gh-9891
size = 20
n_rhs = 70
G = np.random.randn(size, size) + 1j * np.random.randn(size, size)
u = np.random.randn(size, n_rhs) + 1j * np.random.randn(size, n_rhs)
b = G.dot(u)
# This should work without segmentation fault.
u_lstsq, res, rank, sv = linalg.lstsq(G, b, rcond=None)
# check results just in case
assert_array_almost_equal(u_lstsq, u)
示例15: CovarianceMaatrixAdaptionEvolutionStrategyF
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import lstsq [as 别名]
def CovarianceMaatrixAdaptionEvolutionStrategyF(task, epsilon=1e-20, rnd=rand):
lam, alpha_mu, hs, sigma0 = (4 + round(3 * log(task.D))) * 10, 2, 0, 0.3 * task.bcRange()
mu = int(round(lam / 2))
w = log(mu + 0.5) - log(range(1, mu + 1))
w = w / sum(w)
mueff = 1 / sum(w ** 2)
cs = (mueff + 2) / (task.D + mueff + 5)
ds = 1 + cs + 2 * max(sqrt((mueff - 1) / (task.D + 1)) - 1, 0)
ENN = sqrt(task.D) * (1 - 1 / (4 * task.D) + 1 / (21 * task.D ** 2))
cc, c1 = (4 + mueff / task.D) / (4 + task.D + 2 * mueff / task.D), 2 / ((task.D + 1.3) ** 2 + mueff)
cmu, hth = min(1 - c1, alpha_mu * (mueff - 2 + 1 / mueff) / ((task.D + 2) ** 2 + alpha_mu * mueff / 2)), (1.4 + 2 / (task.D + 1)) * ENN
ps, pc, C, sigma, M = full(task.D, 0.0), full(task.D, 0.0), eye(task.D), sigma0, full(task.D, 0.0)
x = rnd.uniform(task.bcLower(), task.bcUpper())
x_f = task.eval(x)
while not task.stopCondI():
pop_step = asarray([rnd.multivariate_normal(full(task.D, 0.0), C) for _ in range(int(lam))])
pop = asarray([task.repair(x + sigma * ps, rnd) for ps in pop_step])
pop_f = apply_along_axis(task.eval, 1, pop)
isort = argsort(pop_f)
pop, pop_f, pop_step = pop[isort[:mu]], pop_f[isort[:mu]], pop_step[isort[:mu]]
if pop_f[0] < x_f: x, x_f = pop[0], pop_f[0]
M = sum(w * pop_step.T, axis=1)
ps = solve(chol(C).conj() + epsilon, ((1 - cs) * ps + sqrt(cs * (2 - cs) * mueff) * M + epsilon).T)[0].T
sigma *= exp(cs / ds * (norm(ps) / ENN - 1)) ** 0.3
ifix = where(sigma == inf)
if any(ifix): sigma[ifix] = sigma0
if norm(ps) / sqrt(1 - (1 - cs) ** (2 * (task.Iters + 1))) < hth: hs = 1
else: hs = 0
delta = (1 - hs) * cc * (2 - cc)
pc = (1 - cc) * pc + hs * sqrt(cc * (2 - cc) * mueff) * M
C = (1 - c1 - cmu) * C + c1 * (tile(pc, [len(pc), 1]) * tile(pc.reshape([len(pc), 1]), [1, len(pc)]) + delta * C)
for i in range(mu): C += cmu * w[i] * tile(pop_step[i], [len(pop_step[i]), 1]) * tile(pop_step[i].reshape([len(pop_step[i]), 1]), [1, len(pop_step[i])])
E, V = eig(C)
if any(E < epsilon):
E = fmax(E, 0)
C = lstsq(V.T, dot(V, diag(E)).T, rcond=None)[0].T
return x, x_f