0

I am trying to implement the logic behind k-cross validation without the use of library on a test matrix.Somehow , my rotated matrices are not working fine.

I have taken k to be 5.

X = np.matrix([[1,2,3,4,5],[7,8,9,4,5],[4,9,6,4,2],[9,5,1,2,3],[7,5,3,4,6]])
P = np.ones((5,5))
target = np.matrix([[1,2,3,4,5]]).T
#def k_fold(X,target,k):
r = X.shape[0]  
k=5
step = r//k  
last_row_train = step*(k-1) 

for i in range(5):
    X_train = X[0:last_row_train,:]
    tempX = X_train

    X_test = X[last_row_train:r,:]
    temp_X_test = X_test

    t_train = target[0:last_row_train,:]
    temp_t_train = t_train
    t_test = target[last_row_train:r,:]
    temp_test = t_test
    X[step:r,:] = tempX # On running this line, it changes the value of 
                        #  temp_X_test which is very weird and not
                        # supposed to happen 
    X[0:step,:] = temp_X_test 
    target[0:step,:] = temp_test
    target[step:r,:] = temp_t_train
    print (X)
    print (target)

1 Answers1

0

tempX = X_train

This statement does not create a new variable tempX and assign X_train to it. It makes both the variable names tempX and X_train point to the same object. Any change in tempX will be reflected in X_train. This is a recurring problem in your code.

When trying to make a list assignment like that use the code below.

tempX = X_train.copy()

Here's a link to a similar question with more solutions.
How to clone or copy a list?

thatNLPguy
  • 101
  • 8