├── .gitignore ├── README.md ├── cnn ├── data │ ├── feature_word_10 │ ├── testing.csv │ └── training.csv ├── data_helpers.py ├── eval.py ├── stop_words_ch.txt ├── text_cnn.py └── train.py ├── data ├── testing.csv └── training.csv ├── stop_words_ch.txt └── xgboost_test_classification.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Python template 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | .hypothesis/ 50 | .pytest_cache/ 51 | 52 | # Translations 53 | *.mo 54 | *.pot 55 | 56 | # Django stuff: 57 | *.log 58 | local_settings.py 59 | db.sqlite3 60 | 61 | # Flask stuff: 62 | instance/ 63 | .webassets-cache 64 | 65 | # Scrapy stuff: 66 | .scrapy 67 | 68 | # Sphinx documentation 69 | docs/_build/ 70 | 71 | # PyBuilder 72 | target/ 73 | 74 | # Jupyter Notebook 75 | .ipynb_checkpoints 76 | 77 | # pyenv 78 | .python-version 79 | 80 | # celery beat schedule file 81 | celerybeat-schedule 82 | 83 | # SageMath parsed files 84 | *.sage.py 85 | 86 | # Environments 87 | .env 88 | .venv 89 | env/ 90 | venv/ 91 | ENV/ 92 | env.bak/ 93 | venv.bak/ 94 | 95 | # Spyder project settings 96 | .spyderproject 97 | .spyproject 98 | 99 | # Rope project settings 100 | .ropeproject 101 | 102 | # mkdocs documentation 103 | /site 104 | 105 | # mypy 106 | .mypy_cache/ 107 | .idea/ 108 | Intent-recognition.iml 109 | 110 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuemzhan/Intent-recognition/60088d62bb1b7b442d8a78b474effbe575ff8bdd/README.md -------------------------------------------------------------------------------- /cnn/data/feature_word_10: -------------------------------------------------------------------------------- 1 | 物业管理 2 | 物业 3 | 房地产 4 | 顾问 5 | 中介 6 | 住宅 7 | 商业 8 | 开发商 9 | 招商 10 | 营销策划 11 | 私募 12 | 融资 13 | 金融 14 | 贷款 15 | 基金 16 | 股权 17 | 资产 18 | 小额贷款 19 | 投资 20 | 担保 21 | 软件 22 | 互联网 23 | 平台 24 | 信息化 25 | 软件开发 26 | 数据 27 | 移动 28 | 信息 29 | 系统集成 30 | 运营 31 | 制造 32 | 安装 33 | 设备 34 | 施工 35 | 机械 36 | 工程 37 | 自动化 38 | 工业 39 | 设计 40 | 装备 41 | 药品 42 | 医药 43 | 生物 44 | 原料药 45 | 药物 46 | 试剂 47 | GMP 48 | 片剂 49 | 制剂 50 | 诊断 51 | 材料 52 | 制品 53 | 塑料 54 | 环保 55 | 新型 56 | 化学品 57 | 改性 58 | 助剂 59 | 涂料 60 | 原材料 61 | 养殖 62 | 农业 63 | 种植 64 | 食品 65 | 加工 66 | 龙头企业 67 | 产业化 68 | 饲料 69 | 基地 70 | 深加工 71 | 医疗器械 72 | 医疗 73 | 医院 74 | 医用 75 | 康复 76 | 治疗 77 | 医疗机构 78 | 临床 79 | 护理 80 | 汽车 81 | 零部件 82 | 发动机 83 | 整车 84 | 模具 85 | C36 86 | 配件 87 | 总成 88 | 车型 89 | 媒体 90 | 制作 91 | 策划 92 | 广告 93 | 传播 94 | 创意 95 | 发行 96 | 影视 97 | 电影 98 | 文化 99 | 运输 100 | 物流 101 | 仓储 102 | 货物运输 103 | 货运 104 | 装卸 105 | 配送 106 | 第三方 107 | 供应链 108 | 集装箱 109 | -------------------------------------------------------------------------------- /cnn/data_helpers.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import re 3 | import jieba 4 | 5 | # 读取停词表 6 | def stop_words(): 7 | stop_words_file = open('stop_words_ch.txt', 'r') 8 | stopwords_list = [] 9 | for line in stop_words_file.readlines(): 10 | stopwords_list.append(line[:-1]) 11 | return stopwords_list 12 | 13 | def jieba_fenci(raw, stopwords_list): 14 | # 使用结巴分词把文件进行切分 15 | text = "" 16 | word_list = list(jieba.cut(raw, cut_all=False)) 17 | for word in word_list: 18 | if word not in stopwords_list and word != '\r\n': 19 | text += word 20 | text += ' ' 21 | return text 22 | 23 | def clean_str(string): 24 | """ 25 | Tokenization/string cleaning for all datasets except for SST. 26 | Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py 27 | """ 28 | string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string) 29 | string = re.sub(r"\'s", " \'s", string) 30 | string = re.sub(r"\'ve", " \'ve", string) 31 | string = re.sub(r"n\'t", " n\'t", string) 32 | string = re.sub(r"\'re", " \'re", string) 33 | string = re.sub(r"\'d", " \'d", string) 34 | string = re.sub(r"\'ll", " \'ll", string) 35 | string = re.sub(r",", " , ", string) 36 | string = re.sub(r"!", " ! ", string) 37 | string = re.sub(r"\(", " \( ", string) 38 | string = re.sub(r"\)", " \) ", string) 39 | string = re.sub(r"\?", " \? ", string) 40 | string = re.sub(r"\s{2,}", " ", string) 41 | return string.strip().lower() 42 | 43 | def load_AI100_data_and_labels(data_path, use_pinyin=False): 44 | x_text = [] 45 | y = [] 46 | stopwords_list = stop_words() 47 | with open(data_path, 'r', encoding = 'utf-8') as f: 48 | for line in f: 49 | lable = int(line.split(',')[0]) 50 | one_hot = [0]*11 51 | one_hot[lable-1] = 1 52 | y.append(np.array(one_hot)) 53 | content = "" 54 | for aa in line.split(',')[1:]: 55 | content += aa 56 | text = jieba_fenci(content, stopwords_list) 57 | x_text.append(text) 58 | print ("data load finished") 59 | return [x_text, np.array(y)] 60 | 61 | def batch_iter(data, batch_size, num_epochs, shuffle=True): 62 | """ 63 | Generates a batch iterator for a dataset. 64 | """ 65 | data = np.array(data) 66 | data_size = len(data) 67 | num_batches_per_epoch = int((len(data)-1)/batch_size) + 1 68 | for epoch in range(num_epochs): 69 | # Shuffle the data at each epoch 70 | if shuffle: 71 | shuffle_indices = np.random.permutation(np.arange(data_size)) 72 | shuffled_data = data[shuffle_indices] 73 | else: 74 | shuffled_data = data 75 | for batch_num in range(num_batches_per_epoch): 76 | start_index = batch_num * batch_size 77 | end_index = min((batch_num + 1) * batch_size, data_size) 78 | yield shuffled_data[start_index:end_index] 79 | -------------------------------------------------------------------------------- /cnn/eval.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import numpy as np 3 | import os 4 | import data_helpers 5 | from tensorflow.contrib import learn 6 | 7 | # Eval Parameters 8 | tf.flags.DEFINE_integer("batch_size", 64, "Batch Size (default: 64)") 9 | tf.flags.DEFINE_string("checkpoint_dir", "runs/1524205259/checkpoints", "Checkpoint directory from training run") 10 | tf.flags.DEFINE_boolean("eval_train", True, "Evaluate on all training data") 11 | 12 | # Misc Parameters 13 | tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement") 14 | tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices") 15 | 16 | FLAGS = tf.flags.FLAGS 17 | 18 | print("\nParameters:") 19 | for attr, value in sorted(FLAGS.__flags.items()): 20 | print("{}={}".format(attr.upper(), value)) 21 | print("") 22 | 23 | # CHANGE THIS: Load data. Load your own data here 24 | if FLAGS.eval_train: 25 | x_raw, y_test = data_helpers.load_AI100_data_and_labels('data/testing.csv') 26 | y_test = np.argmax(y_test, axis=1) 27 | else: 28 | x_raw = ["a masterpiece four years in the making", "everything is off."] 29 | y_test = [1, 0] 30 | 31 | # Map data into vocabulary 32 | vocab_path = os.path.join(FLAGS.checkpoint_dir, "..", "vocab") 33 | vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path) 34 | x_test = np.array(list(vocab_processor.transform(x_raw))) 35 | 36 | print("\nEvaluating........\n") 37 | 38 | # Evaluation 39 | # ================================================== 40 | checkpoint_file = tf.train.latest_checkpoint(FLAGS.checkpoint_dir) 41 | graph = tf.Graph() 42 | with graph.as_default(): 43 | session_conf = tf.ConfigProto( 44 | allow_soft_placement=FLAGS.allow_soft_placement, 45 | log_device_placement=FLAGS.log_device_placement) 46 | sess = tf.Session(config=session_conf) 47 | with sess.as_default(): 48 | # Load the saved meta graph and restore variables 49 | saver = tf.train.import_meta_graph("{}.meta".format(checkpoint_file)) 50 | saver.restore(sess, checkpoint_file) 51 | 52 | # Get the placeholders from the graph by name 53 | input_x = graph.get_operation_by_name("input_x").outputs[0] 54 | # input_y = graph.get_operation_by_name("input_y").outputs[0] 55 | dropout_keep_prob = graph.get_operation_by_name("dropout_keep_prob").outputs[0] 56 | 57 | # Tensors we want to evaluate 58 | predictions = graph.get_operation_by_name("output/predictions").outputs[0] 59 | 60 | # Generate batches for one epoch 61 | batches = data_helpers.batch_iter(list(x_test), FLAGS.batch_size, 1, shuffle=False) 62 | 63 | # Collect the predictions here 64 | all_predictions = [] 65 | 66 | for x_test_batch in batches: 67 | batch_predictions = sess.run(predictions, {input_x: x_test_batch, dropout_keep_prob: 1.0}) 68 | all_predictions = np.concatenate([all_predictions, batch_predictions]) 69 | # with open('CNN_OUTPUT.csv', 'w') as f: 70 | # for i, pre in enumerate(all_predictions): 71 | # f.write(str(i+1)) 72 | # f.write(',') 73 | # f.write(str(int(pre) + 1)) 74 | # f.write('\n') 75 | 76 | count = 0 77 | for i in range(len(all_predictions)): 78 | if(all_predictions[i] == y_test[i]): 79 | count += 1 80 | print("正确率为: " + str(float(count / len(all_predictions)))) -------------------------------------------------------------------------------- /cnn/stop_words_ch.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuemzhan/Intent-recognition/60088d62bb1b7b442d8a78b474effbe575ff8bdd/cnn/stop_words_ch.txt -------------------------------------------------------------------------------- /cnn/text_cnn.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import numpy as np 3 | 4 | 5 | class TextCNN(object): 6 | """ 7 | A CNN for text classification. 8 | Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer. 9 | """ 10 | def __init__( 11 | self, sequence_length, num_classes, vocab_size, 12 | embedding_size, filter_sizes, num_filters, l2_reg_lambda=0.0): 13 | 14 | # Placeholders for input, output and dropout 15 | self.input_x = tf.placeholder(tf.int32, [None, sequence_length], name="input_x") 16 | self.input_y = tf.placeholder(tf.float32, [None, num_classes], name="input_y") 17 | self.dropout_keep_prob = tf.placeholder(tf.float32, name="dropout_keep_prob") 18 | 19 | # Keeping track of l2 regularization loss (optional) 20 | l2_loss = tf.constant(0.0) 21 | 22 | # Embedding layer 23 | with tf.device('/cpu:0'), tf.name_scope("embedding"): 24 | self.W = tf.Variable( 25 | tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0), 26 | name="W") 27 | self.embedded_chars = tf.nn.embedding_lookup(self.W, self.input_x) 28 | self.embedded_chars_expanded = tf.expand_dims(self.embedded_chars, -1) 29 | 30 | # Create a convolution + maxpool layer for each filter size 31 | pooled_outputs = [] 32 | for i, filter_size in enumerate(filter_sizes): 33 | with tf.name_scope("conv-maxpool-%s" % filter_size): 34 | # Convolution Layer 35 | filter_shape = [filter_size, embedding_size, 1, num_filters] 36 | W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name="W") 37 | b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name="b") 38 | conv = tf.nn.conv2d( 39 | self.embedded_chars_expanded, 40 | W, 41 | strides=[1, 1, 1, 1], 42 | padding="VALID", 43 | name="conv") 44 | # Apply nonlinearity 45 | h = tf.nn.relu(tf.nn.bias_add(conv, b), name="relu") 46 | # Maxpooling over the outputs 47 | pooled = tf.nn.max_pool( 48 | h, 49 | ksize=[1, sequence_length - filter_size + 1, 1, 1], 50 | strides=[1, 1, 1, 1], 51 | padding='VALID', 52 | name="pool") 53 | pooled_outputs.append(pooled) 54 | 55 | # Combine all the pooled features 56 | num_filters_total = num_filters * len(filter_sizes) 57 | self.h_pool = tf.concat(pooled_outputs, 3) 58 | self.h_pool_flat = tf.reshape(self.h_pool, [-1, num_filters_total]) 59 | 60 | # Add dropout 61 | with tf.name_scope("dropout"): 62 | self.h_drop = tf.nn.dropout(self.h_pool_flat, self.dropout_keep_prob) 63 | 64 | # Final (unnormalized) scores and predictions 65 | with tf.name_scope("output"): 66 | W = tf.get_variable( 67 | "W", 68 | shape=[num_filters_total, num_classes], 69 | initializer=tf.contrib.layers.xavier_initializer()) 70 | b = tf.Variable(tf.constant(0.1, shape=[num_classes]), name="b") 71 | l2_loss += tf.nn.l2_loss(W) 72 | l2_loss += tf.nn.l2_loss(b) 73 | self.scores = tf.nn.xw_plus_b(self.h_drop, W, b, name="scores") 74 | self.predictions = tf.argmax(self.scores, 1, name="predictions") 75 | 76 | # CalculateMean cross-entropy loss 77 | with tf.name_scope("loss"): 78 | losses = tf.nn.softmax_cross_entropy_with_logits(logits=self.scores, labels=self.input_y) 79 | self.loss = tf.reduce_mean(losses) + l2_reg_lambda * l2_loss 80 | 81 | # Accuracy 82 | with tf.name_scope("accuracy"): 83 | correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1)) 84 | self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy") 85 | -------------------------------------------------------------------------------- /cnn/train.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import numpy as np 3 | import os 4 | import time 5 | import datetime 6 | import data_helpers 7 | from text_cnn import TextCNN 8 | from tensorflow.contrib import learn 9 | 10 | # Data loading params 11 | tf.flags.DEFINE_float("dev_sample_percentage", .1, "Percentage of the training data to use for validation") 12 | 13 | # Model Hyperparameters 14 | tf.flags.DEFINE_integer("embedding_dim", 128, "Dimensionality of character embedding (default: 128)") 15 | tf.flags.DEFINE_string("filter_sizes", "3,4,5", "Comma-separated filter sizes (default: '3,4,5')") 16 | tf.flags.DEFINE_integer("num_filters", 128, "Number of filters per filter size (default: 128)") 17 | tf.flags.DEFINE_float("dropout_keep_prob", 0.5, "Dropout keep probability (default: 0.5)") 18 | tf.flags.DEFINE_float("l2_reg_lambda", 0.0, "L2 regularization lambda (default: 0.0)") 19 | 20 | # Training parameters 21 | tf.flags.DEFINE_integer("batch_size", 64, "Batch Size (default: 64)") 22 | tf.flags.DEFINE_integer("num_epochs", 1, "Number of training epochs (default: 200)") 23 | tf.flags.DEFINE_integer("evaluate_every", 100, "Evaluate model on dev set after this many steps (default: 100)") 24 | tf.flags.DEFINE_integer("checkpoint_every", 10, "Save model after this many steps (default: 100)") 25 | tf.flags.DEFINE_integer("num_checkpoints", 5, "Number of checkpoints to store (default: 5)") 26 | # Misc Parameters 27 | tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement") 28 | tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices") 29 | 30 | FLAGS = tf.flags.FLAGS 31 | 32 | print("\nParameters:") 33 | for attr, value in sorted(FLAGS.__flags.items()): 34 | print("{}={}".format(attr.upper(), value)) 35 | print("") 36 | 37 | 38 | # Data Preparation 39 | # ================================================== 40 | 41 | # Load data 42 | print("Loading data...") 43 | x_text, y = data_helpers.load_AI100_data_and_labels('data/training.csv') 44 | 45 | # Build vocabulary 46 | max_document_length = max([len(x.split(" ")) for x in x_text]) 47 | vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length) 48 | x = np.array(list(vocab_processor.fit_transform(x_text))) 49 | 50 | # Randomly shuffle data 51 | np.random.seed(10) 52 | shuffle_indices = np.random.permutation(np.arange(len(y))) 53 | x_shuffled = x[shuffle_indices] 54 | y_shuffled = y[shuffle_indices] 55 | 56 | # Split train/test set 57 | # TODO: This is very crude, should use cross-validation 58 | dev_sample_index = -1 * int(FLAGS.dev_sample_percentage * float(len(y))) 59 | x_train, x_dev = x_shuffled[:dev_sample_index], x_shuffled[dev_sample_index:] 60 | y_train, y_dev = y_shuffled[:dev_sample_index], y_shuffled[dev_sample_index:] 61 | print("Vocabulary Size: {:d}".format(len(vocab_processor.vocabulary_))) 62 | print("Train/Dev split: {:d}/{:d}".format(len(y_train), len(y_dev))) 63 | 64 | 65 | # Training 66 | # ================================================== 67 | 68 | with tf.Graph().as_default(): 69 | session_conf = tf.ConfigProto( 70 | allow_soft_placement=FLAGS.allow_soft_placement, 71 | log_device_placement=FLAGS.log_device_placement) 72 | sess = tf.Session(config=session_conf) 73 | with sess.as_default(): 74 | cnn = TextCNN( 75 | sequence_length=x_train.shape[1], 76 | num_classes=y_train.shape[1], 77 | vocab_size=len(vocab_processor.vocabulary_), 78 | embedding_size=FLAGS.embedding_dim, 79 | filter_sizes=list(map(int, FLAGS.filter_sizes.split(","))), 80 | num_filters=FLAGS.num_filters, 81 | l2_reg_lambda=FLAGS.l2_reg_lambda) 82 | 83 | # Define Training procedure 84 | global_step = tf.Variable(0, name="global_step", trainable=False) 85 | optimizer = tf.train.AdamOptimizer(1e-3) 86 | grads_and_vars = optimizer.compute_gradients(cnn.loss) 87 | train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step) 88 | 89 | # Keep track of gradient values and sparsity (optional) 90 | grad_summaries = [] 91 | for g, v in grads_and_vars: 92 | if g is not None: 93 | grad_hist_summary = tf.summary.histogram("{}/grad/hist".format(v.name), g) 94 | sparsity_summary = tf.summary.scalar("{}/grad/sparsity".format(v.name), tf.nn.zero_fraction(g)) 95 | grad_summaries.append(grad_hist_summary) 96 | grad_summaries.append(sparsity_summary) 97 | grad_summaries_merged = tf.summary.merge(grad_summaries) 98 | 99 | # Output directory for models and summaries 100 | timestamp = str(int(time.time())) 101 | out_dir = os.path.abspath(os.path.join(os.path.curdir, "runs", timestamp)) 102 | print("Writing to {}\n".format(out_dir)) 103 | 104 | # Summaries for loss and accuracy 105 | loss_summary = tf.summary.scalar("loss", cnn.loss) 106 | acc_summary = tf.summary.scalar("accuracy", cnn.accuracy) 107 | 108 | # Train Summaries 109 | train_summary_op = tf.summary.merge([loss_summary, acc_summary, grad_summaries_merged]) 110 | train_summary_dir = os.path.join(out_dir, "summaries", "train") 111 | train_summary_writer = tf.summary.FileWriter(train_summary_dir, sess.graph) 112 | 113 | # Dev summaries 114 | dev_summary_op = tf.summary.merge([loss_summary, acc_summary]) 115 | dev_summary_dir = os.path.join(out_dir, "summaries", "dev") 116 | dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph) 117 | 118 | # Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it 119 | checkpoint_dir = os.path.abspath(os.path.join(out_dir, "checkpoints")) 120 | checkpoint_prefix = os.path.join(checkpoint_dir, "model") 121 | if not os.path.exists(checkpoint_dir): 122 | os.makedirs(checkpoint_dir) 123 | saver = tf.train.Saver(tf.global_variables(), max_to_keep=FLAGS.num_checkpoints) 124 | 125 | # Write vocabulary 126 | vocab_processor.save(os.path.join(out_dir, "vocab")) 127 | 128 | # Initialize all variables 129 | sess.run(tf.global_variables_initializer()) 130 | 131 | def train_step(x_batch, y_batch): 132 | """ 133 | A single training step 134 | """ 135 | feed_dict = { 136 | cnn.input_x: x_batch, 137 | cnn.input_y: y_batch, 138 | cnn.dropout_keep_prob: FLAGS.dropout_keep_prob 139 | } 140 | _, step, summaries, loss, accuracy = sess.run( 141 | [train_op, global_step, train_summary_op, cnn.loss, cnn.accuracy], 142 | feed_dict) 143 | time_str = datetime.datetime.now().isoformat() 144 | print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy)) 145 | train_summary_writer.add_summary(summaries, step) 146 | 147 | def dev_step(x_batch, y_batch, writer=None): 148 | """ 149 | Evaluates model on a dev set 150 | """ 151 | feed_dict = { 152 | cnn.input_x: x_batch, 153 | cnn.input_y: y_batch, 154 | cnn.dropout_keep_prob: 1.0 155 | } 156 | step, summaries, loss, accuracy = sess.run( 157 | [global_step, dev_summary_op, cnn.loss, cnn.accuracy], 158 | feed_dict) 159 | time_str = datetime.datetime.now().isoformat() 160 | print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy)) 161 | if writer: 162 | writer.add_summary(summaries, step) 163 | 164 | # Generate batches 165 | batches = data_helpers.batch_iter( 166 | list(zip(x_train, y_train)), FLAGS.batch_size, FLAGS.num_epochs) 167 | # Training loop. For each batch... 168 | for batch in batches: 169 | x_batch, y_batch = zip(*batch) 170 | train_step(x_batch, y_batch) 171 | current_step = tf.train.global_step(sess, global_step) 172 | if current_step % FLAGS.evaluate_every == 0: 173 | print("\nEvaluation:") 174 | dev_step(x_dev, y_dev, writer=dev_summary_writer) 175 | print("") 176 | if current_step % FLAGS.checkpoint_every == 0: 177 | path = saver.save(sess, checkpoint_prefix, global_step=current_step) 178 | print("Saved model checkpoint to {}\n".format(path)) 179 | -------------------------------------------------------------------------------- /stop_words_ch.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuemzhan/Intent-recognition/60088d62bb1b7b442d8a78b474effbe575ff8bdd/stop_words_ch.txt -------------------------------------------------------------------------------- /xgboost_test_classification.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import xgboost as xgb 3 | import csv 4 | import jieba 5 | import numpy as np 6 | from sklearn.feature_extraction.text import CountVectorizer 7 | from sklearn.feature_extraction.text import TfidfTransformer 8 | 9 | # 读取训练集 10 | def readtrain(path): 11 | with open(path, 'rt', encoding="utf-8") as csvfile: 12 | reader = csv.reader(csvfile) 13 | column1 = [row for row in reader] 14 | content_train = [i[1] for i in column1] # 第一列为文本内容,并去除列名 15 | opinion_train = [int(i[0])-1 for i in column1] # 第二列为类别,并去除列名 16 | print('训练集有 %s 条句子' % len(content_train)) 17 | train = [content_train, opinion_train] 18 | return train 19 | 20 | def stop_words(): 21 | stop_words_file = open('stop_words_ch.txt', 'r') 22 | stopwords_list = [] 23 | for line in stop_words_file.readlines(): 24 | stopwords_list.append(line[:-1]) 25 | return stopwords_list 26 | 27 | # 对列表进行分词并用空格连接 28 | def segmentWord(cont): 29 | stopwords_list = stop_words() 30 | c = [] 31 | for i in cont: 32 | text = "" 33 | word_list = list(jieba.cut(i, cut_all=False)) 34 | for word in word_list: 35 | if word not in stopwords_list and word != '\r\n': 36 | text += word 37 | text += ' ' 38 | c.append(text) 39 | return c 40 | 41 | def segmentWord1(cont): 42 | c = [] 43 | for i in cont: 44 | a = list(jieba.cut(i)) 45 | b = " ".join(a) 46 | c.append(b) 47 | return c 48 | 49 | if __name__ == '__main__': 50 | train = readtrain('data/training.csv') 51 | train_content = segmentWord1(train[0]) 52 | train_opinion = np.array(train[1]) # 需要numpy格式 53 | print("train data load finished") 54 | test = readtrain('data/testing.csv') 55 | test_content = segmentWord(test[0]) 56 | print('test data load finished') 57 | 58 | vectorizer = CountVectorizer() 59 | tfidftransformer = TfidfTransformer() 60 | tfidf = tfidftransformer.fit_transform(vectorizer.fit_transform(train_content)) 61 | weight = tfidf.toarray() 62 | print(tfidf.shape) 63 | test_tfidf = tfidftransformer.transform(vectorizer.transform(test_content)) 64 | test_weight = test_tfidf.toarray() 65 | print(test_weight.shape) 66 | 67 | dtrain = xgb.DMatrix(weight, label=train_opinion) 68 | dtest = xgb.DMatrix(test_weight) # label可以不要,此处需要是为了测试效果 69 | param = {'max_depth':6, 'eta':0.5, 'eval_metric':'merror', 'silent':1, 'objective':'multi:softmax', 'num_class':11} # 参数 70 | evallist = [(dtrain,'train')] # 这步可以不要,用于测试效果 71 | num_round = 20 # 循环次数 72 | bst = xgb.train(param, dtrain, num_round, evallist) 73 | preds = bst.predict(dtest) 74 | 75 | count = 0 76 | for i in range(len(preds)): 77 | if(preds[i] == test[1][i]): 78 | count += 1 79 | print("正确率为: " + str(float(count/len(preds)))) 80 | 81 | ''' 82 | with open('XGBOOST_OUTPUT.csv', 'w') as f: 83 | for i, pre in enumerate(preds): 84 | f.write(str(test[1][i])) 85 | f.write(',') 86 | f.write(str(int(pre))) 87 | f.write('\n') 88 | ''' --------------------------------------------------------------------------------