0

What am I missing? The following code seems to show the failure of associative law using numpy. It is not just a little off; 3 matricies A, B, C multiplied as (AB)C looks correct but multiplied as A(BC) the output looks like random numbers. The correct output should be a diagonal matrix.

    import numpy as np
    from numpy.linalg import inv
    import tensorflow as tf
    from tensorflow import keras
    from keras.datasets import mnist

    def bug():
        print('associative law fails for matrix multiplication? output looks like random numbers')
        (X, y),(test_images,test_labels)=mnist.load_data()

        X=X[0:60]
        y=y[0:60]

        X=np.reshape(X,(len(X),28*28))#784=28*28
        symmetric_matrix=np.matmul(X,X.T)
        symmetric_matrix_inv=inv(symmetric_matrix)
        diag_y=np.diag(y)
        print('diag_y[:5]',diag_y[:5])
        C=np.matmul(symmetric_matrix_inv,diag_y)

        # to make the code more readable
        A=X
        B=X.T

        print('Output should equal diag_y;THIS FAILS BUT..')
        BmultC=np.matmul(B,C)
        Amult_BmultC=np.matmul(A,BmultC)
        print('Amult_BmultC[:5]',np.around(Amult_BmultC[:5]).astype(int))

        print('...BUT THIS WORKS!!!!')
        AmultB=np.matmul(A,B)
        AmultBmult_C=np.matmul(AmultB,C)
        print('AmultBmult_C[:5]',np.around(AmultBmult_C[:5]).astype(int))

        print('WHY???')
        return

    bug()
  • Please make your code [reproducible](https://stackoverflow.com/help/minimal-reproducible-example). – rpoleski May 13 '20 at 17:46
  • I just created a new jupyter notebook and it reproduces. Are you referring to indentation? or to the libraries like keras/mnist from which it gets its data? Or some other reason it does not work (compile? output is wrong? etc.) – Scott Cohen May 13 '20 at 18:03
  • Sorry, you're right. I've somehow overlooked mnist import – rpoleski May 13 '20 at 18:15

0 Answers0