简体   繁体   English

为什么我不能关闭泡菜文件?

[英]Why can't I close a pickle file?

I have been working on a classifier model, using GridSearchCV to find the best hyperparameters.我一直在研究分类器 model,使用 GridSearchCV 找到最佳超参数。 I then pickled the model, and loaded it back (to save time everytime I have to run the notebook).然后我腌制了 model,并将其加载回来(以节省每次我必须运行笔记本的时间)。

When I try to close it though, I get this error:但是,当我尝试关闭它时,出现此错误:

AttributeError: 'GridSearchCV' object has no attribute 'close'

This is my code:这是我的代码:

# Save the Grid Search CV object as a pickle file
pickle.dump(knn_grid, open(r'./knn_grid_model.p', 'wb'))
# load the Grid Search CV object
knn_grid = pickle.load(open(r'./knn_grid_model.p', 'rb'))
# Close the file
knn_grid.close()

Any idea on how to overcome this?关于如何克服这个问题的任何想法? Will it be a big deal if I don't close the pickle file?如果我不关闭泡菜文件会很重要吗?

knn_grid isn't a file, it's the GridSearchCV object that was unpickled. knn_grid不是文件,它是未腌制的GridSearchCV object。

However, your second question still stands:但是,您的第二个问题仍然存在:

Will it be a big deal if I don't close the pickle file?如果我不关闭泡菜文件会很重要吗?

The way your code is written, the file may be left open until being garbage-collected or until the Python interpreter exits.根据您编写代码的方式,文件可能会保持打开状态,直到被垃圾收集或 Python 解释器退出。 Now, leaving a file open for reading shouldn't cause any problems, but leaving a file open for writing could cause missing data .现在,打开文件进行读取应该不会导致任何问题,但是打开文件进行写入可能会导致丢失数据 So the best practice is to use a with statement to ensure that the content is written and the file is closed:所以最好的做法是使用with语句来保证内容写完,文件关闭:

with open('./knn_grid_model.p', 'wb') as f:
    pickle.dump(knn_grid, f)

with open('./knn_grid_model.p', 'rb') as f:
    knn_grid = pickle.load(f)

(Note that the r-strings don't make any difference in this case.) (请注意,在这种情况下,r 字符串没有任何区别。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM