参考的fasttext项目代码:
https://github.com/Hextech425/fasttext_classification_ch
使用到的数据集:
https://github.com/aceimnorstuvwxz/toutiao-text-classfication-dataset
搜的时候发现还有一个300W+的数据集,下次试一试
1、数据清洗
# -*- coding: utf-8 -*-
from types import MethodType, FunctionType
import jieba
# 导入用于繁体/简体转换的包
from langconv import *
def clean_txt(raw):
fil = re.compile(r"[^0-9a-zA-Z\u4e00-\u9fa5]+")
return fil.sub(' ', raw)
def seg(sentence, sw, apply=None, cut_all=False):
"""
对中文文本去特殊符号、去停用词、分词
:param sentence: 原始中文文本
:param sw:
:param apply:
:param cut_all:
:return: 分词后中文文本
"""
if isinstance(apply, FunctionType) or isinstance(apply, MethodType):
sentence = apply(sentence)
return ' '.join([i for i in jieba.cut(sentence, cut_all=cut_all) if i.strip() and i not in sw])
def stop_words():
with open('stopwords.txt', 'r', encoding='utf-8') as swf:
stopwords = [i.strip() for i in swf.readlines()]
return stopwords
def cht_to_chs(line):
"""
中文繁体文本转简体
:param line: 原始文本
:return: 中文简体文本
"""
line = Converter('zh-hans').convert(line)
line.encode('utf-8')
return line
def replace_text(input_str, str_targ, str_rep):
if isinstance(input_str, list):
return [replace_text(s, str_targ, str_rep) for s in input_str]
return input_str.replace(str_targ, str_rep)
# 对某个sentence进行处理:
if __name__ == '__main__':
content = '海尔(Haier)新风机 室内外空气交换 恒氧新风机 XG-100QH/AA'
res = seg(content.lower().replace('\n', ''), stop_words(), apply=clean_txt)
print(res)
test = stop_words()
print(test)
2、数据准备
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import random
from text_cleaner import *
from tqdm import tqdm
import os
import re
from sklearn.utils import shuffle
def load_df(file_path, encoding='utf-8', drop_dup=True, drop_na=True):
"""
从csv文件读取dataframe
:param file_path: csv文件路径
:param encoding: 编码,默认 UTF-8
:param drop_dup: 去掉重复行
:param drop_na: 去掉空行
:return: dataframe
"""
df <

该博客介绍了如何利用FastText进行中文文本分类。首先,进行了数据清洗,包括去除特殊字符、停用词,并使用jieba进行分词。接着,对数据进行了预处理,包括读取数据、去重、切分训练集和验证集。最后,训练了FastText模型并展示了模型在验证集上的分类报告,显示出模型在多个类别上的精确度、召回率和F1分数。
最低0.47元/天 解锁文章
1440

被折叠的 条评论
为什么被折叠?



