2
votes

I am new to python and working on the multi-class text classification of contract documents of the construction industry. I am facing problems in the implementation of n-grams in my code which I produced form by getting help from different online sources. I want to implement unigram, bi-gram, and tri-gram in my code. Any help in this regard shall be highly appreciated.

I have tried bigram and trigram in my Tfidf part of my code but it is working.

    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)

File "C:\Users\fhassan\anaconda3\lib\site-packages\sklearn\feature_extraction\text.py", line 328, in tokenize(preprocess(self.decode(doc))), stop_words)

File "C:\Users\fhassan\anaconda3\lib\site-packages\sklearn\feature_extraction\text.py", line 256, in return lambda x: strip_accents(x.lower())

File "C:\Users\fhassan\anaconda3\lib\site-packages\scipy\sparse\base.py", line 686, in getattr raise AttributeError(attr + " not found")

AttributeError: lower not found

1

1 Answers

0
votes

At first you fit vectorizer on texts:

tfidf_vect_ngram.fit(df['description']) 

And then try to apply it to counts:

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)

You need to apply vectorizer to texts, not counts:

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)