NLP – 如何添加更多特征?

我想使用 sklearn 分类器训练一个模型来对数据条目进行分类(是,否),使用文本特征(内容)、数值特征(人口)和分类特征(位置)。

enter image description here

下面的模型仅使用文本数据来对每个条目进行分类。文本在导入分类器之前通过 TF-IDF 转换成稀疏矩阵。

有没有办法也添加/使用其他特征?这些特征不是稀疏矩阵格式,所以不确定如何将它们与文本稀疏矩阵结合起来。

    #import libraries    import string, re, nltk    import pandas as pd    from pandas import Series, DataFrame    from nltk.corpus import stopwords    from nltk.stem.porter import PorterStemmer    from sklearn.feature_extraction.text import CountVectorizer    from sklearn.feature_extraction.text import TfidfTransformer    from sklearn.model_selection import train_test_split    from sklearn.metrics import classification_report    from sklearn.pipeline import Pipeline    # read data and remove empty lines    dataset = pd.read_csv('sample_data.txt',                           sep='\t',                           names=['content','location','population','target'])                           .dropna(how='all')                           .dropna(subset=['target'])    df = dataset[1:]    #reset dataframe index    df.reset_index(inplace = True)    #add an extra column which is the length of text    df['length'] = df['content'].apply(len)    #create a dataframe that contains only two columns the text and the target class    df_cont = df.copy()    df_cont = df_cont.drop(        ['location','population','length'],axis = 1)    # function that takes in a string of text, removes all punctuation, stopwords and returns a list of cleaned text    def text_process(mess):        # lower case for string        mess = mess.lower()        # check characters and removes URLs       nourl = re.sub(r'http\S+', ' ', mess)        # check characters and removes punctuation        nopunc = [char for char in nourl if char not in string.punctuation]        # join the characters again to form the string and removes numbers        nopunc = ''.join([i for i in nopunc if not i.isdigit()])        # remove stopwords        return [ps.stem(word) for word in nopunc.split() if word not in set(stopwords.words('english'))]    #split the data in train and test set and train/test the model    cont_train, cont_test, target_train, target_test = train_test_split(df_cont['content'],df_cont['target'],test_size = 0.2,shuffle = True, random_state = 1)    pipeline = Pipeline([('bag_of_words',CountVectorizer(analyzer=text_process)),                         ('tfidf',TfidfTransformer()),                         ('classifier',MultinomialNB())])    pipeline.fit(cont_train,target_train)    predictions = pipeline.predict(cont_test)    print(classification_report(predictions,target_test))

预期模型将返回以下结果:准确率、精确率、召回率、F1分数


回答:

我认为您需要对’位置’特征使用独热编码。给定数据的独热向量将是,

伦敦 – 100

曼彻斯特 – 010

爱丁堡 – 001

向量的长度是你数据中城市的数量。请注意,这里每个位都是一个特征。分类数据通常在输入机器学习算法之前转换为独热向量。

完成这些步骤后,您可以将整行拼接成一个一维数组,然后将其输入到分类器中。

Related Posts

为什么我们在K-means聚类方法中使用kmeans.fit函数?

我在一个视频中使用K-means聚类技术,但我不明白为…

如何获取Keras中ImageDataGenerator的.flow_from_directory函数扫描的类名?

我想制作一个用户友好的GUI图像分类器,用户只需指向数…

如何查看每个词的tf-idf得分

我试图了解文档中每个词的tf-idf得分。然而,它只返…

如何修复 ‘ValueError: Found input variables with inconsistent numbers of samples: [32979, 21602]’?

我在制作一个用于情感分析的逻辑回归模型时遇到了这个问题…

如何向神经网络输入两个不同大小的输入?

我想向神经网络输入两个数据集。第一个数据集(元素)具有…

逻辑回归与机器学习有何关联

我们正在开会讨论聘请一位我们信任的顾问来做机器学习。一…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注