Created
July 11, 2017 07:37
-
-
Save reox/fb8c820c7bf01be2e03169d03de7b853 to your computer and use it in GitHub Desktop.
Linear Algebra with scipy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from itertools import combinations | |
import scipy.linalg | |
x = [1.2, 1.3, 1.6, 2.5, 2.3, 2.8] | |
y = [167.0, 180.3, 177.8, 160.4, 179.6, 154.3] | |
z = [-0.3, -0.8, -0.75, -1.21, -1.65, -0.68] | |
f = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6]).transpose() | |
G = np.c_[x, y, z] | |
A = np.concatenate((G, np.ones((G.shape[0],1))), axis=1) | |
C, _, _, _ = scipy.linalg.lstsq(A, f) | |
# C will have now the coefficients for: | |
# f(x, y, z) = ax + by + cz + d | |
def linear(x, y, z): | |
return C[0] * x + C[1] * y + C[2] * z + C[3] | |
# quadratic eq. | |
dim = G.shape[1] | |
A = np.concatenate((G**2, np.array([np.prod(G[:, k], axis=1) for k in combinations(range(dim), dim-1)]).transpose(), G, np.ones((G.shape[0], 1))), axis=1) | |
D, _, _, _ = scipy.linalg.lstsq(A, f) | |
# C will have now the coefficients for: | |
# f(x, y, z) = ax**2 + by**2 + cz**2 + dxy+ exz + fyz + gx + hy + iz + j | |
def quadratic(a): | |
# a is for example a numpy.array([x, y, z]) | |
dim = a.shape[0] | |
A = np.concatenate((a**2, np.array([np.prod(a[k,]) for k in combinations(range(dim), dim-1)]), a, [1])) | |
return np.sum(np.dot(A, D)) | |
for i in range(G.shape[0]): | |
print(quadratic(G[i,:]), f[i]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment