Reputation: 79
I am trying to save the following to pickle but am getting the error saying my argument must be str, not bytes. I have looked at the pickle documentation and tried converting x and y to strings with no luck. What am I doing wrong?
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
Upvotes: 1
Views: 1826
Reputation: 1182
It's hard to debug without a proper stack trace, please add one.
That said, you are opening the pickle file for writing and then opening it for reading. This is unnecessary and probably what's failing here.
This:
open('level1_classifier.pk', 'wb')
with open ('level1_classifier.pk') as l1clf:
pickle.dump(nb, l1clf)
Should probably be like this:
with open('level1_classifier.pk', 'wb') as l1clf:
pickle.dump(nb, l1clf)
See this guide for more details
Upvotes: 2