我正在尝试在不使用测试矩阵的库的情况下实现k交叉验证背后的逻辑。以某种方式,我的旋转矩阵无法正常工作。
我将k设为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)
答案 0 :(得分:0)
tempX = X_train
此语句不会创建新变量tempX并为其分配X_train。它使变量名称tempX和X_train都指向同一对象。 tempX的任何更改都将反映在X_train中。这是代码中经常发生的问题。
当尝试进行这样的列表分配时,请使用以下代码。
tempX = X_train.copy()
这里是指向类似问题的链接,提供了更多解决方案。
How to clone or copy a list?