Python kódok¶

Hasznos lehet több kód futtatása esetén mindegyik előtt újraindítani a kernelt (menü: Kernel -> Restart, vagy Kernel -> Restart & Clear Output). A kódok néhol különbözhetnek a könyvbeliektől és olyan sorokat is tartalmazhatnak, melyek nem fértek be a könyvbe.

1.19. Lista elemeinek összege, ha a lista üres¶

In [1]:
l = [1, 2, 3]
sum = 0
for i in l:
    sum += i
print(sum)
6
In [2]:
l = []
sum = 0
for i in l:
    sum += i
print(sum)
0
In [3]:
l = set()
sum = 0
for i in l:
    sum += i
print(sum)
0

1.37. Vektorok skalár- és vektori szoztata¶

In [4]:
import numpy as np
In [5]:
a = [2, 3, 6]
b = [3, -6, 2]
c = [1, 0, 1]
In [6]:
# listákkal definiált vektorok is szorozhatók
np.dot(a, b)
Out[6]:
0
In [7]:
# 1-D tömbként definiált vektorok is szorozhatók
A = np.array(a)
B = np.array(b)
np.dot(A, B)
Out[7]:
0
In [8]:
np.cross(a, b)
Out[8]:
array([ 42,  14, -21])
In [9]:
np.dot(_, c)
Out[9]:
21

1.41. Vektorok hossza és hajlásszöge¶

In [10]:
import numpy as np
import math
In [11]:
u = np.array([2, 3, 4, 14])
w = np.array([0, 3, 6, -2])
u, w
Out[11]:
(array([ 2,  3,  4, 14]), array([ 0,  3,  6, -2]))
In [12]:
nu = np.linalg.norm(u)
nw = np.linalg.norm(w)
nu, nw
Out[12]:
(15.0, 7.0)
In [13]:
d = np.dot(u, w)
d
Out[13]:
5
In [14]:
d/nu/nw
Out[14]:
0.047619047619047616
In [15]:
math.acos(_)
Out[15]:
1.5231592641704934

1.48. Korrelációs együttható¶

In [16]:
x = [1, 2, 3, 4, 5]
y = [3, 2, 4, 6, 5]
z = [5, 6, 4, 2, 3]
In [17]:
# 1. pearsonr
from scipy.stats import pearsonr
pearsonr(x, y)
r, _ = pearsonr(x, y)
r
Out[17]:
0.8
In [18]:
pearsonr(x, z)[0]
Out[18]:
-0.8
In [19]:
# 2. linregress
from scipy.stats import linregress
lr = linregress(x, y)
In [20]:
lr.rvalue
Out[20]:
0.8
In [21]:
lr # az csak véletlen, hogy a regressziós egyenes iránytangense (slope) is 0.8
Out[21]:
LinregressResult(slope=0.8, intercept=1.5999999999999996, rvalue=0.8, pvalue=0.10408803866182778, stderr=0.3464101615137754, intercept_stderr=1.1489125293076055)
In [22]:
linregress(x, z).rvalue
Out[22]:
-0.8
In [23]:
# 3. korrelációs mátrix
import numpy as np
xyz = np.array([x, y, z]) # egy tömbbe tesszük
xyz
Out[23]:
array([[1, 2, 3, 4, 5],
       [3, 2, 4, 6, 5],
       [5, 6, 4, 2, 3]])
In [24]:
np.corrcoef(xyz)
Out[24]:
array([[ 1. ,  0.8, -0.8],
       [ 0.8,  1. , -1. ],
       [-0.8, -1. ,  1. ]])

2.2. Redukált lépcsős alak (rref)¶

In [25]:
import sympy
a = sympy.Matrix([[2,1,1],[0,2,1],[0,4,2]])
a
Out[25]:
$\displaystyle \left[\begin{matrix}2 & 1 & 1\\0 & 2 & 1\\0 & 4 & 2\end{matrix}\right]$
In [26]:
a.rref() # a redukált lépcsős alak és a bázisoszlopok indexeinek listája
Out[26]:
(Matrix([
 [1, 0, 1/4],
 [0, 1, 1/2],
 [0, 0,   0]]),
 (0, 1))
In [27]:
# csak a mátrix
a.rref()[0]
Out[27]:
$\displaystyle \left[\begin{matrix}1 & 0 & \frac{1}{4}\\0 & 1 & \frac{1}{2}\\0 & 0 & 0\end{matrix}\right]$
In [28]:
# a bázisoszlopok indexei (a Python konvencióinak megfelelően az első oszlop indexe 0)
a.rref()[1]
Out[28]:
(0, 1)

2.21. Nulltér¶

A könyvben nem szerepel

In [29]:
import numpy as np
from scipy.linalg import null_space
a = np.array([[1,2,2,-1], [1,2,4,0], [3,6,2,-5]])
In [30]:
null_space(a)
Out[30]:
array([[-0.93665071, -0.02709652],
       [ 0.24090271,  0.67391469],
       [ 0.11371132, -0.33018321],
       [-0.22742264,  0.66036643]])
In [31]:
from sympy import *
A = Matrix(a)
A
Out[31]:
$\displaystyle \left[\begin{matrix}1 & 2 & 2 & -1\\1 & 2 & 4 & 0\\3 & 6 & 2 & -5\end{matrix}\right]$
In [32]:
A.nullspace()
Out[32]:
[Matrix([
 [-2],
 [ 1],
 [ 0],
 [ 0]]),
 Matrix([
 [   2],
 [   0],
 [-1/2],
 [   1]])]
In [33]:
A.nullspace()[0]
Out[33]:
$\displaystyle \left[\begin{matrix}-2\\1\\0\\0\end{matrix}\right]$
In [34]:
A.nullspace()[1]
Out[34]:
$\displaystyle \left[\begin{matrix}2\\0\\- \frac{1}{2}\\1\end{matrix}\right]$

3.3. Mátrix megadása¶

In [35]:
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 7]])
a
Out[35]:
array([[1, 2, 3],
       [4, 5, 7]])
In [36]:
# 0-tól indexelünk
a[0, 0]
Out[36]:
1
In [37]:
a[1, 2] 
Out[37]:
7
In [38]:
# utosló sor, utolsó oszlop eleme
a[-1, -1]
Out[38]:
7
In [39]:
a[1, :] # 2. sor, indexe 1, vektor
Out[39]:
array([4, 5, 7])
In [40]:
_.ndim # a vektor 1 dimenziós tömb
Out[40]:
0
In [41]:
a[:,0] # 1. oszlop, ez is vektor!
Out[41]:
array([1, 4])
In [42]:
_.ndim
Out[42]:
0
In [43]:
a[:, [0]] # az első oszlop, mint oszlopvektor 2 dimenziós tömb
Out[43]:
array([[1],
       [4]])
In [44]:
_.ndim # az oszlopvektor 2 dimenziós tömb
Out[44]:
0
In [45]:
a = np.diag([1, 2, 4]) # diagonális mátrix
a
Out[45]:
array([[1, 0, 0],
       [0, 2, 0],
       [0, 0, 4]])
In [46]:
print(a)
[[1 0 0]
 [0 2 0]
 [0 0 4]]

3.4. Mátrixszorzás¶

In [47]:
import numpy as np
A = np.array([[1, 1], [2, 1], [0, 3]])
B = np.array([[1, 1, 2], [2, 1, 0]])
A
Out[47]:
array([[1, 1],
       [2, 1],
       [0, 3]])
In [48]:
B
Out[48]:
array([[1, 1, 2],
       [2, 1, 0]])
In [49]:
A @ B
Out[49]:
array([[3, 2, 2],
       [4, 3, 4],
       [6, 3, 0]])

3.6. Blokkmátrix létrehozása¶

In [50]:
import numpy as np
A = np.array([1,0])
B = np.array([[1]])
C = np.array([[2,1],[0,3]])
D = np.array([[1],[1]])
np.block([[A,B],[C,D]])
Out[50]:
array([[1, 0, 1],
       [2, 1, 1],
       [0, 3, 1]])

3.7. Skalár vagy mátrix¶

In [51]:
import numpy as np
# Vektorok
u = np.array([1, 0, 2])
v = np.array([3, 2, 1])
u, v
Out[51]:
(array([1, 0, 2]), array([3, 2, 1]))
In [52]:
# 3x1-es mátrixok
U = np.array([[1, 0, 2]]).T
V = np.array([[3, 2, 1]]).T
U, V
Out[52]:
(array([[1],
        [0],
        [2]]),
 array([[3],
        [2],
        [1]]))
In [53]:
u @ v # skalárszorzat
Out[53]:
5
In [54]:
np.dot(u, v)
Out[54]:
5
In [55]:
U @ V.T #diadikus szorzat
Out[55]:
array([[3, 2, 1],
       [0, 0, 0],
       [6, 4, 2]])
In [56]:
U.T @ V # 1x1-es mátrix, azaz 2 dimenziós tömb
Out[56]:
array([[5]])
In [57]:
# skalárként kezeli a * művelettel
U.T @ V * np.diag([1, 1])
Out[57]:
array([[5, 0],
       [0, 5]])

3.8. Egységmátrix¶

In [58]:
import numpy as np
np.eye(2)
Out[58]:
array([[1., 0.],
       [0., 1.]])
In [59]:
np.diag([1, 1])
Out[59]:
array([[1, 0],
       [0, 1]])
In [60]:
np.identity(2)
Out[60]:
array([[1., 0.],
       [0., 1.]])
In [61]:
np.eye(2, 3)
Out[61]:
array([[1., 0., 0.],
       [0., 1., 0.]])
In [62]:
# a főátló fölött 1-gyel
np.eye(3, 3, 1, dtype='int')
Out[62]:
array([[0, 1, 0],
       [0, 0, 1],
       [0, 0, 0]])
In [63]:
# a főátló alatt 2-vel
np.eye(4, 4, -2, dtype='int')
Out[63]:
array([[0, 0, 0, 0],
       [0, 0, 0, 0],
       [1, 0, 0, 0],
       [0, 1, 0, 0]])

3.9. Elemi mátrixok¶

In [64]:
import numpy as np
# a 0 és 2 indexű sorok cseréje (S_1 <-> S_3)
A = np.eye(3)
A[(0,2),:] = A[(2,0),:]
A
Out[64]:
array([[0., 0., 1.],
       [0., 1., 0.],
       [1., 0., 0.]])
In [65]:
# a második sor beszorzása 5-tel (5*S_2)
B = np.eye(3)
B[1,:] = 5*B[1,:]
B
Out[65]:
array([[1., 0., 0.],
       [0., 5., 0.],
       [0., 0., 1.]])
In [66]:
# a harmadik sor 2-szeresének hozzáadása az első sorhoz (S_1 + 2*S_3)
C = np.eye(3)
C[0,:] += 2*C[2,:]
C
Out[66]:
array([[1., 0., 2.],
       [0., 1., 0.],
       [0., 0., 1.]])

3.10. vec függvény és Kronecker-szorzat¶

In [67]:
import numpy as np
A=np.array([[1, 2], [3, 4]])
A
Out[67]:
array([[1, 2],
       [3, 4]])
In [68]:
# A vec-függvény a Fortran-sorrendű reshape
# "F" = Fortran sorrend
# ha a sorok száma -1, akkor kiszámolja a sorok valódi számát, ami most 4
A.reshape((-1, 1), order="F")
Out[68]:
array([[1],
       [3],
       [2],
       [4]])
In [69]:
# a sorok száma 4, az oszlopok száma 1
_.shape
Out[69]:
()
In [70]:
B=np.array([[1, 0], [2, 1]])
B
Out[70]:
array([[1, 0],
       [2, 1]])
In [71]:
np.kron(A, B)
Out[71]:
array([[1, 0, 2, 0],
       [2, 1, 4, 2],
       [3, 0, 4, 0],
       [6, 3, 8, 4]])

3.11. Sylvester-egyenlet megoldása¶

In [72]:
import numpy as np
from scipy.linalg import solve_sylvester
A=np.array([[0, 1], [1, 0]])
B=np.array([[1, 1], [0, 2]])
C=np.array([[3, 7], [3, 5]])
solve_sylvester(A, B, C)
Out[72]:
array([[1.5, 2.5],
       [1.5, 0.5]])

3.23. PLU-felbontás¶

In [73]:
import numpy as np
from scipy.linalg import lu
a = np.array(
    [[-1, 6, 1,-7, 4],
     [ 1, 4, 4,-7, 5],
     [ 4,-8, 4, 8,-4],
     [ 3,-6, 8, 6,-8]])
p, l, u = lu(a)
# a == p @ l @ u
print(p)
print(l)
print(u)
[[0. 0. 0. 1.]
 [0. 1. 0. 0.]
 [1. 0. 0. 0.]
 [0. 0. 1. 0.]]
[[ 1.          0.          0.          0.        ]
 [ 0.25        1.          0.          0.        ]
 [ 0.75        0.          1.          0.        ]
 [-0.25        0.66666667  0.          1.        ]]
[[ 4. -8.  4.  8. -4.]
 [ 0.  6.  3. -9.  6.]
 [ 0.  0.  5.  0. -5.]
 [ 0.  0.  0.  1. -1.]]
In [74]:
a == p @ l @ u
Out[74]:
array([[ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True]])
In [75]:
# nem lebegőpontos számolás
# itt A == P.T @ L @ U
from sympy import Matrix, eye
In [76]:
#konverzió numpy -> sympy
A = Matrix(a)
A
Out[76]:
$\displaystyle \left[\begin{matrix}-1 & 6 & 1 & -7 & 4\\1 & 4 & 4 & -7 & 5\\4 & -8 & 4 & 8 & -4\\3 & -6 & 8 & 6 & -8\end{matrix}\right]$
In [77]:
L, U, p = A.LUdecomposition()
L
Out[77]:
$\displaystyle \left[\begin{matrix}1 & 0 & 0 & 0\\-1 & 1 & 0 & 0\\-3 & \frac{6}{5} & 1 & 0\\-4 & \frac{8}{5} & 0 & 1\end{matrix}\right]$
In [78]:
U
Out[78]:
$\displaystyle \left[\begin{matrix}-1 & 6 & 1 & -7 & 4\\0 & 10 & 5 & -14 & 9\\0 & 0 & 5 & \frac{9}{5} & - \frac{34}{5}\\0 & 0 & 0 & \frac{12}{5} & - \frac{12}{5}\end{matrix}\right]$
In [79]:
p  # a sorcserék párjai
Out[79]:
[[2, 3]]
In [80]:
# a permutáló mátrix konstrukciója a sorcserékből
I = eye(A.rows)
In [81]:
P = I.permuteFwd(p)
P # permutálómátrix p-ből
Out[81]:
$\displaystyle \left[\begin{matrix}1 & 0 & 0 & 0\\0 & 1 & 0 & 0\\0 & 0 & 0 & 1\\0 & 0 & 1 & 0\end{matrix}\right]$
In [82]:
P.T @ L @ U
Out[82]:
$\displaystyle \left[\begin{matrix}-1 & 6 & 1 & -7 & 4\\1 & 4 & 4 & -7 & 5\\4 & -8 & 4 & 8 & -4\\3 & -6 & 8 & 6 & -8\end{matrix}\right]$
In [83]:
_ == A
Out[83]:
False

Miéert kaptunk az előzőtől különböző P, L, U mátrixokat?

Itt szükségtelen a legnagyobb abszolút értékű elemmel eliminálni, mert a számításaink pontosak. Elég csak akkor sort cserélni, ha a főátlóban megjelenik egy 0, de alatta van nemnulla elem, mert azt másként nem tudnánk eliminálni.

4.7. Determináns kiszámítása¶

In [84]:
import numpy as np
a = np.array(
    [[2, 2, -3],
     [2, 2, -4],
     [4, 5, -6]])
a
Out[84]:
array([[ 2,  2, -3],
       [ 2,  2, -4],
       [ 4,  5, -6]])
In [85]:
np.linalg.det(a)
Out[85]:
2.0
In [86]:
from sympy import *
x, y = symbols('x, y')
In [87]:
A = Matrix([x, y, -y, x]).reshape(2, 2)
A
Out[87]:
$\displaystyle \left[\begin{matrix}x & y\\- y & x\end{matrix}\right]$
In [88]:
A.det()
Out[88]:
$\displaystyle x^{2} + y^{2}$
In [89]:
det(A)
Out[89]:
$\displaystyle x^{2} + y^{2}$

4.14. Vandermonde-determináns¶

In [90]:
import numpy as np
x = np.array([2, 3, 4])
V = np.vander(x)
V
Out[90]:
array([[ 4,  2,  1],
       [ 9,  3,  1],
       [16,  4,  1]])
In [91]:
np.linalg.det(V)
Out[91]:
-2.0
In [92]:
# egyesek az első oszlopban
np.fliplr(V) # flip left -> right
Out[92]:
array([[ 1,  2,  4],
       [ 1,  3,  9],
       [ 1,  4, 16]])
In [93]:
# egyesek az első sorban
np.fliplr(V).T
Out[93]:
array([[ 1,  1,  1],
       [ 2,  3,  4],
       [ 4,  9, 16]])

5.9. Forgatás térben¶

In [94]:
from sympy import *
x, y, z = symbols('x y z')
A = Matrix(
    [[cos(x), -sin(x), 0],
     [sin(x), cos(x), 0],
     [0, 0, 1]])
A
Out[94]:
$\displaystyle \left[\begin{matrix}\cos{\left(x \right)} & - \sin{\left(x \right)} & 0\\\sin{\left(x \right)} & \cos{\left(x \right)} & 0\\0 & 0 & 1\end{matrix}\right]$
In [95]:
B = A.subs(x, pi/3)
B
Out[95]:
$\displaystyle \left[\begin{matrix}\frac{1}{2} & - \frac{\sqrt{3}}{2} & 0\\\frac{\sqrt{3}}{2} & \frac{1}{2} & 0\\0 & 0 & 1\end{matrix}\right]$
In [96]:
v = Matrix(3, 1, [1, 1, 2])
B * v
Out[96]:
$\displaystyle \left[\begin{matrix}\frac{1}{2} - \frac{\sqrt{3}}{2}\\\frac{1}{2} + \frac{\sqrt{3}}{2}\\2\end{matrix}\right]$

6.4. Sajátérték, sajátvektor 1¶

In [97]:
import numpy as np
a = np.array(
    [[0, 1, 1],
     [0, 2, 0],
     [0, 0, 2]])
c, l = np.linalg.eig(a)
c
Out[97]:
array([0., 2., 2.])
In [98]:
l
Out[98]:
array([[1.        , 0.4472136 , 0.4472136 ],
       [0.        , 0.89442719, 0.        ],
       [0.        , 0.        , 0.89442719]])
In [99]:
# szimbolikus csomaggal:
import sympy as sp
A = sp.Matrix(a)
A
Out[99]:
$\displaystyle \left[\begin{matrix}0 & 1 & 1\\0 & 2 & 0\\0 & 0 & 2\end{matrix}\right]$
In [100]:
# {saj.ért.: multipl.}
A.eigenvals()
Out[100]:
{2: 2, 0: 1}
In [101]:
A.eigenvects()
Out[101]:
[(0,
  1,
  [Matrix([
   [1],
   [0],
   [0]])]),
 (2,
  2,
  [Matrix([
   [1/2],
   [  1],
   [  0]]),
   Matrix([
   [1/2],
   [  0],
   [  1]])])]
In [102]:
len(_)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[102], line 1
----> 1 len(_)

TypeError: object of type 'numpy.float64' has no len()
In [103]:
# a 0-hoz tartozó sajátvektor
A.eigenvects()[0][2][0]
Out[103]:
$\displaystyle \left[\begin{matrix}1\\0\\0\end{matrix}\right]$
In [104]:
# a 2-höz tartozó sajátalteret kifeszítő
# első sajátvektor
A.eigenvects()[1][2][0]
Out[104]:
$\displaystyle \left[\begin{matrix}\frac{1}{2}\\1\\0\end{matrix}\right]$
In [105]:
# a 2-höz tartozó sajátalteret kifeszítő
# második sajátvektor
A.eigenvects()[1][2][1]
Out[105]:
$\displaystyle \left[\begin{matrix}\frac{1}{2}\\0\\1\end{matrix}\right]$

6.7. Sajátérték, sajátvektor 2¶

In [106]:
from sympy import *
a = Rational(1,2) * Matrix(
    [[1, -sqrt(3)],
     [sqrt(3), 1]])
In [107]:
# sajátérték: multiplicitással
a.eigenvals()
Out[107]:
{1/2 - sqrt(3)*I/2: 1, 1/2 + sqrt(3)*I/2: 1}
In [108]:
# sajátértékek listája
list(a.eigenvals())
Out[108]:
[1/2 - sqrt(3)*I/2, 1/2 + sqrt(3)*I/2]
In [109]:
list(a.eigenvals())[0]
Out[109]:
$\displaystyle \frac{1}{2} - \frac{\sqrt{3} i}{2}$
In [110]:
list(a.eigenvals())[1]
Out[110]:
$\displaystyle \frac{1}{2} + \frac{\sqrt{3} i}{2}$
In [111]:
# sajátvektorok
v = a.eigenvects()
In [112]:
v
Out[112]:
[(1/2 - sqrt(3)*I/2,
  1,
  [Matrix([
   [-sqrt(3)/3 + 2*sqrt(3)*(1/2 - sqrt(3)*I/2)/3],
   [                                           1]])]),
 (1/2 + sqrt(3)*I/2,
  1,
  [Matrix([
   [-sqrt(3)/3 + 2*sqrt(3)*(1/2 + sqrt(3)*I/2)/3],
   [                                           1]])])]
In [113]:
v[0][2][0].simplify()
v[0][2][0]
Out[113]:
$\displaystyle \left[\begin{matrix}- i\\1\end{matrix}\right]$
In [114]:
v[1][2][0].simplify()
v[1][2][0]
Out[114]:
$\displaystyle \left[\begin{matrix}i\\1\end{matrix}\right]$

6.15. Jordan-láncok, Jordan-felbontás (1 Jordan-lánc)¶

In [115]:
from sympy import *
A = Matrix(3, 3, 
   [6, -1, -3,
    -1, 5, 2,
    2, -1, 1])
A
Out[115]:
$\displaystyle \left[\begin{matrix}6 & -1 & -3\\-1 & 5 & 2\\2 & -1 & 1\end{matrix}\right]$
In [116]:
A.eigenvects()
Out[116]:
[(4,
  3,
  [Matrix([
   [ 1],
   [-1],
   [ 1]])])]
In [117]:
A.jordan_form()
Out[117]:
(Matrix([
 [-1,  2, 1],
 [ 1, -1, 0],
 [-1,  2, 0]]),
 Matrix([
 [4, 1, 0],
 [0, 4, 1],
 [0, 0, 4]]))
In [118]:
A.jordan_form()[0]
Out[118]:
$\displaystyle \left[\begin{matrix}-1 & 2 & 1\\1 & -1 & 0\\-1 & 2 & 0\end{matrix}\right]$
In [119]:
A.jordan_form()[1]
Out[119]:
$\displaystyle \left[\begin{matrix}4 & 1 & 0\\0 & 4 & 1\\0 & 0 & 4\end{matrix}\right]$

6.16. Jordan-láncok, Jordan-felbontás (2 Jordan-lánc)¶

In [120]:
from sympy import *
A = Matrix(3, 3, 
           [2, -3, 2, 
            4, 10, -4, 
            4, 6, 0])
A
Out[120]:
$\displaystyle \left[\begin{matrix}2 & -3 & 2\\4 & 10 & -4\\4 & 6 & 0\end{matrix}\right]$
In [121]:
A.eigenvects()
Out[121]:
[(4,
  3,
  [Matrix([
   [-3/2],
   [   1],
   [   0]]),
   Matrix([
   [1],
   [0],
   [1]])])]
In [122]:
A.jordan_form()
Out[122]:
(Matrix([
 [-2, 1, -3/2],
 [ 4, 0,    1],
 [ 4, 0,    0]]),
 Matrix([
 [4, 1, 0],
 [0, 4, 0],
 [0, 0, 4]]))
In [123]:
A.jordan_form()[0]
Out[123]:
$\displaystyle \left[\begin{matrix}-2 & 1 & - \frac{3}{2}\\4 & 0 & 1\\4 & 0 & 0\end{matrix}\right]$
In [124]:
A.jordan_form()[1]
Out[124]:
$\displaystyle \left[\begin{matrix}4 & 1 & 0\\0 & 4 & 0\\0 & 0 & 4\end{matrix}\right]$

7.7. Többváltozós lineáris regresszió¶

In [125]:
import numpy as np
from sklearn.linear_model import LinearRegression
x = np.array([[0, 0],[0, 1], [1, 0],[1, 1]])
x
Out[125]:
array([[0, 0],
       [0, 1],
       [1, 0],
       [1, 1]])
In [126]:
z = np.array([4, 0, 3, 3])
z
Out[126]:
array([4, 0, 3, 3])
In [127]:
lr = LinearRegression()
lr.fit(x,z)
Out[127]:
LinearRegression()
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
LinearRegression()
In [128]:
lr.coef_
Out[128]:
array([ 1., -2.])
In [129]:
lr.intercept_
Out[129]:
3.0

7.11. Pszeudoinverz¶

In [130]:
#numpy.linalg.pinv() függvény
import numpy as np
B = np.array(
    [[0, 1], 
     [1, 1], 
     [1, 0]])
In [131]:
Bplus = np.linalg.pinv(B)
print(Bplus)
[[-0.33333333  0.33333333  0.66666667]
 [ 0.66666667  0.33333333 -0.33333333]]
In [132]:
# sympy.pinv() metódus
import sympy as sy
B = sy.Matrix(B)
B
Out[132]:
$\displaystyle \left[\begin{matrix}0 & 1\\1 & 1\\1 & 0\end{matrix}\right]$
In [133]:
B.pinv()
Out[133]:
$\displaystyle \left[\begin{matrix}- \frac{1}{3} & \frac{1}{3} & \frac{2}{3}\\\frac{2}{3} & \frac{1}{3} & - \frac{1}{3}\end{matrix}\right]$
In [134]:
C = sy.Matrix(
    [[1, 0, 1], 
     [0, 1, 1]]) 
C
Out[134]:
$\displaystyle \left[\begin{matrix}1 & 0 & 1\\0 & 1 & 1\end{matrix}\right]$
In [135]:
C.pinv()
Out[135]:
$\displaystyle \left[\begin{matrix}\frac{2}{3} & - \frac{1}{3}\\- \frac{1}{3} & \frac{2}{3}\\\frac{1}{3} & \frac{1}{3}\end{matrix}\right]$
In [136]:
M = B @ C
M
Out[136]:
$\displaystyle \left[\begin{matrix}0 & 1 & 1\\1 & 1 & 2\\1 & 0 & 1\end{matrix}\right]$
In [137]:
M.pinv()
Out[137]:
$\displaystyle \left[\begin{matrix}- \frac{4}{9} & \frac{1}{9} & \frac{5}{9}\\\frac{5}{9} & \frac{1}{9} & - \frac{4}{9}\\\frac{1}{9} & \frac{2}{9} & \frac{1}{9}\end{matrix}\right]$

7.12. Optimális megoldás pszeudoinverzzel¶

In [138]:
import sympy as sy
A = sy.Matrix(
    [[0, 1, 1], 
     [1, 1, 2], 
     [1, 0, 1]])
A
Out[138]:
$\displaystyle \left[\begin{matrix}0 & 1 & 1\\1 & 1 & 2\\1 & 0 & 1\end{matrix}\right]$
In [139]:
b = sy.Matrix([3, 2, 2])
b
Out[139]:
$\displaystyle \left[\begin{matrix}3\\2\\2\end{matrix}\right]$
In [140]:
A.pinv_solve(b)
Out[140]:
$\displaystyle \left[\begin{matrix}\frac{w_{0 0}}{3} + \frac{w_{1 0}}{3} - \frac{w_{2 0}}{3}\\\frac{w_{0 0}}{3} + \frac{w_{1 0}}{3} - \frac{w_{2 0}}{3} + 1\\- \frac{w_{0 0}}{3} - \frac{w_{1 0}}{3} + \frac{w_{2 0}}{3} + 1\end{matrix}\right]$
In [141]:
# a sortérbe eső optimális megoldás
A.pinv_solve(b, arbitrary_matrix = sy.Matrix([0,0,0]))
Out[141]:
$\displaystyle \left[\begin{matrix}0\\1\\1\end{matrix}\right]$
In [142]:
# az összes optimális megoldás
t = sy.symbols("t")
A.pinv_solve(b, arbitrary_matrix = sy.Matrix([3*t,0,0]))
Out[142]:
$\displaystyle \left[\begin{matrix}t\\t + 1\\1 - t\end{matrix}\right]$

7.18. Gram–Schidt ortogonalizáció¶

In [143]:
import sympy as sy
b1 = sy.Matrix([3, 6, 2]); b1
Out[143]:
$\displaystyle \left[\begin{matrix}3\\6\\2\end{matrix}\right]$
In [144]:
b2 = sy.Matrix([1, 9,-4]); b2
Out[144]:
$\displaystyle \left[\begin{matrix}1\\9\\-4\end{matrix}\right]$
In [145]:
B = [b1, b2]
B
Out[145]:
[Matrix([
 [3],
 [6],
 [2]]),
 Matrix([
 [ 1],
 [ 9],
 [-4]])]
In [146]:
gs = sy.GramSchmidt(B)
sy.init_printing()         # a pprint függvényhez a grafikus outputhoz
for i in gs:
    sy.pprint(i, use_unicode=True)
⎡3⎤
⎢ ⎥
⎢6⎥
⎢ ⎥
⎣2⎦
⎡-2⎤
⎢  ⎥
⎢3 ⎥
⎢  ⎥
⎣-6⎦
In [147]:
GS = sy.GramSchmidt(B, True)
for i in GS: 
    sy.pprint(i, use_unicode=True)
⎡3/7⎤
⎢   ⎥
⎢6/7⎥
⎢   ⎥
⎣2/7⎦
⎡-2/7⎤
⎢    ⎥
⎢3/7 ⎥
⎢    ⎥
⎣-6/7⎦
In [148]:
gs[0].dot(gs[1])      # merőlegesek egymásra
Out[148]:
$\displaystyle 0$
In [149]:
GS[0].norm(), GS[1].norm()  # egységvektorok
Out[149]:
$\displaystyle \left( 1, \ 1\right)$

7.20. QR-felbontás¶

In [150]:
import sympy as sy
A = sy.Matrix(
    [[1, 3, 6],
     [1,-1, 2],
     [1, 3, 2],
     [1,-1,-2]])
A
Out[150]:
$\displaystyle \left[\begin{matrix}1 & 3 & 6\\1 & -1 & 2\\1 & 3 & 2\\1 & -1 & -2\end{matrix}\right]$
In [151]:
A.QRdecomposition()
Out[151]:
$\displaystyle \left( \left[\begin{matrix}\frac{1}{2} & \frac{1}{2} & \frac{1}{2}\\\frac{1}{2} & - \frac{1}{2} & \frac{1}{2}\\\frac{1}{2} & \frac{1}{2} & - \frac{1}{2}\\\frac{1}{2} & - \frac{1}{2} & - \frac{1}{2}\end{matrix}\right], \ \left[\begin{matrix}2 & 2 & 4\\0 & 4 & 4\\0 & 0 & 4\end{matrix}\right]\right)$
In [152]:
[Q, R] = A.QRdecomposition()
In [153]:
Q
Out[153]:
$\displaystyle \left[\begin{matrix}\frac{1}{2} & \frac{1}{2} & \frac{1}{2}\\\frac{1}{2} & - \frac{1}{2} & \frac{1}{2}\\\frac{1}{2} & \frac{1}{2} & - \frac{1}{2}\\\frac{1}{2} & - \frac{1}{2} & - \frac{1}{2}\end{matrix}\right]$
In [154]:
R
Out[154]:
$\displaystyle \left[\begin{matrix}2 & 2 & 4\\0 & 4 & 4\\0 & 0 & 4\end{matrix}\right]$
In [155]:
Q @ R == A
Out[155]:
True

9.3. Vektornormák¶

In [156]:
import numpy as np
from numpy.linalg import norm
v = np.array([[3, -4]])
In [157]:
norm(v)
Out[157]:
$\displaystyle 5.0$
In [158]:
norm(v, 1)
Out[158]:
$\displaystyle 4.0$
In [159]:
norm(v, np.inf)
Out[159]:
$\displaystyle 7.0$
In [160]:
w = np.array([3, 4, 5])
norm(w, 3)
Out[160]:
$\displaystyle 6.0$

9.4. Mátrixnormák¶

In [161]:
import numpy as np
from numpy.linalg import norm, svd
A = np.array(
    [[2, -2], 
     [1, 2]])
In [162]:
# Fobenius-norma
norm(A)
Out[162]:
$\displaystyle 3.60555127546399$
In [163]:
norm(A, 'fro')
Out[163]:
$\displaystyle 3.60555127546399$
In [164]:
# 2-norma = sigma_1
norm(A, 2)
Out[164]:
$\displaystyle 3.0$
In [165]:
svd(A)[1]
Out[165]:
array([3., 2.])
In [166]:
# a legnagyobb szinguláris érték
svd(A)[1][0]
Out[166]:
$\displaystyle 3.0$
In [167]:
# 1-norma
norm(A, 1)
Out[167]:
$\displaystyle 4.0$
In [168]:
# oo-norma
norm(A, np.inf)
Out[168]:
$\displaystyle 4.0$

9.7. Kondíciószám¶

In [169]:
import numpy as np
from numpy.linalg import cond
a = np.array(
    [[6.73, -8.97],
     [4.79, -6.39]])
cond(a)
Out[169]:
$\displaystyle 4935.67688072789$
In [170]:
cond(a, 1)
Out[170]:
$\displaystyle 6280.00000000159$

11.3. A mod függvény¶

In [171]:
13 % 5         # 13 mod 5 = 3
Out[171]:
$\displaystyle 3$
In [172]:
-13 % 5
Out[172]:
$\displaystyle 2$
In [173]:
13 // 5        # egészosztás
Out[173]:
$\displaystyle 2$
In [174]:
-13 // 5
Out[174]:
$\displaystyle -3$
In [175]:
divmod(13, 5)  # mindkettő
Out[175]:
$\displaystyle \left( 2, \ 3\right)$
In [176]:
divmod(-13, 5)
Out[176]:
$\displaystyle \left( -3, \ 2\right)$

11.8. Komplex számok¶

In [177]:
z = 3 - 1j  # !
z
Out[177]:
(3-1j)
In [178]:
w = 2 + 1j  # j nem elég
w
Out[178]:
(2+1j)
In [179]:
z * w
Out[179]:
(7+1j)
In [180]:
z / w
Out[180]:
(1-1j)
In [181]:
z**2
Out[181]:
(8-6j)
In [182]:
z.real # valós rész
Out[182]:
$\displaystyle 3.0$
In [183]:
z.imag # imaginárius rész
Out[183]:
$\displaystyle -1.0$
In [184]:
z.conjugate() # konjugált
Out[184]:
(3+1j)
In [185]:
# csomag komplexekhez
from cmath import *
polar(1j)
Out[185]:
$\displaystyle \left( 1.0, \ 1.5707963267949\right)$
In [186]:
exp(1j*pi)    # = -1
Out[186]:
(-1+1.2246467991473532e-16j)
In [ ]: