如何在python中的不同文件中保存许多列表?

时间:2016-10-31 14:41:01

标签: python-3.x numpy

我有一个for循环,在将它们发送到混淆矩阵部分之前调用我的6个文件(AWA,REM等)。 我想保存每个生成的列表(6个列表),以便我可以稍后调用它们并绘制混淆矩阵。

我用过泡菜。

这里是代码:

#Here I load the matlab files
for name in ["AWA", "Rem", "S1","S2","SWS","stades"]: 
    x=sio.loadmat('/home/{}_FeaturesAll.mat'.format(name))['x'] 
    s_y=sio.loadmat('/home/{}_FeaturesAll.mat'.format(name))['y']
    y=np.ravel(s_y)

    print(name, x.shape, y.shape) 
    print("")

#Here come code of the classifier and the cross validation
.
.
.

##########################Confusion Matrix#########################
from sklearn.metrics import confusion_matrix
for train_index, test_index in sss:                                                                                                                               
   x_train, x_test = x[train_index], x[test_index] 
   y_train, y_test = y[train_index], y[test_index]   

   y_pred = clf.fit(x_train, y_train).predict(x_test) 

   cm = confusion_matrix(y_test, y_pred) 
   np.set_printoptions(precision=3) 

   list_cm.append(cm) #I WANT TO SAVE THIS LIST FOR EACH FILE: AWA_list_cm, Rem_list_cm, etc


   #MY ATTEMPT SAVING 1 FILE
   ##################The pickling####################
   with open("list_cm.txt", "wb") as fp: 
            pickle.dump(list_cm, fp)


#MY ATTEMPT RECOVERING MY SAVED FILE
####Here I call the list to do the plotting#####
with open("list_cm.txt", "rb") as fp:   
    list_cm = pickle.load(fp)

1 个答案:

答案 0 :(得分:0)

我只添加了" .format(名称)"

 ############The pickling for any # of files################        
 with open("{}_cm.txt".format(name), "wb") 
      pickle.dump(list_cm, fp) 



######################"unpickling for any # of files"####################
for name in ["AWA", "Rem", "S1" ,"S2","SWS","stades"]:

    with open('{}_cm.txt'.format(name), "rb") as fp:   
        list_cm = pickle.load(fp)