{"id":8,"date":"2024-09-28T17:54:05","date_gmt":"2024-09-28T09:54:05","guid":{"rendered":"http:\/\/www.xtmouse.top\/?p=8"},"modified":"2024-09-28T21:44:07","modified_gmt":"2024-09-28T13:44:07","slug":"%e5%9f%ba%e4%ba%8etransformer%e7%9a%84%e7%ab%8b%e5%9c%ba%e6%a3%80%e6%b5%8b","status":"publish","type":"post","link":"http:\/\/www.xtmouse.top\/index.php\/2024\/09\/28\/%e5%9f%ba%e4%ba%8etransformer%e7%9a%84%e7%ab%8b%e5%9c%ba%e6%a3%80%e6%b5%8b\/","title":{"rendered":"\u57fa\u4e8etransformer\u7684\u7acb\u573a\u68c0\u6d4b"},"content":{"rendered":"\n<p>\u57fa\u4e8etransformer\u6a21\u578b\u7684\u7acb\u573a\u68c0\u6d4b\u7b97\u6cd5\uff0c\u6d89\u53ca\u5230\u65b0\u7586\u68c9\u6570\u636e\u96c6\uff0c\u53ef\u8054\u7cfb\u535a\u4e3b\u83b7\u53d6<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\nimport torch  \nfrom torch.utils.data import DataLoader, RandomSampler, SequentialSampler  \nfrom transformers import BertTokenizer, BertForSequenceClassification, AdamW, get_linear_schedule_with_warmup  \nfrom transformers import DataCollatorWithPadding  \nfrom sklearn.model_selection import train_test_split  \nimport tqdm as tqdm\nimport pandas as pd\nimport numpy as np\nfrom sklearn.metrics import accuracy_score, classification_report  \n\n\nimport pandas as pd\nimport numpy as np\nimport random\nfrom sklearn.model_selection import StratifiedKFold\nfrom tqdm import tqdm\nimport tensorflow as tf\nimport tensorflow.python.keras.backend as K\nfrom tensorflow.keras.utils import to_categorical\n#from keras.utils import to_categorical\n\nimport re\nimport os\nimport gc\ngc.collect()\nimport keras\nimport pandas as pd\nimport codecs, gc\nimport numpy as np\nfrom sklearn.model_selection import KFold\nfrom keras_bert import load_trained_model_from_checkpoint, Tokenizer\nfrom keras.metrics import top_k_categorical_accuracy\nfrom keras.layers import *\nfrom keras.callbacks import *\nfrom keras.models import Model\nimport keras.backend as K\nfrom sqlalchemy import create_engine  \nimport pymysql \nfrom keras.initializers import glorot_uniform\n\n\ndef textAll(data):\n    for i in tqdm(range(len(data))):  \n        data.loc&#91;i, 'all'] = str(data.loc&#91;i, 'target']) + ',' + str(data.loc&#91;i, 'text'])\n    return data\n\n\n\nBERT_PATH='.\/my_bert_base\/'\nmaxlen = 200\n\n\n#\u4ece\u6570\u636e\u5e93\u4e2d\u8bfb\u53d6\u8bad\u7ec3\u96c6\u548c\u6d4b\u8bd5\u96c6\n# \u521b\u5efa\u6570\u636e\u5e93\u5f15\u64ce  \nDATABASE_URL = \"mysql+pymysql:\/\/root:123456@localhost\/doubanmovie\"  \nengine = create_engine(DATABASE_URL)  \n  \n# \u4f7f\u7528SQLAlchemy\u4eceTexts\u8868\u4e2d\u8bfb\u53d6target, text, stance\u4e09\u5217  \nquery = \"SELECT target, text, stance FROM Texts\"  \ndf = pd.read_sql(query, engine)  \n  \n# \u5047\u8bbe\u6211\u4eec\u60f3\u8981\u5c06\u6570\u636e\u768480%\u7528\u4f5c\u8bad\u7ec3\u96c6\uff0c20%\u7528\u4f5c\u6d4b\u8bd5\u96c6  \ntrain_ratio = 0.8  \ntest_ratio = 0.2  \n  \n# \u6253\u4e71\u6570\u636e\u987a\u5e8f  \ndf = df.sample(frac=1, random_state=42)  # random_state\u7528\u4e8e\u786e\u4fdd\u6bcf\u6b21\u6253\u4e71\u7684\u7ed3\u679c\u4e00\u81f4  \n  \n# \u5206\u5272\u6570\u636e\u4e3a\u8bad\u7ec3\u96c6\u548c\u6d4b\u8bd5\u96c6  \ndf_train = df.head(int(train_ratio * len(df)))  \ndf_test = df.tail(int(test_ratio * len(df)))  \n\n#\u7528csv\u6765\u8bfb\u53d6\u8bad\u7ec3\u96c6\u548c\u6d4b\u8bd5\u96c6\n#df_train = pd.read_csv('C:\/Users\/\u8096\u5929\/Desktop\/Xinx.csv',sep=',',engine='python',encoding='utf-8').astype(str)\n#df_test = pd.read_csv('C:\/Users\/\u8096\u5929\/Desktop\/Sub_Xinx.csv',sep=',',engine='python',encoding='utf8').astype(str)\n\ndf_train = textAll(df_train)\ndf_test = textAll(df_test)\n\ndf_train&#91;'long'] = df_train&#91;'all'].apply(lambda x: len(x))\ndf_test&#91;'long'] = df_test&#91;'all'].apply(lambda x: len(x))\ninput_categories = 'all'\noutput_categories = 'stance'\n\ndf_train = df_train&#91;df_train&#91;output_categories].isin(&#91;'FAVOR', 'AGAINST', 'NONE'])]\n\n\ndef label(x):\n    if x == 'FAVOR':\n        return 2\n    if x == 'NONE':\n        return 1\n    if x == 'AGAINST':\n        return 0\n\n\ndf_train.stance = df_train.stance.apply(lambda x: label(x))  # \u5c06\u60c5\u611f\u8f6c\u4e3a\u6570\u5b57\u8868\u793a\n\n\n# 1. \u51c6\u5907\u6570\u636e  \n#train_texts, train_labels, val_texts, val_labels = load_data()  # \u8fd9\u91cc\u4f60\u9700\u8981\u5b9e\u73b0\u52a0\u8f7d\u6570\u636e\u7684\u51fd\u6570  \n  \nprint('\u52a0\u8f7d\u9884\u8bad\u7ec3\u7684BERT tokenizer')\n#\u9884\u8bad\u7ec3\u597d\u7684\u6a21\u578b\nconfig_path = BERT_PATH + 'bert_config.json'\ncheckpoint_path = BERT_PATH + 'bert_model.ckpt'\ndict_path = BERT_PATH + 'vocab.txt'\n\n# \u5c06\u8bcd\u8868\u4e2d\u7684\u8bcd\u7f16\u53f7\u8f6c\u6362\u4e3a\u5b57\u5178\ntoken_dict = {}\nwith codecs.open(dict_path, 'r', 'utf8') as reader:\n    for line in reader:\n        token = line.strip()\n        token_dict&#91;token] = len(token_dict)\n\n\ntokenizer = BertTokenizer.from_pretrained(BERT_PATH) \n  \nprint('\u5bf9\u6570\u636e\u8fdb\u884c\u7f16\u7801')\ndef tokenize_and_encode(texts, labels, tokenizer, max_length=128):  \n    input_ids = &#91;]  \n    attention_masks = &#91;]  \n\n    for text in texts:  \n        encoded_dict = tokenizer.encode_plus(  \n            text,                      # Sentence to encode.  \n            add_special_tokens=True,   # Add '&#91;CLS]' and '&#91;SEP]'  \n            padding='max_length',\n            max_length=max_length,           # Pad &amp; truncate all sentences.  \n            return_attention_mask=True,   # Construct attn. masks.  \n            return_tensors='pt',     # Return pytorch tensors.  \n        )  \n        input_ids.append(encoded_dict&#91;'input_ids'])  \n        attention_masks.append(encoded_dict&#91;'attention_mask']) \n    for i, tensor in enumerate(input_ids):  \n        if tensor.size(1) > 128:  # \u5047\u8bbe\u9664\u4e86\u7ef4\u5ea60\u4e4b\u5916\uff0c\u9700\u8981\u5339\u914d\u7684\u7ef4\u5ea6\u662f1  \n            tensor = tensor&#91;:, :128]  # \u622a\u65ad\u5f20\u91cf\u5230\u957f\u5ea6128\n            input_ids&#91;i] = tensor\n        \n    for i, tensor in enumerate(attention_masks):  \n        if tensor.size(1) > 128:  # \u5047\u8bbe\u9664\u4e86\u7ef4\u5ea60\u4e4b\u5916\uff0c\u9700\u8981\u5339\u914d\u7684\u7ef4\u5ea6\u662f1  \n            tensor = tensor&#91;:, :128]  # \u622a\u65ad\u5f20\u91cf\u5230\u957f\u5ea6128\n            attention_masks&#91;i] = tensor\n    \n\n    input_ids = torch.cat(input_ids, dim=0)  \n    attention_masks = torch.cat(attention_masks, dim=0)  \n    labels = torch.tensor(labels)   \n    return input_ids, attention_masks, labels  \n\n\ntrain_input_ids, train_attention_masks, train_labels = tokenize_and_encode(df_train&#91;'text'], df_train&#91;'stance'], tokenizer)  \nval_input_ids, val_attention_masks, val_labels = tokenize_and_encode(df_train&#91;'text'], df_train&#91;'stance'], tokenizer)  \n  \nprint('\u5b9a\u4e49\u6570\u636e\u52a0\u8f7d\u5668') \ntrain_dataset = torch.utils.data.TensorDataset(train_input_ids, train_attention_masks, train_labels)  \nval_dataset = torch.utils.data.TensorDataset(val_input_ids, val_attention_masks, val_labels)  \n  \ntrain_sampler = RandomSampler(train_dataset)  \ntrain_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=16)  \n  \nval_sampler = SequentialSampler(val_dataset)  \nval_dataloader = DataLoader(val_dataset, sampler=val_sampler, batch_size=64)  \n  \nprint('\u52a0\u8f7d\u9884\u8bad\u7ec3\u7684BERT\u6a21\u578b\u548c\u5b9a\u4e49\u6a21\u578b')\nmodel = BertForSequenceClassification.from_pretrained(BERT_PATH)  \n \nprint('\u8bad\u7ec3\u6a21\u578b')  \ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")  \nmodel.to(device)  \n  \noptimizer = AdamW(model.parameters(), lr=2e-5, eps=1e-8)  \nepochs = 3\n  \nscheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=0, num_training_steps=len(train_dataloader)*epochs)  \n\nnum_batches = len(train_dataloader)  \nprint(f\"\u603b\u5171\u6709 {num_batches} \u4e2a\u6279\uff08batches\uff09\u5728\u8bad\u7ec3\u6570\u636e\u96c6\u4e2d\u3002\") \nval_num_batches = len(val_dataloader)  \nprint(f\"\u603b\u5171\u6709 {num_batches} \u4e2a\u6279\uff08batches\uff09\u5728\u6d4b\u8bd5\u6570\u636e\u96c6\u4e2d\u3002\") \n# \u8bad\u7ec3\u51fd\u6570  \ndef train(model, train_dataloader, optimizer, epoch):  \n    model.train()  \n    # \u521b\u5efa\u635f\u5931\u51fd\u6570\uff08\u4f8b\u5982\uff0c\u5bf9\u4e8e\u591a\u5206\u7c7b\u4efb\u52a1\uff0c\u4f7f\u7528\u4ea4\u53c9\u71b5\u635f\u5931\uff09  \n    criterion = torch.nn.CrossEntropyLoss()   \n    \n    pbar = tqdm(train_dataloader, desc=f'Epoch {epoch+1}\/{...}')  # \u5047\u8bbe\u4f60\u77e5\u9053\u603b\u5171\u7684epoch\u6570\uff0c\u5426\u5219\u8fd9\u91cc\u53ef\u4ee5\u662f\u5360\u4f4d\u7b26  \n\n    for i,batch in enumerate(pbar):  \n        b_input_ids = batch&#91;0].to(device)  \n        b_attention_mask = batch&#91;1].to(device)  \n        b_labels = batch&#91;2].to(device)  \n        \n        pbar.set_description(f'Epoch {epoch+1}\/{...} - Batch {i+1}\/{len(train_dataloader)}')  \n        \n        if i>num_batches:\n            break\n        \n        model.zero_grad()  \n        outputs = model(b_input_ids, attention_mask=b_attention_mask)  \n        logits = outputs&#91;0]  # \u8fd9\u53ef\u80fd\u56e0\u4f60\u7684\u6a21\u578b\u548c\u4efb\u52a1\u800c\u5f02  \n        padded_logits = torch.cat((logits, torch.zeros(16, 1)), dim=1)  \n        \n         \n        # \u8ba1\u7b97\u635f\u5931\uff08\u73b0\u5728\u4f20\u9012labels\u7ed9\u635f\u5931\u51fd\u6570\uff09  \n        loss = criterion(padded_logits, b_labels)  \n        #loss = outputs.loss  \n        loss.backward()  \n        optimizer.step()  \n  \n# \u8bc4\u4f30\u51fd\u6570  \ndef evaluate(model, data_loader):  \n    model.eval()  \n    predictions = &#91;]  \n    true_labels = &#91;]  \n    \n    i=0\n    with torch.no_grad():  \n        for batch in data_loader:  \n            b_input_ids = batch&#91;0].to(device)  \n            b_attention_mask = batch&#91;1].to(device)  \n            b_labels = batch&#91;2].to(device)  \n            \n            i+=1\n            print(i)\n            if i>val_num_batches:\n                break\n            \n            outputs = model(b_input_ids, attention_mask=b_attention_mask)  \n            logits = outputs.logits  \n            preds = torch.argmax(logits, dim=1).flatten().cpu().tolist()  \n  \n            predictions.extend(preds)  \n            true_labels.extend(b_labels.cpu().numpy())  \n  \n    return accuracy_score(true_labels, predictions), classification_report(true_labels, predictions)  \n  \n#\u8bad\u7ec3\u5faa\u73af  \nfor epoch in range(epochs):  \n    train(model, train_dataloader, optimizer, epoch)  \n    print(f'Epoch {epoch+1}\/{epochs}')  \n    acc, report = evaluate(model, val_dataloader)  \n    print(f'Test Accuracy: {acc:.4f}')  \n    print(report)\ntorch.save(model, 'model.pth')\n\n\n#\u8bc4\u4f30\u6a21\u578b\nmodel_xt = torch.load('model.pth')  \nmodel_xt.eval()  # \u8bbe\u7f6e\u6a21\u578b\u4e3a\u8bc4\u4f30\u6a21\u5f0f  \n  \nacc, report = evaluate(model_xt, val_dataloader)  \nprint(f'Test Accuracy: {acc:.4f}')  \nprint(report)\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>\u57fa\u4e8etransformer\u6a21\u578b\u7684\u7acb\u573a\u68c0\u6d4b\u7b97\u6cd5\uff0c\u6d89\u53ca\u5230\u65b0\u7586\u68c9\u6570\u636e\u96c6\uff0c\u53ef\u8054\u7cfb\u535a\u4e3b\u83b7\u53d6<\/p>\n","protected":false},"author":1,"featured_media":19,"comment_status":"open","ping_status":"open","sticky":true,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-8","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-uncategorized"],"_links":{"self":[{"href":"http:\/\/www.xtmouse.top\/index.php\/wp-json\/wp\/v2\/posts\/8","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.xtmouse.top\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.xtmouse.top\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.xtmouse.top\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/www.xtmouse.top\/index.php\/wp-json\/wp\/v2\/comments?post=8"}],"version-history":[{"count":4,"href":"http:\/\/www.xtmouse.top\/index.php\/wp-json\/wp\/v2\/posts\/8\/revisions"}],"predecessor-version":[{"id":45,"href":"http:\/\/www.xtmouse.top\/index.php\/wp-json\/wp\/v2\/posts\/8\/revisions\/45"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/www.xtmouse.top\/index.php\/wp-json\/wp\/v2\/media\/19"}],"wp:attachment":[{"href":"http:\/\/www.xtmouse.top\/index.php\/wp-json\/wp\/v2\/media?parent=8"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.xtmouse.top\/index.php\/wp-json\/wp\/v2\/categories?post=8"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.xtmouse.top\/index.php\/wp-json\/wp\/v2\/tags?post=8"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}