2025.7.21 行列の正定性
numpy 版で作ってみよう。
code:p1.py
import numpy
x = numpy.array(-1, 2],[0, 0, dtype=float)
eigs = numpy.linalg.eigvals(x)
print(eigs)
if np.all(eigs > 0):
print('positive definite')
elif np.all(eigs >= 0):
print('positive semi-definite')
elif np.all(eigs < 0):
print('negative definite')
elif np.all(eigs <= 0):
print('negative semi-definite')
else:
print('Not definite')
改良
関数化
ndarrayが入力されたときは tensorに変換して処理を行う
結果に応じて以下の値を返す
0 ... 定値性を持たない
1 ... 正定
2 ... 半正定
3 ... 負定
4 ... 半負定
code:takapack.py
def is_symmetric(x):
if isinstance(x, numpy.ndarray):
x = torch.tensor(x)
return torch.equal(a, a.T)
def matrix_definiteness(x):
# 鞍点は4
if isinstance(x, numpy.ndarray):
x = torch.tensor(x)
if is_symmetric(x) == False:
print('警告:行列は対称(エルミート)ではない')
eigs = torch.linalg.eigvals(x)
print(eigs)
eigs = eigs.real
if torch.all(eigs > 0):
# print('positive definite') # 極小値
return 1
elif torch.all(eigs >= 0):
# print('positive semi-definite')
return 2
elif torch.all(eigs < 0): # 極大値
# print('negative definite')
return 3
elif torch.all(eigs <= 0):
# print('negative semi-definite')
return 4
else:
# print('Not definite') # 鞍点
return 0 # sa
x = numpy.array(1, 2],[2, 0, dtype=float)
ret = matrix_definiteness(x)
print(ret)