skinOptions.hljs
[NLP] 수집한 데이터로 커스텀 개체명인식 데이터셋 구축하기 - (1)
·
Project/Paper Project
from konlpy.tag import Mecab # 개체명 사전 로드 ner_dict = {"PERSON": ["John", "Mary", "Peter"], "ORGANIZATION": ["Google", "Microsoft", "Apple"], "LOCATION": ["New York", "London", "Paris"]} # 텍스트 입력 받기 text = "John works at Google in New York." # 텍스트를 단어로 분리 tokenizer = Mecab() words = tokenizer.morphs(text) print(words) # 개체명 사전을 사용하여 개체명을 태깅 tags = [] for word in words: for ner in ner_dict: if word..
[NLP Project] BERT NER 개체명 인식기로 퀴즈 알고리즘 만들기
·
Project/캡스톤디자인2
문제 템플릿 생성하기¶문제 유형¶ 빈칸 유형 OX 유형 오지선다형 주관식 서술형 문제는 의미역 구문 분석이 필요 In [250]: from predict import ner_prediction, pos_process from transformers import BertTokenizer, TFBertModel from konlpy.tag import Mecab # 형태소 단위로 나누기 import kss # 문장단위로 나누기 from pykospacing import Spacing# 띄어쓰기 교정하기 from hanspell import spell_checker # 띄어쓰기 + 맞춤법 교정 import random import os import warnings from silence_tensorflow i..
[NLP Project] 문장에서 불용어 제거하기
·
Project/캡스톤디자인2
Predict 함수에서 불용어를 제거하는 함수를 작성하도록 하겠습니다. def remove_stopwords(sentence): with open('stop_words.txt',"r") as f: stop_words = [line.rstrip('\n') for line in f] print(stop_words) result = [] sentence = sentence.split(' ') for i in sentence: if i not in stop_words: result.append(i) return " ".join(result) 자주 사용하는 불용어 목록은 첨부한 텍스트 파일과 같습니다. 제가 작성한 stop_words 불용어 사전은 제가 프로젝트를 진행함에 있어 조금 커스텀 해주었습니다. (년 월..
[NLP Project] tensorflow 파인튜닝한 모델 저장하고 모델 불러오기
·
Project/캡스톤디자인2
텐서플로우에서 파인튜닝한 버트 모델을 저장하고 불러오겠습니다. model.fit( X_train, y_train, epochs=1, batch_size=128, callbacks = [f1_score_report] ) model.save_weights('save_model/model_weight') 학습한 모델은 save_weights 로 저장합니다. predict.py def model_load(): model = modeling(model_name='bert-base-multilingual-cased', tag_size=30) model.load_weights('save_model/model_weight') print("model_load성공!!") return model 모델의 아키텍처를 모두 불러..
[NLP Project] Bert model 성능 기록
·
Project/캡스톤디자인2
11월 12일 bert-base-multilingual-cased epochs = 20, batch_size = 128 RMSprop lr" 5e-5 f1 score : 82.17 더보기 Epoch 1/20 461/461 [==============================] - 356s 743ms/step - loss: 0.4317 - f1: 75.18 precision recall f1-score support AT_B 0.85 0.90 0.87 1743 AT_I 0.76 0.87 0.81 500 ER_B 0.70 0.77 0.73 2853 ER_I 0.48 0.29 0.36 337 FW_B 0.46 0.23 0.31 284 FW_I 0.20 0.16 0.18 80 IM_B 0.80 0.79 0...
[NLP Project] Bert 모델에 NER 학습시키기 (텐서플로우) - keras.saving() 해결일지
·
Project/캡스톤디자인2
기존의 인터넷 상에 있던 코드들은 모두 옛날 코드인지 잘 적용이 안됐었다. 긴 시간 구현해보고 파이토치로도 구현해보았는데 제대로 코드조차 실행이 안됐다. 사실은 다른 오픈소스를 다운받아 해결할 수 있었겠지만, 그렇게 하면 공부가 절대 되지 않을 것 같아 직접 발로 뛰며 구현했다. (사실 앉아만 있었음) 버트 인풋 만들기에서 조금 더 추가한 부분이 있다. 'token_type_ids' [CLS] 부분과 [SEP] 부분까지의 문장을 구분한다. 사실 내가 전처리한 데이터 셋에는 데이터셋 처음 부분은 [CLS], 마지막 부분은 [SEP]라서 문장 자체에서 이렇게 구분하진 않아도 된다. 그래도 일단... 인풋에 필요하다고 하니 넣어주기로 한다. # 'token_type_ids' ( [CLS]와 [SEP]를 구분해..
[NLP Project] Test data, Train Data Split
·
Project/캡스톤디자인2
학습을 위해 데이터를 분리하여주겠습니다. from sklearn.model_selection import train_test_split # train 데이터에서 10% 만큼을 validation 데이터로 분리 tr_inputs, val_inputs, tr_tags, val_tags = train_test_split(input_ids, tags, random_state=222, test_size=0.1) tr_masks, val_masks, _, _ = train_test_split(attention_masks, input_ids, random_state=222, test_size=0.1) main.py import pickle import numpy as np from tensorflow.keras.pr..
[NLP Project] Padding , Attention mask
·
Project/캡스톤디자인2
pickle file save & load main.py import pickle import numpy as np def file_open(filePath): f =open(filePath,"rb") data = pickle.load(f) f.close() return data if __name__ == "__main__": tokened_data = file_open('data/token_data.pkl') tokenized_texts = [token_label_pair[0] for token_label_pair in tokened_data] labels = [token_label_pair[1] for token_label_pair in tokened_data] ## padding print(np.q..
[NLP Project] BERT 인풋 만들기 - 1. 문장 전처리
·
Project/캡스톤디자인2
전처리한 데이터를 바탕으로 태그와 문장을 토큰화 해보겠습니다. 문장 토큰화 tokenization.py from transformers import BertTokenizer from transformers import BertTokenizer def tokenize_and_preserve_labels(sentence, text_labels): tokenizer = BertTokenizer.from_pretrained('bert-base-multilingual-cased') tokenized_sentence = [] labels = [] for word, label in zip(sentence, text_labels): tokenized_word = tokenizer.tokenize(word) n_subw..
[NLP Project] 1-2. 데이터 전처리 - 특수문자 제거하기
·
Project/캡스톤디자인2
이전에 구현했던 코드에서 데이터 전처리를 조금 더 진행해보겠다. data_load.py에서 구현했던 tag_split() 함수에서 해당 문자에서 한글, 영어, 소문자, 대문자 이외의 단어를 제거하는 함수를 작성해보겠다. cng_sentence = [] for str in sentence: # 한글, 영어, 소문자, 대문자 이외의 단어 제거 str = re.sub(r'[^ㄱ-ㅣ가-힣0-9a-zA-Z.]', "", str) cng_sentence.append(str) # 전처리한 데이터를 바탕으로 단어와 태그 나누기 def tag_split(tagged_sentences): sentences, ner_tags = [],[] for tagged_sentence in tagged_sentences: senten..
[NLP Project] F1 Score
·
Project/캡스톤디자인2
f1score란.. 블로그에서 해당 내용에 대해 다룬 게시글이 있으므로 나중에 링크 걸어두겠다. https://bestkcs1234.tistory.com/61 Tensorflow addons 을 이용한 F1 score 출력 tensorflow는 모델을 compile 할 때 다양한 metrics를 제공해준다. 다음과 같이 설정하면 매 epoch 마다 해당하는 수치들을 계산하여 출력해준다. 하지만 f1 score는 tf.metrics에서 찾아볼 수 없는데 Tensorflow a bestkcs1234.tistory.com from sklearn.metrics import classification_report,f1_score # f1 score p = model.predict(np.array(X_test)) ..
[NLP Project] LSTM + self-attention
·
Project/캡스톤디자인2
모델에 attention 층 추가 model.add(Bidirectional(LSTM(units=128, return_sequences=True, dropout=0.2, recurrent_dropout=0.2))) model.add(SeqSelfAttention(attention_activation='sigmoid')) model.add(Bidirectional(LSTM(units=64, return_sequences=True, dropout=0.2, recurrent_dropout=0.2))) model.add(SeqSelfAttention(attention_activation='sigmoid')) model.add(Dense(1, activation='sigmoid')) model.py from ke..