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 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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
| import json import codecs import pandas as pd import numpy as np from keras_bert import load_trained_model_from_checkpoint, Tokenizer from keras.layers import * from keras.models import Model from keras.optimizers import Adam
maxlen = 300 BATCH_SIZE = 8 config_path = './chinese_L-12_H-768_A-12/bert_config.json' checkpoint_path = './chinese_L-12_H-768_A-12/bert_model.ckpt' dict_path = './chinese_L-12_H-768_A-12/vocab.txt'
token_dict = {} with codecs.open(dict_path, 'r', 'utf-8') as reader: for line in reader: token = line.strip() token_dict[token] = len(token_dict)
class OurTokenizer(Tokenizer): def _tokenize(self, text): R = [] for c in text: if c in self._token_dict: R.append(c) else: R.append('[UNK]') return R
tokenizer = OurTokenizer(token_dict)
def seq_padding(X, padding=0): L = [len(x) for x in X] ML = max(L) return np.array([ np.concatenate([x, [padding] * (ML - len(x))]) if len(x) < ML else x for x in X ])
class DataGenerator:
def __init__(self, data, batch_size=BATCH_SIZE): self.data = data self.batch_size = batch_size self.steps = len(self.data) // self.batch_size if len(self.data) % self.batch_size != 0: self.steps += 1
def __len__(self): return self.steps
def __iter__(self): while True: idxs = list(range(len(self.data))) np.random.shuffle(idxs) X1, X2, Y = [], [], [] for i in idxs: d = self.data[i] text = d[0][:maxlen] x1, x2 = tokenizer.encode(first=text) y = d[1] X1.append(x1) X2.append(x2) Y.append(y) if len(X1) == self.batch_size or i == idxs[-1]: X1 = seq_padding(X1) X2 = seq_padding(X2) Y = seq_padding(Y) yield [X1, X2], Y [X1, X2, Y] = [], [], []
def create_cls_model(num_labels): bert_model = load_trained_model_from_checkpoint(config_path, checkpoint_path, seq_len=None)
for layer in bert_model.layers: layer.trainable = True
x1_in = Input(shape=(None,)) x2_in = Input(shape=(None,))
x = bert_model([x1_in, x2_in]) cls_layer = Lambda(lambda x: x[:, 0])(x) p = Dense(num_labels, activation='softmax')(cls_layer)
model = Model([x1_in, x2_in], p) model.compile( loss='categorical_crossentropy', optimizer=Adam(1e-5), metrics=['accuracy'] )
return model
if __name__ == '__main__':
print("begin data processing...") train_df = pd.read_csv("data/cnews/cnews_train.csv").fillna(value="") test_df = pd.read_csv("data/cnews/cnews_test.csv").fillna(value="")
labels = train_df["label"].unique() with open("label.json", "w", encoding="utf-8") as f: f.write(json.dumps(dict(zip(range(len(labels)), labels)), ensure_ascii=False, indent=2))
train_data = [] test_data = [] for i in range(train_df.shape[0]): label, content = train_df.iloc[i, :] label_id = [0] * len(labels) for j, _ in enumerate(labels): if _ == label: label_id[j] = 1 train_data.append((content, label_id))
for i in range(test_df.shape[0]): label, content = test_df.iloc[i, :] label_id = [0] * len(labels) for j, _ in enumerate(labels): if _ == label: label_id[j] = 1 test_data.append((content, label_id))
print("finish data processing!")
model = create_cls_model(len(labels)) train_D = DataGenerator(train_data) test_D = DataGenerator(test_data)
print("begin model training...") model.fit_generator( train_D.__iter__(), steps_per_epoch=len(train_D), epochs=3, validation_data=test_D.__iter__(), validation_steps=len(test_D) )
print("finish model training!")
model.save('cls_cnews.h5') print("Model saved!")
result = model.evaluate_generator(test_D.__iter__(), steps=len(test_D)) print("模型评估结果:", result)
|