fasttext文本分类python实现_基于FastText进行文本分类

liunx版本下操作:

$ git clone https://github.com/facebookresearch/fastText.git

$ cd fastText

$ pip install .

安装成功后的导入:

新建test.py文件,写入:

import fastText.FastText as fasttext(可能会瞟红线)

新增:最近发现fasttext的github更新了,引入方式发生了变化,如果上述引入报错,改成 import fasttext.FastText as fasttext

新增:现在安装直接 pip install fasttext,导入直接 import fasttext 就行

保存后退出并运行:

python3 test.py

没报错说明安装成功第二步:准备数据集我这里用的是清华的新闻数据集(由于完整数据集较大,这里只取部分数据)

数据链接:点击获取网盘数据 提取码:byoi(data.txt为数据集,stopwords.txt为停用词)

下载好后的数据格式为:

对应的标签分别为(由于只是用小部分数据,所以data.txt只包含部分标签):

mapper_tag = {

'财经': 'Finance',

'彩票': 'Lottery',

'房产': 'Property',

'股票': 'Shares',

'家居': 'Furnishing',

'教育': 'Education',

'科技': 'Technology',

'社会': 'Sociology',

'时尚': 'Fashion',

'时政': 'Affairs',

'体育': 'Sports',

'星座': 'Constellation',

'游戏': 'Game',

'娱乐': 'Entertainment'

}第三步:数据预处理由于data.txt已经经过了分词和去停用词的处理,所以这里只需要对数据进行切割为训练集和测试集即可。

分词和去停用词的工具代码(运行时不需要执行此部分代码):

import re

from types import MethodType, FunctionType

import jieba

def clean_txt(raw):

fil = re.compile(r"[^0-9a-zA-Z\u4e00-\u9fa5]+")

return fil.sub(' ', raw)

def seg(sentence, sw, apply=None):

if isinstance(apply, FunctionType) or isinstance(apply, MethodType):

sentence = apply(sentence)

return ' '.join([i for i in jieba.cut(sentence) if i.strip() and i not in sw])

def stop_words():

with open('stop_words.txt', 'r', encoding='utf-8') as swf:

return [line.strip() for line in swf]

# 对某个sentence进行处理:

content = '上海天然橡胶期价周三再创年内新高,主力合约突破21000元/吨重要关口。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
FastText是Facebook开发的一种文本分类算法,它通过将文本分解成n-gram特征来表示文本,并基于这些特征训练模型。PyTorch是一个流行的深度学习框架,可以用于实现FastText文本分类算法。 以下是使用PyTorch实现FastText文本分类的基本步骤: 1. 数据预处理:将文本数据分成训练集和测试集,并进行预处理,如分词、去除停用词、构建词典等。 2. 构建数据集:将预处理后的文本数据转换成PyTorch中的数据集格式,如torchtext中的Dataset。 3. 定义模型:使用PyTorch定义FastText模型,模型包括嵌入层、平均池化层和全连接层。 4. 训练模型:使用训练集训练FastText模型,并在验证集上进行验证调整超参数。 5. 测试模型:使用测试集评估训练好的FastText模型的性能。 以下是一个简单的PyTorch实现FastText文本分类的示例代码: ```python import torch import torch.nn as nn import torch.optim as optim from torchtext.legacy.data import Field, TabularDataset, BucketIterator # 数据预处理 TEXT = Field(tokenize='spacy', tokenizer_language='en_core_web_sm', include_lengths=True) LABEL = Field(sequential=False, dtype=torch.float) train_data, test_data = TabularDataset.splits( path='data', train='train.csv', test='test.csv', format='csv', fields=[('text', TEXT), ('label', LABEL)] ) TEXT.build_vocab(train_data, max_size=25000, vectors="glove.6B.100d") LABEL.build_vocab(train_data) # 定义模型 class FastText(nn.Module): def __init__(self, vocab_size, embedding_dim, output_dim): super().__init__() self.embedding = nn.Embedding(vocab_size, embedding_dim) self.fc = nn.Linear(embedding_dim, output_dim) def forward(self, x): embedded = self.embedding(x) pooled = embedded.mean(0) output = self.fc(pooled) return output # 训练模型 BATCH_SIZE = 64 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') train_iterator, test_iterator = BucketIterator.splits( (train_data, test_data), batch_size=BATCH_SIZE, sort_within_batch=True, device=device ) model = FastText(len(TEXT.vocab), 100, 1).to(device) optimizer = optim.Adam(model.parameters()) criterion = nn.BCEWithLogitsLoss().to(device) for epoch in range(10): for batch in train_iterator: text, text_lengths = batch.text labels = batch.label optimizer.zero_grad() output = model(text).squeeze(1) loss = criterion(output, labels) loss.backward() optimizer.step() with torch.no_grad(): total_loss = 0 total_correct = 0 for batch in test_iterator: text, text_lengths = batch.text labels = batch.label output = model(text).squeeze(1) loss = criterion(output, labels) total_loss += loss.item() predictions = torch.round(torch.sigmoid(output)) total_correct += (predictions == labels).sum().item() acc = total_correct / len(test_data) print('Epoch:', epoch+1, 'Test Loss:', total_loss / len(test_iterator), 'Test Acc:', acc) ``` 这个示例代码使用了torchtext库来处理数据集,并定义了一个FastText模型,模型包括一个嵌入层、一个平均池化层和一个全连接层。模型在训练集上训练,并在测试集上进行测试,并输出测试集的损失和准确率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值