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 | # 파일 호출하기 f = open('/content/drive/My Drive/train.txt', 'r') # 파일 추출하기 - 단어/문법 리스트 tmp_sentence = [] total_sentence = [] for line in f: token = line.split(" ") if len(line)==0 or token[0]=='\n' or token[0]=='-DOCSTART-': if len(tmp_sentence)>0: total_sentence.append(tmp_sentence) tmp_sentence = [] continue tmp_sentence.append([token[0].lower(), token[1].lower()]) # 단어 따로, 문법 따로 리스트 만들기 - zip 사용 list_word = [] list_grammar = [] for sentence in total_sentence: word, grammar = zip(*sentence) list_word.append(list(word)) list_grammar.append(list(grammar)) # 정수로 인코딩 하기(1) - 인덱스 매칭 from tensorflow.keras.preprocessing.text import Tokenizer tokenizer_word = Tokenizer(num_words=4000, oov_token='OOV') tokenizer_word.fit_on_texts(list_word) size_word = 4000 tokenizer_grammar = Tokenizer() tokenizer_grammar.fit_on_texts(list_grammar) size_grammar = len(tokenizer_grammar.word_index) + 1 # 정수로 인코딩 하기(2) - 각각 인덱스 붙여주기 seq_word = tokenizer_word.texts_to_sequences(list_word) seq_grammar = tokenizer_grammar.texts_to_sequences(list_grammar) # 패딩 수행하기 from tensorflow.keras.preprocessing.sequence import pad_sequences max_len = 70 pad_word = pad_sequences(seq_word, maxlen=max_len) pad_grammar = pad_sequences(seq_grammar, maxlen=max_len) # y값에 대한 원핫인코딩 수행하기 from tensorflow.keras.utils import to_categorical onehot_grammar = to_categorical(pad_grammar) from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, LSTM, Bidirectional, TimeDistributed, Embedding model = Sequential() model.add(Embedding(input_dim=size_word, output_dim = 128, mask_zero=True)) model.add(Bidirectional(LSTM(128, return_sequences=True))) model.add(TimeDistributed(Dense(size_grammar, activation='softmax'))) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['acc']) model.fit(x=pad_word, y=onehot_grammar, batch_size=100, epochs=5) | cs |
개체명 인식기와 동일한 메커니즘으로 작동한다
'기계학습 > 자연어 처리 머신러닝' 카테고리의 다른 글
글자 단위 RNN - N:1 모델 LSTM (0) | 2020.02.18 |
---|---|
글자단위 예측 모델 - N:N 모델 LSTM (0) | 2020.02.18 |
개체명 인식기 - N:N 양방향 LSTM 모델 (0) | 2020.02.17 |
신문 제목 분류 실습 - 나이브 베이즈 분류기 (0) | 2020.02.14 |
스팸 메일 분류기 - 실습 이론 (0) | 2020.02.13 |