保存到 Pickle 时出错 - TypeError:write() 参数必须是 str,而不是 bytes

Error on saving to Pickle - TypeError: write() argument must be str, not bytes

提问人:angeliquelinde 提问时间:7/6/2021 最后编辑:angeliquelinde 更新时间:7/7/2021 访问量:1188

问:

我正在尝试将以下内容保存到 pickle,但收到错误说我的参数必须是 str,而不是字节。我查看了 pickle 文档并尝试将 x 和 y 转换为字符串,但没有运气。我做错了什么?

import pandas as pd
from sklearn.naive_bayes import GaussianNB
import pickle



df = {'Description':[100,200,300,400,500],'Level_1':[1,2,3,4,5]}

df = pd.DataFrame(df,columns=['Description','Level_1'])

print(df)

   Description  Level_1
0          100        1
1          200        2
2          300        3
3          400        4
4          500        5

x = df[['Description']]
y = df['Level_1']

nb = GaussianNB()
nb.fit(x,y)

open('level1_classifier.pk', 'wb')
with open ('level1_classifier.pk') as l1clf:
    pickle.dump(nb, l1clf)

Error Message:
 ``TypeError                                 Traceback (most recent call last)
<ipython-input-21-89a76f30f361> in <module>
      6 #open('level1_classifier.pk', 'wb')
      7 with open ('level1_classifier.pk') as l1clf:
----> 8     pickle.dump(nb, l1clf)

TypeError: write() argument must be str, not bytes
泡菜

评论

0赞 angeliquelinde 7/6/2021
这是堆栈: TypeError Traceback (最近一次调用) <ipython-input-21-89a76f30f361> in <module> 6 #open('level1_classifier.pk', 'wb') 7 with open ('level1_classifier.pk') as l1clf: ----> 8 pickle.dump(nb, l1clf) TypeError: write() 参数必须是 str,而不是 bytes

答:

2赞 Almog-at-Nailo 7/6/2021 #1

如果没有适当的堆栈跟踪,则很难进行调试,请添加一个。

也就是说,您正在打开泡菜文件进行写入,然后打开它进行读取。这是不必要的,可能是这里失败的原因。

这:

open('level1_classifier.pk', 'wb')
with open ('level1_classifier.pk') as l1clf:
    pickle.dump(nb, l1clf)

大概应该是这样的:

with open('level1_classifier.pk', 'wb') as l1clf:
    pickle.dump(nb, l1clf)

有关更多详细信息,请参阅本指南