以textCNN为例,搭建属于自己的tf风格的深度学习代码_textcnn(vocab_size, embedding_dim, num_classes, fi-程序员宅基地

技术标签: 机器学习  

建议在编写深度学习代码时分成以下几个步骤:

Step 1:编写 网络结构 文件

Step 2:编写输入文件——读写训练集,测试集样本

Step 3:编写 训练网络文件

         3.1:调整 输入 格式

         3.2:具体训练内容——优化函数等

 

第一步:搭建model,即网络的结构,多少个卷积层,多少个池化层,全连接层等等,建议编写一个类如Class TextCNN:

import tensorflow as tf
import numpy as np


class TextCNN(object):
    """
    A CNN for text classification.
    Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer.
    """
    def __init__(
      self, sequence_length, num_classes, vocab_size,
      embedding_size, filter_sizes, num_filters, l2_reg_lambda=0.0):

        # Placeholders for input, output and dropout
        self.input_x = tf.placeholder(tf.int32, [None, sequence_length], name="input_x")
        self.input_y = tf.placeholder(tf.float32, [None, num_classes], name="input_y")
        self.dropout_keep_prob = tf.placeholder(tf.float32, name="dropout_keep_prob")

        # Keeping track of l2 regularization loss (optional)
        l2_loss = tf.constant(0.0)

        # Embedding layer #Embedding 层
        with tf.device('/cpu:0'), tf.name_scope("embedding"):
            self.W = tf.Variable(
                tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0),
                name="W")
            self.embedded_chars = tf.nn.embedding_lookup(self.W, self.input_x)
            self.embedded_chars_expanded = tf.expand_dims(self.embedded_chars, -1)

        # Create a convolution + maxpool layer for each filter size #卷积层 池化层
        pooled_outputs = []
        for i, filter_size in enumerate(filter_sizes):
            with tf.name_scope("conv-maxpool-%s" % filter_size):
                # Convolution Layer
                filter_shape = [filter_size, embedding_size, 1, num_filters]
                W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name="W")
                b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name="b")
                conv = tf.nn.conv2d(
                    self.embedded_chars_expanded,
                    W,
                    strides=[1, 1, 1, 1],
                    padding="VALID",
                    name="conv"
                )
                # Apply nonlinearity
                h = tf.nn.relu(tf.nn.bias_add(conv, b), name="relu")
                # Maxpooling over the outputs
                pooled = tf.nn.max_pool(
                    h,
                    ksize=[1, sequence_length - filter_size + 1, 1, 1],
                    strides=[1, 1, 1, 1],
                    padding='VALID',
                    name="pool"
                )
                pooled_outputs.append(pooled)

        # Combine all the pooled features #连接 所有池化的特征
        num_filters_total = num_filters * len(filter_sizes)
        self.h_pool = tf.concat(pooled_outputs, 3)
        self.h_pool_flat = tf.reshape(self.h_pool, [-1, num_filters_total])

        # Add dropout
        with tf.name_scope("dropout"):
            self.h_drop = tf.nn.dropout(self.h_pool_flat, self.dropout_keep_prob)

        # Final (unnormalized) scores and predictions #最后的BP层
        with tf.name_scope("output"):
            W = tf.get_variable(
                "W",
                shape=[num_filters_total, num_classes],
                initializer=tf.contrib.layers.xavier_initializer())
            b = tf.Variable(tf.constant(0.1, shape=[num_classes]), name="b")
            l2_loss += tf.nn.l2_loss(W)
            l2_loss += tf.nn.l2_loss(b)
            self.scores = tf.nn.xw_plus_b(self.h_drop, W, b, name="scores")
            self.predictions = tf.argmax(self.scores, 1, name="predictions")

        # Calculate mean cross-entropy loss
        with tf.name_scope("loss"):
            losses = tf.nn.softmax_cross_entropy_with_logits(logits=self.scores, labels=self.input_y)
            self.loss = tf.reduce_mean(losses) + l2_reg_lambda * l2_loss

        # Accuracy
        with tf.name_scope("accuracy"):
            correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1))
            self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy")

第二步:编写读写文件(以及其他帮助文件)

def clean_str(string):
    string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string)
    string = re.sub(r"\'s", " \'s", string)
    string = re.sub(r"\'ve", " \'ve", string)
    string = re.sub(r"n\'t", " n\'t", string)
    string = re.sub(r"\'re", " \'re", string)
    string = re.sub(r"\'d", " \'d", string)
    string = re.sub(r"\'ll", " \'ll", string)
    string = re.sub(r",", " , ", string)
    string = re.sub(r"!", " ! ", string)
    string = re.sub(r"\(", " \( ", string)
    string = re.sub(r"\)", " \) ", string)
    string = re.sub(r"\?", " \? ", string)
    string = re.sub(r"\s{2,}", " ", string)
    return string.strip().lower()

def load_data_and_labels(positive_data_file, negative_data_file):
    """
    Loads MR polarity data from files, splits the data into words and generates labels.
    Returns split sentences and labels.
    """
    # Load data from files
    positive_examples = list(open(positive_data_file, "r", encoding='utf-8').readlines())
    positive_examples = [s.strip() for s in positive_examples]
    negative_examples = list(open(negative_data_file, "r", encoding='utf-8').readlines())
    negative_examples = [s.strip() for s in negative_examples]
    # Split by words
    x_text = positive_examples + negative_examples
    x_text = [clean_str(sent) for sent in x_text]
    # Generate labels
    positive_labels = [[0, 1] for _ in positive_examples]
    negative_labels = [[1, 0] for _ in negative_examples]
    y = np.concatenate([positive_labels, negative_labels], 0) 
    return [x_text, y]


def batch_iter(data, batch_size, num_epochs, shuffle=True):
    """
    Generates a batch iterator for a dataset.
    """
    data = np.array(data)
    data_size = len(data)
    num_batches_per_epoch = int((len(data)-1)/batch_size) + 1
    for epoch in range(num_epochs):
        # Shuffle the data at each epoch
        if shuffle:
            shuffle_indices = np.random.permutation(np.arange(data_size))
            shuffled_data = data[shuffle_indices]
        else:
            shuffled_data = data
        
        for batch_num in range(num_batches_per_epoch):
            start_index = batch_num * batch_size
            end_index = min((batch_num + 1) * batch_size, data_size)
            yield shuffled_data[start_index:end_index]

第三步:编写训练文件

3.1:调正输入格式(embedding)

def preprocess():
    # Data Preparation
    # ==================================================

    # Load data
    print("Loading data...")
    x_text, y = data_helpers.load_data_and_labels(FLAGS.positive_data_file, FLAGS.negative_data_file)

    # Build vocabulary
    max_document_length = max([len(x.split(" ")) for x in x_text])
    vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length)
    x = np.array(list(vocab_processor.fit_transform(x_text)))

    # Randomly shuffle data
    np.random.seed(10)
    shuffle_indices = np.random.permutation(np.arange(len(y)))
    x_shuffled = x[shuffle_indices]
    y_shuffled = y[shuffle_indices]

    # Split train/test set
    # TODO: This is very crude, should use cross-validation
    dev_sample_index = -1 * int(FLAGS.dev_sample_percentage * float(len(y)))
    x_train, x_dev = x_shuffled[:dev_sample_index], x_shuffled[dev_sample_index:]
    y_train, y_dev = y_shuffled[:dev_sample_index], y_shuffled[dev_sample_index:]

    del x, y, x_shuffled, y_shuffled

    print("Vocabulary Size: {:d}".format(len(vocab_processor.vocabulary_)))
    print("Train/Dev split: {:d}/{:d}".format(len(y_train), len(y_dev)))
    return x_train, y_train, vocab_processor, x_dev, y_dev

3.2:训练内容

def train(x_train, y_train, vocab_processor, x_dev, y_dev):
    # Training
    # ==================================================

    with tf.Graph().as_default():
        session_conf = tf.ConfigProto( allow_soft_placement=FLAGS.allow_soft_placement, log_device_placement=FLAGS.log_device_placement)
        sess = tf.Session(config=session_conf)
        
        with sess.as_default():
            cnn = TextCNN(
                sequence_length=x_train.shape[1],
                num_classes=y_train.shape[1],
                vocab_size=len(vocab_processor.vocabulary_),
                embedding_size=FLAGS.embedding_dim,
                filter_sizes=list(map(int, FLAGS.filter_sizes.split(","))),
                num_filters=FLAGS.num_filters,
                l2_reg_lambda=FLAGS.l2_reg_lambda
            )

            # Define Training procedure
            global_step = tf.Variable(0, name="global_step", trainable=False)
            optimizer = tf.train.AdamOptimizer(1e-3)
            grads_and_vars = optimizer.compute_gradients(cnn.loss)
            train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step)

            # Keep track of gradient values and sparsity (optional)
            grad_summaries = []
            for g, v in grads_and_vars:
                if g is not None:
                    grad_hist_summary = tf.summary.histogram("{}/grad/hist".format(v.name), g)
                    sparsity_summary = tf.summary.scalar("{}/grad/sparsity".format(v.name), tf.nn.zero_fraction(g))
                    grad_summaries.append(grad_hist_summary)
                    grad_summaries.append(sparsity_summary)
            grad_summaries_merged = tf.summary.merge(grad_summaries)

            # Output directory for models and summaries
            timestamp = str(int(time.time()))
            out_dir = os.path.abspath(os.path.join(os.path.curdir, "runs", timestamp))
            print("Writing to {}\n".format(out_dir))

            # Summaries for loss and accuracy
            loss_summary = tf.summary.scalar("loss", cnn.loss)
            acc_summary = tf.summary.scalar("accuracy", cnn.accuracy)

            # Train Summaries
            train_summary_op = tf.summary.merge([loss_summary, acc_summary, grad_summaries_merged])
            train_summary_dir = os.path.join(out_dir, "summaries", "train")
            train_summary_writer = tf.summary.FileWriter(train_summary_dir, sess.graph)

            # Dev summaries
            dev_summary_op = tf.summary.merge([loss_summary, acc_summary])
            dev_summary_dir = os.path.join(out_dir, "summaries", "dev")
            dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph)

            # Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it
            checkpoint_dir = os.path.abspath(os.path.join(out_dir, "checkpoints"))
            checkpoint_prefix = os.path.join(checkpoint_dir, "model")
            if not os.path.exists(checkpoint_dir):
                os.makedirs(checkpoint_dir)
            saver = tf.train.Saver(tf.global_variables(), max_to_keep=FLAGS.num_checkpoints)

            # Write vocabulary
            vocab_processor.save(os.path.join(out_dir, "vocab"))

            # Initialize all variables
            sess.run(tf.global_variables_initializer())

            def train_step(x_batch, y_batch):
                """
                A single training step
                """
                feed_dict = {
                  cnn.input_x: x_batch,
                  cnn.input_y: y_batch,
                  cnn.dropout_keep_prob: FLAGS.dropout_keep_prob
                }
                _, step, summaries, loss, accuracy = sess.run(
                    [train_op, global_step, train_summary_op, cnn.loss, cnn.accuracy],
                    feed_dict
                )
                time_str = datetime.datetime.now().isoformat()
                print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy))
                train_summary_writer.add_summary(summaries, step)

            def dev_step(x_batch, y_batch, writer=None):
                """
                Evaluates model on a dev set
                """
                feed_dict = {
                  cnn.input_x: x_batch,
                  cnn.input_y: y_batch,
                  cnn.dropout_keep_prob: 1.0
                }
                step, summaries, loss, accuracy = sess.run(
                    [global_step, dev_summary_op, cnn.loss, cnn.accuracy],
                    feed_dict
                )
                time_str = datetime.datetime.now().isoformat()
                print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy))
                if writer:
                    writer.add_summary(summaries, step)

            # Generate batches
            batches = data_helpers.batch_iter(
                list(zip(x_train, y_train)), FLAGS.batch_size, FLAGS.num_epochs)
            # Training loop. For each batch...
            for batch in batches:
                x_batch, y_batch = zip(*batch)
                train_step(x_batch, y_batch)
                current_step = tf.train.global_step(sess, global_step)
                if current_step % FLAGS.evaluate_every == 0:
                    print("\nEvaluation:")
                    dev_step(x_dev, y_dev, writer=dev_summary_writer)
                    print("")
                if current_step % FLAGS.checkpoint_every == 0:
                    path = saver.save(sess, checkpoint_prefix, global_step=current_step)
                    print("Saved model checkpoint to {}\n".format(path))

 

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_36336522/article/details/106527632

智能推荐

Spring 报错:Error creating bean with name的解决方法_error creating bean with name 'org.springframework-程序员宅基地

文章浏览阅读9.7w次,点赞2次,收藏7次。Spring报错:Error creating bean with name的解决方法_error creating bean with name 'org.springframework.transaction.annotation.pr

【白兔兔】用TiKZ画2017高考全国1卷理科数学流程图_2017年高考数学全国一卷的流程图题怎么算-程序员宅基地

文章浏览阅读689次。2017高考全国1卷数学流程图_2017年高考数学全国一卷的流程图题怎么算

ES6—46:class中getter和setter的设置方法_class统一设置setter-程序员宅基地

文章浏览阅读546次。测试代码实现效果_class统一设置setter

python编程用什么软件-python用什么软件编写-程序员宅基地

文章浏览阅读5.2k次。现在,python语言可以说是非常火热的语言之一。很多人开始学习python,下面我将和大家说说,python用什么软件编写。Python开发软件可根据其用途不同分为两种,一种是Python代码编辑器,一种是Python集成开发工具,两者的配合使用可以极大的提高Python开发人员的编程效率,以下是常用的几款Python代码编辑器和Python集成开发工具。一、Python代码编辑器1. Subl..._python敲代码用什么软件

golang基础-接口、接口嵌套、类型断言、接口与结构体_接口等转换_go 结构体转为接口类型-程序员宅基地

文章浏览阅读2.4k次。接口package mainimport "fmt"type Test interface { Print() Sleep()}type Student struct { name string age int score int}/*student实现接口Print方法*/func (p Student) Print() {_go 结构体转为接口类型

通过SSH远程访问puppy linux-程序员宅基地

文章浏览阅读402次。http://fengqing888.blog.163.com/blog/static/3301141620117205563951/ 转载于:https://blog.51cto.com/584250550/1187682_puppy linux ssh

随便推点

JDBC通过文件读取加载方式连接数据库(以MySQL为例)_jdbc 加载本地文件到-程序员宅基地

文章浏览阅读5.5k次。JDBC通过文件读取加载方式连接数据库(以MySQL为例)前言: 在java项目开发中,必然会经常使用到数据库连接,并且数据库的种类也不尽相同,另外JDBC(java DataBase Connectivity :java数据库连接)的方式也有很多种方式。所以本博文是以文件读取加载方式连接数据库,这种方式的好处在于当数据库驱动,地址或者用户名密码发生变动时,只需要在文件里改动即可,而不需要在代码里改_jdbc 加载本地文件到

数值积分中的辛普森方法及其误差估计-程序员宅基地

文章浏览阅读3.3k次。$f$在$(x_0,x_2)$上四阶可导,且在$[x_0,x_2]$上三阶导函数连续.则\begin{equation} \int_{x_0}^{x_2}f(x)dx=\frac{h}{3}[f(x_0)+4f(x_1)+f(x_2)]-\frac{h^5}{90}f^{(4)}(\xi) \end{equation}其中$h=x_1-x_0=x_2-x_1$.证明:我们仍然进行牛顿插..._辛普森公式误差怎么求

面试必问题目“进程、线程对比”,包你会_问什么进程比线程 重量-程序员宅基地

文章浏览阅读103次。简要说明烟雨红尘小说网 https://wap.zuxs.net/在C语言、C++等方向面试时,经常会被问道 进程、线程等问题,当然了10年前我刚开始找工作那会,也是各种煎熬“我又不写操作系统,为什么还要学这么底层的知识”,真想不通面试官是不是sha。。。转眼间,我现在成了面试官,你说可笑不。。。。世事变化无常啊。。。。为了让各位小伙伴把这块理解了,所以趁一个空闲时机把它们的对..._问什么进程比线程 重量

java:枚举:Demo_enumdemo-程序员宅基地

文章浏览阅读1.1w次。 定义Color枚举类:package testEnum;public enum Color { RED(0,"红色"), BLUE(1,"这是蓝色"), YELLOW(2,"这是黄色"), GREEN(3,"这是绿色"); //可以看出这在枚举类型里定义变量和方法和在普通类里面定义方法和变量没有什么区别。 //唯一要注意的只是变量和方法定义必须放在所有枚举值定义..._enumdemo

如何在HBuilder里面运行php文件_hbuilder运行php-程序员宅基地

文章浏览阅读1.7w次,点赞4次,收藏19次。1.首先在HBuilder里面配置外部服务器2.绑定你的项目,即在下面圈选的地方写上你项目的完整路径3.点击下面的图标运行你的项目注意:到此处就成功了。..._hbuilder运行php

使用VScode开发ESP8266,PlatformIO开发ESP8266-程序员宅基地

文章浏览阅读4.6k次,点赞5次,收藏39次。安装arduino扩展首先下载arduino IDE并安装。然后打开VScode安装arduino扩展“File”-“Preference”-“settings”打开设置窗口,输入arduino搜索,往下拉找到arduino Path,把刚才arduino IDE的安装路径复制进去,注意要将 “\” 改为 “/”打开或新建.ino文件,我这里使用自带的Blink例程来测试。打开.ino后,点击右下角来配置编程器、开发板参数、COM口,和在arduino IDE中一样。这些配置和安信_vscode开发esp8266

推荐文章

热门文章

相关标签