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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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