Search code examples
arrayspython-3.xupdating

strange behavior when updating matrix


import numpy as np

X_mini=np.array([[   4, 2104,    1],
   [   1, 1600,    3],
   [   3, 2400,    100]])

def feature_normalization(X):

    row_length=len(X[0:1][0])

    for i in range(0, row_length):
        if not X[:,i].std()==0:

            temp=(X[:,i]-X[:,i].mean())/X[:,i].std()
            print(temp)
            X[:,i]=temp



feature_normalization(X_mini)
print(X_mini)

outputs:

[ 1.06904497 -1.33630621  0.26726124]
[ 0.209937   -1.31614348  1.10620649]
[-0.72863911 -0.68535362  1.41399274]
[[ 1  0  0]
 [-1 -1  0]
 [ 0  1  1]]

my question is, why does not X_mini (after applying feature_normalization) correspond to what is being printed out?


Solution

  • Your array holds values of integer type (probably int64). When fractions are inserted into it, they're converted to int.

    You can explicitly specify the type of an array you create:

    X_mini = np.array([[ 4.0,  2104.0,  1.0],
           [ 1.0,  1600.0,  3.0],
           [ 3.0,  2400.0,  100.0]], dtype=np.float128)
    

    You can also convert an array to another type using numpy.ndarray.astype (docs).