0

I m using pickle to save obj file. Obj file is used to save a model.

import numpy as np
import pandas as pd
import dill as pickle
from sklearn.base import BaseEstimator

class clf_express(BaseEstimator):
    """
    Base class for model handling
    """
    def __init__(self):
        """
        Assign objects to use in transform() and predict() methods
        """

        #creation_time = pd.Timestamp.now().ctime()
        time = pd.Timestamp.now().strftime('%Y-%m-%d-%H-%M')
        self.name = "RISK_MODEL_for_credit_card_without_non_logical_created_at_" + time  

    def pickle_myself(self):
        """
        Save class object to binary file
        """
        self.date_create = pd.Timestamp.now().ctime()
        with open(self.name +'.obj', 'wb') as f:
            pickle.dump(self, f, protocol=3)

the problem starts with pickle_myself method().

this code works if i use strftime() for timestamp:

        time = pd.Timestamp.now().strftime('%Y-%m-%d-%H-%M') #this works
        self.name = "RISK_MODEL_for_credit_card_without_non_logical_created_at_" + time

and when I call pickle_myself() it works, it does save it and dump as obj file. the name for my model that i save is:

'RISK_MODEL_for_credit_card_without_non_logical_created_at_2019-12-19-17-42'

this code does not work if i use ctime() for timestamp:

    time = pd.Timestamp.now().ctime()
    self.name = "RISK_MODEL_for_credit_card_without_non_logical_created_at_" + time

the name i should have for my model is:

'RISK_MODEL_for_credit_card_without_non_logical_created_at_Thu Dec 19 17:42:44 2019'

but both strftime and ctime are strings! Why is pickle dump not working?

the error msg:

OSError: [Errno 22] Invalid argument: 'RISK_MODEL_for_credit_card_without_non_logical_created_at_Thu Dec 19 17:44:14 2019.obj'
kaban
  • 423
  • 1
  • 5
  • 10

1 Answers1

1

This has nothing to do with pickle's library, if you look at the error you got it says OSError: [Errno 22].

If you google for this error, you may stumble upon this question.

Which would lead me to this question: are you on Windows? Because the file you're trying to write, has colons in its name.

Then the issue is that you're trying to name your file with colons:

'RISK_MODEL_for_credit_card_without_non_logical_created_at_Thu Dec 19 17:42:44 2019'

doing a .replace(":", "_") should be enough for fixing it.

Federico Ponzi
  • 2,682
  • 4
  • 34
  • 60