2

我是 python 新手,致力于建筑行业合同文件的多类文本分类。我在我的代码中实现 n-gram 时遇到了问题,我通过从不同的在线资源获得帮助来生成表单。我想在我的代码中实现 unigram、bi-gram 和 tri-gram。在这方面的任何帮助将不胜感激。

我在我的代码的 Tfidf 部分中尝试了二元组和三元组,但它正在工作。

    df = pd.read_csv('projectdataayes.csv')
    df = df[pd.notnull(df['types'])]
    my_types = ['Requirement','Non-Requirement']

    #converting to lower case
    df['description'] = df.description.map(lambda x: x.lower()) 

    #Removing the punctuation
    df['description'] = df.description.str.replace('[^\w\s]', '')  

    #splitting the word into tokens
    df['description'] = df['description'].apply(tokenize.word_tokenize) 

    #stemming
    stemmer = PorterStemmer()
    df['description'] = df['description'].apply(lambda x: [stemmer.stem(y) for y in x]) 

    print(df[:10])

    ## This converts the list of words into space-separated strings
    df['description'] = df['description'].apply(lambda x: ' '.join(x))
    count_vect = CountVectorizer()  
    counts = count_vect.fit_transform(df['description']) 


    X_train, X_test, y_train, y_test = train_test_split(counts, df['types'], test_size=0.3, random_state=39) 

    tfidf_vect_ngram = TfidfVectorizer(analyzer='word', 
    token_pattern=r'\w{1,}', ngram_range=(2,3), max_features=5000)
    tfidf_vect_ngram.fit(df['description'])
    X_train_Tfidf =  tfidf_vect_ngram.transform(X_train)
    X_test_Tfidf =  tfidf_vect_ngram.transform(X_test)

    model = MultinomialNB().fit(X_train, y_train)

文件“C:\Users\fhassan\anaconda3\lib\site-packages\sklearn\feature_extraction\text.py”,第 328 行,在 tokenize(preprocess(self.decode(doc))),stop_words)

文件“C:\Users\fhassan\anaconda3\lib\site-packages\sklearn\feature_extraction\text.py”,第 256 行,返回 lambda x: strip_accents(x.lower())

文件“C:\Users\fhassan\anaconda3\lib\site-packages\scipy\sparse\base.py”,第 686 行,在getattr raise AttributeError(attr + " not found")

AttributeError:未找到下限

4

1 回答 1

0

首先,您在文本上安装矢量化器:

tfidf_vect_ngram.fit(df['description']) 

然后尝试将其应用于计数:

counts = count_vect.fit_transform(df['description'])
X_train, X_test, y_train, y_test = train_test_split(counts, df['types'], test_size=0.3, random_state=39) 
tfidf_vect_ngram.transform(X_train)

您需要将矢量化器应用于文本,而不是计数:

X_train, X_test, y_train, y_test = train_test_split(df['description'], df['types'], test_size=0.3, random_state=39)
tfidf_vect_ngram.transform(X_train)
于 2019-04-07T03:09:14.173 回答