新闻文本分类task4

Fasttext使用

fasttext安装

安装地址
任务代码:

import pandas as pd
from sklearn.metrics import f1_score

# 转换为FastText需要的格式
train_df = pd.read_csv('./data/train_set.csv', sep='\t', nrows=15000)
train_df['label_ft'] = '__label__' + train_df['label'].astype(str)
train_df[['text','label_ft']].iloc[:-5000].to_csv('train.csv', index=None, header=None, sep='\t')

import fasttext
model = fasttext.train_supervised('train.csv', lr=1.0, wordNgrams=2,
                                  verbose=2, minCount=1, epoch=25, loss="hs")

val_pred = [model.predict(x)[0][0].split('__')[-1] for x in train_df.iloc[-5000:]['text']]
print(f1_score(train_df['label'].values[-5000:].astype(str), val_pred, average='macro'))

默认__label__为预测值前缀
训练模型

trainDataFile = 'train.txt'
 
classifier = fasttext.train_supervised(
    input = trainDataFile,
    label_prefix = '__label__',
    dim = 256,
    epoch = 50,
    lr = 1,
    lr_update_rate = 50,
    min_count = 3,
    loss = 'softmax',
    word_ngrams = 2,
    bucket = 1000000)
classifier.save_model("Model.bin")

使用fastText进行预测

testDataFile = 'test.txt'
classifier = fasttext.load_model('Model.bin') 
result = classifier.test(testDataFile)
print '测试集上数据量', result[0]
print '测试集上准确率', result[1]
print '测试集上召回率', result[2]

Bag of tricks for efficient text classification
1)分层softmax:对于类别过多的类目,fastText并不是使用的原生的softmax过交叉熵,而是使用的分层softmax,这样会大大提高模型的训练和预测的速度。

2)n-grams:fastText使用了字符级别的n-grams来表示一个单词。对于单词“apple”,假设n的取值为则它的trigram有“<ap”, “app”, “ppl”, “ple”, “le>”

其中,<表示前缀,>表示后缀。于是,我们可以用这些trigram来表示“apple”这个单词,进一步,我们可以用这5个trigram的向量叠加来表示“apple”的词向量。

这带来两点好处:

  1. 对于低频词生成的词向量效果会更好。因为它们的n-gram可以和其它词共享。
  2. 对于训练词库之外的单词,仍然可以构建它们的词向量。我们可以叠加它们的字符级n-gram向量

可选参数

The following arguments are mandatory:
  -input              training file path
  -output             output file path
 
The following arguments are optional:
  -verbose            verbosity level [2]
 
The following arguments for the dictionary are optional:
  -minCount           minimal number of word occurrences [1]
  -minCountLabel      minimal number of label occurrences [0]
  -wordNgrams         max length of word ngram [1]
  -bucket             number of buckets [2000000]
  -minn               min length of char ngram [0]
  -maxn               max length of char ngram [0]
  -t                  sampling threshold [0.0001]
  -label              labels prefix [__label__]
 
The following arguments for training are optional:
  -lr                 learning rate [0.1]
  -lrUpdateRate       change the rate of updates for the learning rate [100]
  -dim                size of word vectors [100]
  -ws                 size of the context window [5]
  -epoch              number of epochs [5]
  -neg                number of negatives sampled [5]
  -loss               loss function {ns, hs, softmax} [softmax]
  -thread             number of threads [12]
  -pretrainedVectors  pretrained word vectors for supervised learning []
  -saveOutput         whether output params should be saved [0]
 
The following arguments for quantization are optional:
  -cutoff             number of words and ngrams to retain [0]
  -retrain            finetune embeddings if a cutoff is applied [0]
  -qnorm              quantizing the norm separately [0]
  -qout               quantizing the classifier [0]
  -dsub               size of each sub-vector [2]
XGBoost是一种机器学习算法,可以用于分类和回归任务。它有两种接口:XGBoost原生接口和scikit-learn接口。对于新闻分类任务,你可以使用XGBoost模型来进行分类。 在使用XGBoost进行新闻分类时,你可以考虑调整一些参数以优化模型的性能。其中一些重要的参数包括: - booster: 指定使用的booster类型,可以是gbtree、gblinear或dart。 - n_jobs: 并行运行XGBoost时使用的线程数。 - verbosity: 控制输出的详细程度,取值范围是0(静默)到3(调试)。 - scale_pos_weight: 正负样本权重的平衡。 通过调整这些参数,你可以进一步提升XGBoost模型在新闻分类任务中的表现。 另外,你可以参考一些已有的资源,比如XGBoost与LightGBM文本分类源代码及数据集,来了解更多关于如何使用XGBoost进行新闻分类的实例和数据集。 综上所述,XGBoost可以用于新闻分类任务,你可以调整相关参数来提高模型的性能,并参考相关资源来获取更多实例和数据集。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [XGBoost与LightGBM文本分类](https://blog.csdn.net/asialee_bird/article/details/94836962)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [使用xgboost进行文本分类](https://blog.csdn.net/bitcarmanlee/article/details/123991000)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值