zoukankan      html  css  js  c++  java
  • sohu_news搜狐新闻类型分类

    数据获取

    • 数据是从搜狐新闻开放的新闻xml数据,经过一系列的处理之后,生成的一个excel文件
    • 该xml文件的处理有单独的处理过程,就是用pandas处理,该过程在此省略
    import numpy as np
    import pandas as pd
    
    • 读取新闻文本文件,查看文本的长度
    df=pd.read_excel('sohu_data.xlsx')
    df['length']=df['content'].apply(lambda x: len(x)).values
    
    • 去掉长度小于50的文本
    df_data = df[df['length']>=50][['content','category']]
    
    • 查看新闻类型的分布,共9类
    df_data['category'].value_counts()
    # 可以看到这里面存在类别不平衡,最大的差距有17倍。
    
    health      30929
    news        27613
    auto        22841
    stock       18152
    it          13875
    yule        13785
    women        4667
    book         4411
    business     1769
    Name: category, dtype: int64
    
    • 使用sklearn中的处理模块的labelEncoder方法对类标进行处理
    from sklearn.preprocessing import LabelEncoder
    class_le=LabelEncoder()
    class_le.fit(np.unique(df['category'].values)
    print(list(class_le.classes_))
    y=class_le.transform(df['category'].values)
    
    # 查看前20个新闻样本的类别
    y[:20]
    
    ['auto', 'book', 'business', 'health', 'it', 'news', 'stock', 'women', 'yule']
    array([7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7], dtype=int64)
    
    • 导入jieba,进行分词
    import jieba
    def chinese_word_cut(mytext):
        return " ".join(jieba.cut(mytext))
    X=pd.DataFrame()
    X['cut_content']=df["content"].apply(chinese_word_cut)
    X['cut_content'].head()
    
    Building prefix dict from the default dictionary ...
    Loading model from cache C:UsersHUANG_~1AppDataLocalTempjieba.cache
    Loading model cost 0.966 seconds.
    Prefix dict has been built succesfully.
    
    
    
    
    
    1    产品名称 : � 规格 及 价格 : 3 0 m l / 3 0 0   元 � 羽西 当归...
    2    常见问题 � Q : 为什么 我 提交 不了 试用 申请   A : 试用 申请 必须 同时...
    3    产品名称 : 肌醇 ( P u r e   S k i n ) 深层 卸妆 凝胶 � 规格 ...
    4    欧诗漫 的 试用装 终于 延期 而 至 , 果然 不负 所望 , 包装 很 精美 。 从 快...
    5    试用 申请 步骤 � 1 注册 并 完善 个人资料   登入 搜狐 试用 频道 , 填写 并...
    Name: cut_content, dtype: object
    
    • 使用词袋模型进行文本处理,去除停用词,去除数字特征,使用朴素贝叶斯进行分类
    from sklearn.model_selection import  train_test_split
    X_train,X_test,y_train,y_test= train_test_split(X,y,random_state=42,test_size=0.25)
    def get_custom_stopwords(stop_words_file):
        with open(stop_words_file,encoding="utf-8") as f:
            custom_stopwords_list=[i.strip() for i in f.readlines()]
        return custom_stopwords_list
    stop_words_file = "stopwords.txt"
    stopwords = get_custom_stopwords(stop_words_file) # 获取停用词
    from sklearn.feature_extraction.text import  CountVectorizer
    vect = CountVectorizer(token_pattern=u'(?u)\b[^\d\W]\w+\b',stop_words=frozenset(stopwords))
    from sklearn.naive_bayes import MultinomialNB
    nb=MultinomialNB()
    from sklearn.pipeline import make_pipeline
    pipe=make_pipeline(vect,nb)
    pipe.fit(X_train.cut_content, y_train)
    y_pred = pipe.predict(X_test.cut_content)
    from sklearn import  metrics
    print(metrics.accuracy_score(y_test,y_pred))
    metrics.confusion_matrix(y_test,y_pred)
    
    0.897216216938
    
    
    
    
    
    array([[6266,  163,    2,  249,    5,  345,   66,   74,   53],
           [   5, 1118,    0,    0,    0,   31,    2,    5,   37],
           [   8,    4,   15,    0,    0,  104,  329,    5,    3],
           [   4,    1,    0, 8230,    0,   64,    6,    1,    0],
           [  59,   29,    0,   10, 3672,   66,   29,   26,   45],
           [  72,   71,    6,   26,    1, 5683,  756,   60,  193],
           [  28,    0,   10,    0,    0,  381, 4275,    0,    2],
           [   9,   90,    0,    5,    1,   74,    5,  890,  132],
           [   2,   38,    1,    2,    0,   44,    1,   11, 3467]], dtype=int64)
    
    • 可以看到朴素贝叶斯对该测试集的正确率达到了接近90%

    • 对训练集进行评估,正确率91%

    y_pred = pipe.predict(X_train.cut_content)
    from sklearn import  metrics
    print(metrics.accuracy_score(y_train,y_pred))
    
    0.913158362989
    
    from sklearn.linear_model import LogisticRegression
    
    • 随后我们使用逻辑回归模型进行拟合模型并对测试集进行预测,测试集准确率达到94%
    lr=LogisticRegression()  
    from sklearn.pipeline import make_pipeline
    pipe=make_pipeline(vect,lr)
    pipe.fit(X_train.cut_content, y_train)
    y_pred = pipe.predict(X_test.cut_content)
    from sklearn import  metrics
    print(metrics.accuracy_score(y_test,y_pred))
    metrics.confusion_matrix(y_test,y_pred)
    
    0.944644620599
    
    
    array([[7079,    3,    3,    5,   19,   62,   27,   10,   15],
           [  43, 1131,    1,    0,    3,    3,    4,    6,    7],
           [  16,    0,   36,    1,    1,  106,  296,    7,    5],
           [   7,    0,    0, 8298,    0,    1,    0,    0,    0],
           [  48,    1,    0,    0, 3870,    9,    2,    1,    5],
           [  60,   12,   22,   14,    9, 6453,  218,   35,   45],
           [  36,    1,  140,    0,    7,  415, 4090,    3,    4],
           [  48,   28,    1,    1,   10,   54,    6, 1008,   50],
           [  44,   12,    0,    1,   10,   38,    4,   29, 3428]], dtype=int64)
    
    from sklearn.tree import DecisionTreeClassifier
    tree=DecisionTreeClassifier(criterion='entropy',random_state=1)
    from sklearn.ensemble import BaggingClassifier
    bag=BaggingClassifier(base_estimator=tree,
                         n_estimators=10,
                         max_samples=1.0,
                         max_features=1.0,
                         bootstrap=True,
                         bootstrap_features=False,
                         n_jobs=4,random_state=1)
    pipe=make_pipeline(vect,bag)
    pipe.fit(X_train.cut_content, y_train)
    y_pred = pipe.predict(X_test.cut_content)
    metrics.accuracy_score(y_test,y_pred)
    
    • 使用bagging的方法将决策树进行ensemble,得到的准确率比逻辑回归低了1%
      0.9294045426642111
    • 通过对混淆矩阵进行分析,我们发现对第三类,也就是business类的误分类较多,后续需要改进的模型
      • 可以使用td-idf进行文本特征处理
      • word2vector与深度学习的方式进行结合,测试文本分类效果
      • LSTM
      • embedding
      • 其他NLP 方法
  • 相关阅读:
    HDOJ2032_杨辉三角
    素数问题练习_HDOJ1262
    素数问题三步曲_HDOJ2098
    小黄衫的故事
    软件工程实践总结
    Beta吐槽
    Beta版本讨论
    Beta版本总结
    Beat版本冲刺(七)
    Beta版本冲刺(六)
  • 原文地址:https://www.cnblogs.com/onemorepoint/p/9530992.html
Copyright © 2011-2022 走看看