Page 1 of 1

Bester Weg, um die Boolesche Matrix -Multiplikation in Numpy zu berechnen

Posted: 12 Apr 2025, 17:47
by Anonymous
Ich möchte das Matrixprodukt eines Booleschen Arrays mit seiner Transponierung berechnen: < /p>

Code: Select all

import numpy as np
a = np.array([[1, 0, 1], [1, 1, 0]], dtype=bool)
< /code>
Was ist die beste /schnellste Art, dies zu tun?out1 = np.matmul(a, a.T)
print(out1)
< /code>

[[True] [True True]] < /p>
< /blockquote>
Anwendung nur np.matmul < /code> funktioniert nicht wegen des Überlaufs. NP.UINT64 
Ausgabarray für die Funktion: funktioniert auch nicht. Es scheint, als würde die Summe mit Bools berechnet und dann auf uint64 gegossen. < /P>
out2 = np.zeros((2, 2), dtype=np.uint64)
np.matmul(a, a.T, out=out2)
print(out2)
< /code>

[[1 1] [1 1]] < /p>
< /blockquote>

Versuch 3 < /H2>
Die Zeilen -* -Spaltenprodukte. Wenn Sie das Summe bezeichnen, werden das Summenprodukt.out3 = (a[None,:, :] * a[:, None, :]).sum(axis=-1)
print(out3)
< /code>

[[2 1] [1 2]] < /p>
< /blockquote>

Versuch 4 < /h2>
Ich habe versucht, das Array vor der Berechnung zu gießen, und wirkt auch. Aber das Gießen des Eingabebereichs dauert 64 Mal des Speichers, und ich denke, dass die Multiplikation mehr Zeit in Anspruch nimmt, wenn sie mit UINT64 im Vergleich zu zwei Booleschen durchgeführt wird. < /P>
out4 = np.matmul(a.astype(np.uint64), a.T)
print(out4)
< /code>

[[2 1] [1 2]] < /p>
< /blockquote>

Gibt es eine bessere Lösung für dieses Problem, das ich möglicherweise übersesen habe? < /p>