【问题标题】:Import Only Work Inside Python Function导入仅适用于 Python 函数
【发布时间】:2017-01-20 19:56:11
【问题描述】:

背景信息:我正在使用 scikit-learn 开发模型。我使用 sklearn.cross_validation 模块将数据分成单独的训练和测试集,如下所示:

def train_test_split(input_data):
       from sklearn.cross_validation import train_test_split

        ### STEP 1: Separate y variable and remove from X
       y = input_data['price']
       X = input_data.copy()
       X.drop('price', axis=1, inplace=True)

        ### STEP 2: Split into training & test sets
       X_train, X_test, y_train, y_test =\ 
                        train_test_split(X, y, test_size=0.2, random_state=0)
       return X_train, X_test, y_train, y_test

我的问题:当我尝试在我的函数之外导入 sklearn.cross_validation 模块时,像这样,我收到以下错误:

from sklearn.cross_validation import train_test_split

def train_test_split(input_data):
       ### STEP 1: Separate y variable and remove from X
       y = input_data['price']
       X = input_data.copy()
       X.drop('price', axis=1, inplace=True)

       ### STEP 2: Split into training & test sets
       X_train, X_test, y_train, y_test =\ 
                        train_test_split(X, y, test_size=0.2, random_state=0)
       return X_train, X_test, y_train, y_test

错误:

TypeError: train_test_split() got an unexpected keyword argument 'test_size'

知道为什么吗?

【问题讨论】:

    标签: python scikit-learn python-import


    【解决方案1】:

    您正在从 sklear.cross_validation 导入函数 train_test_split,然后用本地函数 train_test_split 覆盖名称。

    试试:

    from sklearn.cross_validation import train_test_split as sk_train_test_split
    
    def train_test_split(input_data):
           ### STEP 1: Separate y variable and remove from X
           y = input_data['price']
           X = input_data.copy()
           X.drop('price', axis=1, inplace=True)
    
           ### STEP 2: Split into training & test sets
           X_train, X_test, y_train, y_test =\ 
                            sk_train_test_split(X, y, test_size=0.2, random_state=0)  # use the imported function instead of local one
           return X_train, X_test, y_train, y_test
    

    【讨论】:

    • 哈哈!这么小的错误,我想不通。谢谢@RedX - 这就是答案!
    猜你喜欢
    • 1970-01-01
    • 2017-01-12
    • 2012-06-26
    • 2022-01-16
    • 2018-01-23
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多