搜狐新闻文本分类之CNN(tensorflow版Version1)

注:数据提取码
代码所需训练数据

一、环境配置

python3.6
tensorflow-gpu1.12
Windows10
pycharm

二、代码背景

**1、**结合Character-level Convolutional Networks for Text Classification这篇论文,参考了github上的代码进行学习,github地址
**2、**本篇代码尚未使用词向量模型处理,通过简单的统计出所有文本中高频出现的5000个词的个数,然后根据每篇文章中的词得出相应的词的id,组成一个文本的向量作为输入值

三、代码

**注:**运行时,要在终端运行
(1)先运行python run_cnn.py train
(2)在运行python run_cnn.py test
(3)这个项目一共有三个文件分别为 cnn_model.py(cnn搭建模型)、cnews_loader.py(信息加载)、run_cnn.py(运行文件)
(4)我们需要在同级目录下创建data文件夹、Checkpoint文件夹、tensorboard文件夹
在这里插入图片描述

1、 cnn_model.py文件

import sys
import numpy as np
import tensorflow as tf
from collections import Counter


def read_file(filename):
    #读取文件数据,将每个文本中的每个字分隔开
    contents,labels = [],[]
    with open(filename,mode='r',encoding='utf-8',errors='ignore') as f:
        for line in f:
            try:
                label,content = line.strip().split('\t')
                if content:
                    contents.append(list(content))
                    #将当前文本中的每一个字作为一个字符串分开
                    labels.append(label)
            except:
                pass
    return contents,labels

def build_vocab(train_dir,vocab_dir,vocab_size = 5000):
    #根据训练集构建词汇表存储
    data_train,_ = read_file(train_dir)
    #将每篇文章分为每一个字为一个字符串的链表
    all_data = []
    for content in data_train:
        all_data.extend(content)
        #将所有文本中的内容放在一个链表中
        #在all_data的数组中追加content列表中的内容,将所有内容都放在一个列表中

    counter = Counter(all_data)
    #统计每个字出现的次数
    count_pairs = counter.most_common(vocab_size-1)
    #返回的内容为top(vocab_size-1)的字符和频率
    words,_ = list(zip(*count_pairs))
    #将元组列表解压为列表,只取前top的
    words = ['<PAD>']+list(words)
    # 添加一个<PAD>来将所有的文本pad为同一长度
    open(vocab_dir,mode='w').write('\n'.join(words)+'\n')

def read_vocab(vocab_dir):
    #读取词汇表
    with open(vocab_dir,mode='r',encoding='utf-8',errors='ignore') as fp:
        words = [words.strip() for words in fp.readlines()]
    word_to_id = dict(zip(words,range(len(words))))
    return words,word_to_id

def read_category():
    #读取分类目录,固定
    categories = categories = ['体育', '财经', '房产', '家居', '教育', '科技', '时尚', '时政', '游戏', '娱乐']
    categories = [content for content in categories]

    cat_to_id = dict(zip(categories,range(len(categories))))
    return categories,cat_to_id

def to_words(content,words):
    #将id的内容转化为文字
    return ''.join(words[x] for x in content)

def process_file(filename,word_to_id,cat_to_id,max_lenth = 600):
    #将文件转化为id的表示
    contents,labels = read_file(filename)
    data_id,label_id = [],
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值