2012-04-13 3 views
0

나는 많은 수의 다른 데이터 세트에 모두 같은 수의 점을 맞추기를 원한다. 예를 들어, 이미지의 모든 행에 다항식을 맞출 수 있습니다. scipy 나 다른 패키지를 사용하여 효율적이고 벡터화 된 방법이 있습니까? 아니면 단일 루프를 사용해야합니까 (아니면 속도를 높이기 위해 다중 처리를 사용해야합니까?).파이썬에서 N 개의 데이터 세트에 동시에 맞추기

답변

0

당신은 numpy.linalg.lstsq 사용할 수 있습니다

import numpy as np 

# independent variable 
x = np.arange(100) 

# some sample outputs with random noise 
y1 = 3*x**2 + 2*x + 4 + np.random.randn(100) 
y2 = x**2 - 4*x + 10 + np.random.randn(100) 

# coefficient matrix, where each column corresponds to a term in your function 
# this one is simple quadratic polynomial: 1, x, x**2 
a = np.vstack((np.ones(100), x, x**2)).T 

# result matrix, where each column is one set of outputs 
b = np.vstack((y1, y2)).T 

solutions, residuals, rank, s = np.linalg.lstsq(a, b) 

# each column in solutions is the coefficients of terms 
# for the corresponding output 
for i, solution in enumerate(zip(*solutions),1): 
    print "y%d = %.1f + (%.1f)x + (%.1f)x^2" % ((i,) + solution) 


# outputs: 
# y1 = 4.4 + (2.0)x + (3.0)x^2 
# y2 = 9.8 + (-4.0)x + (1.0)x^2 
+0

감사합니다! 이 방법은 다항식에서만 작동합니까, 아니면 임의의 함수와 함께 사용할 수 있습니까? – astrofrog

+0

@astrofrog : 모든 기능을 넣을 수 있습니다. 예 : 'a = np.vstack ((np.exp (x), x)) .''는'A * e^x + B * x'에 맞추려고합니다. 그에 따라 열을 구성하면됩니다. – Avaris

관련 문제