【问题标题】:How to solve Nameerror: name 'n' is not defined in train_test_split of scikit-learn 0.22 version without downgrading the version?如何解决 Nameerror: name 'n' is not defined in train_test_split of scikit-learn 0.22 version without downgrade the version?
【发布时间】:2020-07-11 15:59:49
【问题描述】:

我正在做情绪分析并使用 scikit learn train_test_split 函数。但是我收到 Nameerror: 'n' is not defined 即使我已经定义了它。在检查了各种论坛后,我发现这个错误与 scikit learn 的新版本(0.19 之后)有关。所以给出的解决方案是将 scikit learn 降级到 0.19 版本,它会起作用。但我的问题是我正在使用 python 3.7 并使用 anaconda3、jupyter notebook 6.0.3 并且它没有降级到旧版本。

我该怎么办?如何解决这个问题?

def postprocess(data, n=1000000):
    data = data.head(n)
    data['tokens'] = data['Articles'].progress_map(tokenize)  ## progress_map is a variant of the map function plus a progress bar. Handy to monitor DataFrame creations.
    data = data[data.tokens != 'NC']
    data.reset_index(inplace=True)
    data.drop('index', inplace=True, axis=1)
    return data

data = postprocess(data)

x_train, x_test, y_train, y_test = train_test_split(np.array(data.head(n).tokens),
                                                    np.array(data.head(n).Sentiment), test_size=0.2)  

错误:

NameError Traceback(最近调用 最后)在 ----> 1 x_train, x_test, y_train, y_test = train_test_split(np.array(data.head(n).tokens), 2 np.array(data.head(n).Sentiment), test_size=0.2)

NameError: name 'n' is not defined

提前致谢。

【问题讨论】:

    标签: python scikit-learn python-3.7 nameerror train-test-split


    【解决方案1】:

    您似乎没有在您的 postprocess 函数之外的任何地方定义 n,而且在最近的版本中,这样的错误听起来不太可能是由于 scikit-learn 错误造成的(当声称类似的东西时,您应始终包括您自己的研究结果)。

    无论如何,这很可能会起作用(前提是您的代码和数据没有其他问题):

    n=1000000
    data = postprocess(data, n=n)
    x_train, x_test, y_train, y_test = train_test_split(np.array(data.head(n).tokens),
                                                        np.array(data.head(n).Sentiment), test_size=0.2)  
    

    【讨论】:

    • 现在我得到 ValueError: With n_samples=0, test_size=0.2 and train_size=None, 结果训练集将为空。调整上述任何参数。
    • @PiyushGhasiya 正如我所说 - 前提是您的代码和数据没有其他问题。你的data.head(n) 好像是空的。无论如何,这是一个完全不同的错误;由于答案解决了您的 NameError 而不降级您的 scikit-learn 或 Python,请接受它并使用新问题(以及您的调查结果)打开一个新问题。
    • @PiyushGhasiya 不清楚为什么在train_test_split 中使用data.head(n),而您已经在postprocess 函数中使用data = data.head(n)
    猜你喜欢
    • 2016-06-21
    • 2023-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-02
    • 2021-12-15
    • 1970-01-01
    相关资源
    最近更新 更多