Ejemplo n.º 1
0
def predict(text):
    word2idx, idx2word, vocab_len = data.load_vocabulary()
    classifier = tf.estimator.Estimator(model_fn=ml.model,
                                        model_dir=DEFINES.check_point_path,
                                        params={
                                            'hidden_size': DEFINES.hidden_size,
                                            'layer_size': DEFINES.layer_size,
                                            'learning_rate':
                                            DEFINES.learning_rate,
                                            'vocab_len': vocab_len,
                                            'embedding_size':
                                            DEFINES.embedding_size,
                                            'embedding': DEFINES.embedding,
                                            'multilayer': DEFINES.multilayer,
                                        })
    # 테스트셋 인코딩 / 디코딩 입력 / 디코딩 출력
    predic_input_enc, predic_input_enc_length = data.enc_processing([text],
                                                                    word2idx)
    predic_input_dec, predic_input_dec_length = data.dec_input_processing(
        [""], word2idx)
    predic_target_dec = data.dec_target_processing([""], word2idx)

    # 예측 실행
    predictions = classifier.predict(input_fn=lambda: data.eval_input_fn(
        predic_input_enc, predic_input_dec, predic_target_dec, DEFINES.
        batch_size))

    # 예측한 값을 텍스트로 변경하는 부분이다.
    data.pred2string(predictions, idx2word)
Ejemplo n.º 2
0
def main(self):
    data_out_path = os.path.join(os.getcwd(), DATA_OUT_PATH)
    os.makedirs(data_out_path, exist_ok=True)
    # 데이터를 통한 사전 구성 한다.
    word2idx,  idx2word, vocabulary_length = data.load_vocabulary()
	# 훈련 데이터와 테스트 데이터를 가져온다.
    train_input, train_label, eval_input, eval_label = data.load_data()

	# 훈련셋 인코딩 / 디코딩 입력 / 디코딩 출력 만드는 부분이다.
    train_input_enc, train_input_enc_length = data.enc_processing(train_input, word2idx)
    train_input_dec, train_input_dec_length = data.dec_input_processing(train_label, word2idx)
    train_target_dec = data.dec_target_processing(train_label, word2idx)
	
	# 평가셋 인코딩 / 디코딩 입력 / 디코딩 출력 만드는 부분이다.
    eval_input_enc, eval_input_enc_length = data.enc_processing(eval_input,word2idx)
    eval_input_dec, eval_input_dec_length = data.dec_input_processing(eval_label, word2idx)
    eval_target_dec = data.dec_target_processing(eval_label, word2idx)

    # 현재 경로'./'에 현재 경로 하부에 체크 포인트를 저장한 디렉토리를 설정한다.
    check_point_path = os.path.join(os.getcwd(), DEFINES.check_point_path)
    os.makedirs(check_point_path, exist_ok=True)

	# 에스티메이터 구성한다.
    classifier = tf.estimator.Estimator(
            model_fn=ml.model, # 모델 등록한다.
            model_dir=DEFINES.check_point_path, 
            params={
                'hidden_size': DEFINES.hidden_size, 
                'layer_size': DEFINES.layer_size, 
                'learning_rate': DEFINES.learning_rate, 
                'vocabulary_length': vocabulary_length, 
                'embedding_size': DEFINES.embedding_size, 
                'embedding': DEFINES.embedding, 
                'multilayer': DEFINES.multilayer,
            })

	# 학습 실행
    classifier.train(input_fn=lambda:data.train_input_fn(
        train_input_enc, train_input_dec, train_target_dec,  DEFINES.batch_size), steps=DEFINES.train_steps)
    
    # 평가 실행
    eval_result = classifier.evaluate(input_fn=lambda:data.eval_input_fn(
        eval_input_enc, eval_input_dec, eval_target_dec,  DEFINES.batch_size))
    print('\nEVAL set accuracy: {accuracy:0.3f}\n'.format(**eval_result))


	# 테스트셋 인코딩 / 디코딩 입력 / 디코딩 출력 만드는 부분이다.
    predic_input_enc, predic_input_enc_length = data.enc_processing(["가끔 궁금해"], word2idx)
    predic_input_dec, predic_input_dec_length = data.dec_input_processing([""], word2idx)       
    predic_target_dec = data.dec_target_processing([""], word2idx)      

    # 예측 실행
    predictions = classifier.predict(
        input_fn=lambda:data.eval_input_fn(predic_input_enc, predic_input_dec, predic_target_dec, DEFINES.batch_size))
    
    # 예측한 값을 텍스트로 변경하는 부분이다.
    data.pred2string(predictions, idx2word)
Ejemplo n.º 3
0
def main(self):
    data_out_path = os.path.join(os.getcwd(), DATA_OUT_PATH)
    os.makedirs(data_out_path, exist_ok=True)

    word2idx, idxword, vocabulary_length = data.load_vocabulary()
    train_input, train_label, eval_input, eval_label = data.load_data()
    train_input_enc, train_input_enc_length = data.enc_processing(
        train_input, word2idx)
    train_input_dec, train_input_dec_length = data.dec_input_processing(
        train_label, word2idx)
    train_target_dec = data.dec_target_processing(train_label, word2idx)

    eval_input_enc, eval_input_enc_length = data.enc_processing(
        eval_input, word2idx)
    eval_input_dec, eval_input_dec_length = data.dec_input_processing(
        eval_label, word2idx)
    eval_target_dec = data.dec_target_processing(eval_label, word2idx)

    check_point_path = os.path.join(os.getcwd(), DEFINES.check_point_path)
    os.makedirs(check_point_path, exist_ok=True)

    classifier = tf.estimator.Estimator(model_fn=ml.model,
                                        model_dir=DEFINES.check_point_path,
                                        params={
                                            'hidden_size': DEFINES.hidden_size,
                                            'layer_size': DEFINES.layer_size,
                                            'learning_rate':
                                            DEFINES.learning_rate,
                                            'vocabulary_length':
                                            vocabulary_length,
                                            'embedding_size':
                                            DEFINES.embedding_size,
                                            'embedding': DEFINES.embedding,
                                            'multilayer': DEFINES.multilayer,
                                        })

    classifier.train(input_fn=lambda: data.train_input_fn(
        train_input_enc, train_input_dec, train_target_dec, DEFINES.batch_size
    ),
                     steps=DEFINES.train_steps)

    eval_result = classifier.evaluate(input_fn=lambda: data.eval_input_fn(
        eval_input_enc, eval_input_dec, eval_target_dec, DEFINES.batch_size))
    print('\nEVAL set accuracy: {accuracy:0.3f}\n'.format(**eval_result))

    predic_input_enc, predic_input_enc_length = data.enc_processing(["가끔 궁금해"],
                                                                    word2idx)
    predic_input_dec, predic_input_decLength = data.dec_input_processing(
        [""], word2idx)
    predic_target_dec = data.dec_target_processing([""], word2idx)

    predictions = classifier.predict(input_fn=lambda: data.eval_input_fn(
        predic_input_enc, predic_input_dec, predic_target_dec, DEFINES.
        batch_size))

    data.pred2string(predictions, idx2word)
Ejemplo n.º 4
0
def train(self):
    data_out_path = os.path.join(BASE_DIR, DATA_OUT_PATH)
    os.makedirs(data_out_path, exist_ok=True)
    # 데이터를 통한 사전 구성
    word2idx, idx2word, vocab_len = data.load_vocabulary()

    train_input, train_label, eval_input, eval_label = data.load_data()
    # 훈련셋 인코딩 / 디코딩 입력 / 디코딩 출력
    train_input_enc, train_input_enc_len = data.enc_processing(
        train_input, word2idx)
    train_input_dec, train_input_dec_len = data.dec_input_processing(
        train_label, word2idx)
    train_target_dec = data.dec_target_processing(train_label, word2idx)
    # 평가셋 인코딩 / 디코딩 입력 / 디코딩 출력
    eval_input_enc, eval_input_enc_len = data.enc_processing(
        eval_input, word2idx)
    eval_input_dec, eval_input_dec_len = data.dec_input_processing(
        eval_label, word2idx)
    eval_target_dec = data.dec_target_processing(eval_label, word2idx)

    os.makedirs(DEFINES.check_point_path, exist_ok=True)

    classifier = tf.estimator.Estimator(model_fn=ml.model,
                                        model_dir=DEFINES.check_point_path,
                                        params={
                                            'hidden_size': DEFINES.hidden_size,
                                            'layer_size': DEFINES.layer_size,
                                            'learning_rate':
                                            DEFINES.learning_rate,
                                            'vocab_len': vocab_len,
                                            'embedding_size':
                                            DEFINES.embedding_size,
                                            'embedding': DEFINES.embedding,
                                            'multilayer': DEFINES.multilayer,
                                        })
    # 학습 실행
    classifier.train(input_fn=lambda: data.train_input_fn(
        train_input_enc, train_input_dec, train_target_dec, DEFINES.batch_size
    ),
                     steps=DEFINES.train_steps)
    # 평가 실행
    eval_result = classifier.evaluate(input_fn=lambda: data.eval_input_fn(
        eval_input_enc, eval_input_dec, eval_target_dec, DEFINES.batch_size))
    print('\nEVAL set accuracy: {accuracy:0.3f}\n'.format(**eval_result))
Ejemplo n.º 5
0
def main(self):
    data_out_path = os.path.join(os.getcwd(), DATA_OUT_PATH)
    os.makedirs(data_out_path, exist_ok=True)
    # 데이터를 통한 사전 구성 한다.
    char2idx, idx2char, vocabulary_length = data.load_vocabulary()

    # 에스티메이터 구성한다.
    classifier = tf.estimator.Estimator(
        model_fn=ml.Model,  # 모델 등록한다.
        model_dir=DEFINES.check_point_path,  # 체크포인트 위치 등록한다.
        params={  # 모델 쪽으로 파라메터 전달한다.
            'embedding_size': DEFINES.embedding_size,
            'model_hidden_size': DEFINES.model_hidden_size,  # 가중치 크기 설정한다.
            'ffn_hidden_size': DEFINES.ffn_hidden_size,
            'attention_head_size': DEFINES.attention_head_size,
            'learning_rate': DEFINES.learning_rate,  # 학습율 설정한다.
            'vocabulary_length': vocabulary_length,  # 딕셔너리 크기를 설정한다.
            'embedding_size': DEFINES.embedding_size,  # 임베딩 크기를 설정한다.
            'layer_size': DEFINES.layer_size,
            'max_sequence_length': DEFINES.max_sequence_length,
            'xavier_initializer': DEFINES.xavier_initializer
        })

    # 테스트용 데이터 만드는 부분이다.
    # 인코딩 부분 만든다.
    predic_input_enc, predic_input_enc_length = data.enc_processing([a],
                                                                    char2idx)
    # 학습 과정이 아니므로 디코딩 입력은
    # 존재하지 않는다.(구조를 맞추기 위해 넣는다.)
    predic_output_dec, predic_output_decLength = data.dec_output_processing(
        [""], char2idx)
    # 학습 과정이 아니므로 디코딩 출력 부분도
    # 존재하지 않는다.(구조를 맞추기 위해 넣는다.)
    predic_target_dec = data.dec_target_processing([""], char2idx)

    predictions = classifier.predict(input_fn=lambda: data.eval_input_fn(
        predic_input_enc, predic_output_dec, predic_target_dec, 1))

    answer, finished = data.pred_next_string(predictions, idx2char)

    # 예측한 값을 인지 할 수 있도록
    # 텍스트로 변경하는 부분이다.
    print("answer: ", answer)
Ejemplo n.º 6
0
                        type=str,
                        help="Location of output file")
    parser.add_argument('--batch-size',
                        type=int,
                        help="size of batch",
                        default=32)

    args = parser.parse_args()

    MAX_NUM_TOKENS = 250
    test_instances = read_instances(args.data_file_path,
                                    MAX_NUM_TOKENS,
                                    test=True)

    vocabulary_path = os.path.join(args.load_serialization_dir, "vocab.txt")
    vocab_token_to_id, _ = load_vocabulary(vocabulary_path)

    test_instances = index_instances(test_instances, vocab_token_to_id)

    # load config
    config_path = os.path.join(args.load_serialization_dir, "config.json")
    with open(config_path, 'r') as f:
        config = json.load(f)

    # load model
    model = load_pretrained_model(args.load_serialization_dir)

    predict(model, test_instances, args.batch_size, args.prediction_file)

    if args.prediction_file:
        print(f"predictions stored at: {args.prediction_file}")
Ejemplo n.º 7
0
def main(self):
    data_out_path = os.path.join(os.getcwd(), DATA_OUT_PATH)
    os.makedirs(data_out_path, exist_ok=True)
    # 데이터를 통한 사전 구성 한다.
    char2idx, idx2char, vocabulary_length = data.load_vocabulary()
    # 훈련 데이터와 테스트 데이터를 가져온다.
    train_input, train_label, eval_input, eval_label = data.load_data()

    # 훈련셋 인코딩 만드는 부분이다.
    train_input_enc, train_input_enc_length = data.enc_processing(
        train_input, char2idx)
    # 훈련셋 디코딩 입력 부분 만드는 부분이다.
    train_output_dec, train_output_dec_length = data.dec_output_processing(
        train_label, char2idx)
    # 훈련셋 디코딩 출력 부분 만드는 부분이다.
    train_target_dec = data.dec_target_processing(train_label, char2idx)

    # 평가셋 인코딩 만드는 부분이다.
    eval_input_enc, eval_input_enc_length = data.enc_processing(
        eval_input, char2idx)
    # 평가셋 인코딩 만드는 부분이다.
    eval_output_dec, eval_output_dec_length = data.dec_output_processing(
        eval_label, char2idx)
    # 평가셋 인코딩 만드는 부분이다.
    eval_target_dec = data.dec_target_processing(eval_label, char2idx)

    # 현재 경로'./'에 현재 경로 하부에
    # 체크 포인트를 저장한 디렉토리를 설정한다.
    check_point_path = os.path.join(os.getcwd(), DEFINES.check_point_path)
    # 디렉토리를 만드는 함수이며 두번째 인자 exist_ok가
    # True이면 디렉토리가 이미 존재해도 OSError가
    # 발생하지 않는다.
    # exist_ok가 False이면 이미 존재하면
    # OSError가 발생한다.
    os.makedirs(check_point_path, exist_ok=True)

    # 에스티메이터 구성한다.
    classifier = tf.estimator.Estimator(
        model_fn=ml.Model,  # 모델 등록한다.
        model_dir=DEFINES.check_point_path,  # 체크포인트 위치 등록한다.
        params={  # 모델 쪽으로 파라메터 전달한다.
            'model_hidden_size': DEFINES.model_hidden_size,  # 가중치 크기 설정한다.
            'ffn_hidden_size': DEFINES.ffn_hidden_size,
            'attention_head_size': DEFINES.attention_head_size,
            'learning_rate': DEFINES.learning_rate,  # 학습율 설정한다.
            'vocabulary_length': vocabulary_length,  # 딕셔너리 크기를 설정한다.
            'embedding_size': DEFINES.embedding_size,  # 임베딩 크기를 설정한다.
            'layer_size': DEFINES.layer_size,
            'max_sequence_length': DEFINES.max_sequence_length,
            'xavier_initializer': DEFINES.xavier_initializer
        })

    # 학습 실행
    classifier.train(input_fn=lambda: data.train_input_fn(
        train_input_enc, train_output_dec, train_target_dec, DEFINES.batch_size
    ),
                     steps=DEFINES.train_steps)

    eval_result = classifier.evaluate(input_fn=lambda: data.eval_input_fn(
        eval_input_enc, eval_output_dec, eval_target_dec, DEFINES.batch_size))

    print('\nEVAL set accuracy: {accuracy:0.3f}\n'.format(**eval_result))

    # 테스트용 데이터 만드는 부분이다.
    # 인코딩 부분 만든다.
    predic_input_enc, predic_input_enc_length = data.enc_processing(["가끔 궁금해"],
                                                                    char2idx)
    # 학습 과정이 아니므로 디코딩 입력은
    # 존재하지 않는다.(구조를 맞추기 위해 넣는다.)
    predic_output_dec, predic_output_decLength = data.dec_output_processing(
        [""], char2idx)
    # 학습 과정이 아니므로 디코딩 출력 부분도
    # 존재하지 않는다.(구조를 맞추기 위해 넣는다.)
    predic_target_dec = data.dec_target_processing([""], char2idx)

    predictions = classifier.predict(input_fn=lambda: data.eval_input_fn(
        predic_input_enc, predic_output_dec, predic_target_dec, 1))

    answer, finished = data.pred_next_string(predictions, idx2char)

    # 예측한 값을 인지 할 수 있도록
    # 텍스트로 변경하는 부분이다.
    print("answer: ", answer)
Ejemplo n.º 8
0
import tensorflow as tf
import numpy as np
import data
import model as ml
from configs import DEFINES

tf.logging.set_verbosity(tf.logging.ERROR)
word2idx, idx2word, vocabulary_length = data.load_vocabulary()

# 에스티메이터 구성
classifier = tf.estimator.Estimator(model_fn=ml.model,
                                    model_dir=DEFINES.check_point_path,
                                    params={
                                        'hidden_size': DEFINES.hidden_size,
                                        'layer_size': DEFINES.layer_size,
                                        'learning_rate': DEFINES.learning_rate,
                                        'vocabulary_length': vocabulary_length,
                                        'embedding_size':
                                        DEFINES.embedding_size
                                    })


# 확률적 답변을 위해 다항분포 샘플링을 이용한다.
# preds는 디코더의 출력인 softmax이고, beta는 softmax의 강도를 조절하는 변수이다.
# beta가 작아질수록 정적으로 답변하고 (랜덤 성향이 큼), beta가 커질수록 동적으로 답변한다.
def pred_indices(preds, beta=1.0):
    preds = np.asarray(preds).astype('float64')
    preds = np.log(preds + 0.000000001) / beta
    exp_preds = np.exp(preds)
    preds = exp_preds / np.sum(exp_preds)
    probs = np.random.multinomial(1, preds, 1)
Ejemplo n.º 9
0
def main(self):
    data_out_path = os.path.join(os.getcwd(), DATA_OUT_PATH)
    os.makedirs(data_out_path, exist_ok=True)
    # 사전 데이터 불러오기 (인덱싱된 단어, 단어 자체, 단어 길이)
    char2idx, idx2char, vocabulary_length = data.load_vocabulary()
    # 훈련, 테스트용으로 input과 label을 가져온다
    train_input, train_label, eval_input, eval_label = data.load_data()

    # 훈련 인코딩 입력
    train_input_enc, train_input_enc_length = data.enc_processing(
        train_input, char2idx)
    # 훈련 디코딩 입력
    train_output_dec, train_output_dec_length = data.dec_output_processing(
        train_label, char2idx)
    # 훈련 디코딩 출력
    train_target_dec = data.dec_target_processing(train_label, char2idx)

    # 평가 인코딩 입력
    eval_input_enc, eval_input_enc_length = data.enc_processing(
        eval_input, char2idx)
    # 평가 디코딩 입력
    eval_output_dec, eval_output_dec_length = data.dec_output_processing(
        eval_label, char2idx)
    # 평가 디코딩 출력
    eval_target_dec = data.dec_target_processing(eval_label, char2idx)

    # 현재 경로'./'에 현재 경로 하부에
    # 체크 포인트를 저장한 디렉토리를 설정
    check_point_path = os.path.join(os.getcwd(), DEFINES.check_point_path)
    # save_model_path = os.path.join(os.getcwd(), DEFINES.save_model_path)
    # 디렉토리를 만드는 함수이며 두번째 인자 exist_ok가
    # True이면 디렉토리가 이미 존재해도 OSError가
    # 발생하지 않는다.
    # exist_ok가 False이면 이미 존재하면
    # OSError가 발생한다.
    os.makedirs(check_point_path, exist_ok=True)
    # os.makedirs(save_model_path, exist_ok = True)

    # 에스티메이터 구성한다.
    classifier = tf.estimator.Estimator(
        model_fn=ml.Model,  # 모델 등록한다.
        model_dir=DEFINES.check_point_path,  # 체크포인트 위치 등록한다.
        params={  # 모델 쪽으로 파라메터 전달한다.
            'embedding_size': DEFINES.embedding_size,
            'model_hidden_size': DEFINES.model_hidden_size,  # 가중치 크기 설정한다.
            'ffn_hidden_size': DEFINES.ffn_hidden_size,
            'attention_head_size': DEFINES.attention_head_size,
            'learning_rate': DEFINES.learning_rate,  # 학습율 설정한다.
            'vocabulary_length': vocabulary_length,  # 딕셔너리 크기를 설정한다.
            'embedding_size': DEFINES.embedding_size,  # 임베딩 크기를 설정한다.
            'layer_size': DEFINES.layer_size,
            'max_sequence_length': DEFINES.max_sequence_length,
            'xavier_initializer': DEFINES.xavier_initializer
        })

    # 학습 실행
    classifier.train(input_fn=lambda: data.train_input_fn(
        train_input_enc, train_output_dec, train_target_dec, DEFINES.batch_size
    ),
                     steps=DEFINES.train_steps)

    eval_result = classifier.evaluate(input_fn=lambda: data.eval_input_fn(
        eval_input_enc, eval_output_dec, eval_target_dec, DEFINES.batch_size))
    print('\nEVAL set accuracy: {accuracy:0.3f}\n'.format(**eval_result))

    # 테스트용 데이터 만드는 부분이다.
    # 인코딩 부분 만든다.
    predic_input_enc, predic_input_enc_length = data.enc_processing([
        "Many people have pointed out that personal responsibility can often be lost in groups. Consider how often you’ve passed someone who is pulled over on the side of the road with car trouble. It is easy to justify your failure to help by telling yourself someone else will stop. Corporations add another layer of complication to the story of reduced personalresponsibility in group settings because corporations are set up to assign legal responsibility to the corporation itself instead of to its members. There are other complex organizations in which the individual members are often not sure of their impact or power to bring about change. In this kind of culture,“someone else will do it” is a common excuse."
    ], char2idx)
    # 학습 과정이 아니므로 디코딩 입력은
    # 존재하지 않는다.(구조를 맞추기 위해 넣는다.)
    predic_output_dec, predic_output_decLength = data.dec_output_processing(
        [""], char2idx)
    # 학습 과정이 아니므로 디코딩 출력 부분도
    # 존재하지 않는다.(구조를 맞추기 위해 넣는다.)
    predic_target_dec = data.dec_target_processing([""], char2idx)

    for i in range(DEFINES.max_sequence_length):
        if i > 0:
            predic_output_dec, predic_output_decLength = data.dec_output_processing(
                [answer], char2idx)
            predic_target_dec = data.dec_target_processing([answer], char2idx)
        # 예측을 하는 부분이다.
        predictions = classifier.predict(input_fn=lambda: data.eval_input_fn(
            predic_input_enc, predic_output_dec, predic_target_dec, 1))

        answer, finished = data.pred_next_string(predictions, idx2char)

        if finished:
            break

    # 예측한 값을 인지 할 수 있도록
    # 텍스트로 변경하는 부분이다.
    print("answer: ", answer)
Ejemplo n.º 10
0
def main(self):
    data_out_path = os.path.join(os.getcwd(), DATA_OUT_PATH)
    os.makedirs(data_out_path, exist_ok=True)
    # 데이터를 통한 사전 구성 한다.
    char2idx, idx2char, vocabulary_length = data.load_vocabulary()
    # 훈련 데이터와 테스트 데이터를 가져온다.
    train_input, train_label, eval_input, eval_label = data.load_data()

    # 훈련셋 인코딩 만드는 부분이다.
    train_input_enc, train_input_enc_length = data.enc_processing(train_input, char2idx)
    # 훈련셋 디코딩 출력 부분 만드는 부분이다.
    train_target_dec, train_target_dec_length = data.dec_target_processing(train_label, char2idx)
    
    # 평가셋 인코딩 만드는 부분이다.
    eval_input_enc, eval_input_enc_length = data.enc_processing(eval_input,char2idx)
    # 평가셋 디코딩 출력 부분 만드는 부분이다.
    eval_target_dec, _ = data.dec_target_processing(eval_label, char2idx)

    # 현재 경로'./'에 현재 경로 하부에 
    # 체크 포인트를 저장한 디렉토리를 설정한다.
    check_point_path = os.path.join(os.getcwd(), DEFINES.check_point_path)
    save_model_path = os.path.join(os.getcwd(), DEFINES.save_model_path)
    # 디렉토리를 만드는 함수이며 두번째 인자 exist_ok가 
    # True이면 디렉토리가 이미 존재해도 OSError가 
    # 발생하지 않는다.
    # exist_ok가 False이면 이미 존재하면 
    # OSError가 발생한다.
    os.makedirs(check_point_path, exist_ok=True)
    os.makedirs(save_model_path, exist_ok=True)

    # 에스티메이터 구성한다.
    classifier = tf.estimator.Estimator(
        model_fn=ml.Model,  # 모델 등록한다.
        model_dir=DEFINES.check_point_path,  # 체크포인트 위치 등록한다.
        params={  # 모델 쪽으로 파라메터 전달한다.
            'hidden_size': DEFINES.hidden_size,  # 가중치 크기 설정한다.
            'layer_size': DEFINES.layer_size,  # 멀티 레이어 층 개수를 설정한다.
            'learning_rate': DEFINES.learning_rate,  # 학습율 설정한다.
            'teacher_forcing_rate': DEFINES.teacher_forcing_rate, # 학습시 디코더 인풋 정답 지원율 설정
            'vocabulary_length': vocabulary_length,  # 딕셔너리 크기를 설정한다.
            'embedding_size': DEFINES.embedding_size,  # 임베딩 크기를 설정한다.
            'embedding': DEFINES.embedding,  # 임베딩 사용 유무를 설정한다.
            'multilayer': DEFINES.multilayer,  # 멀티 레이어 사용 유무를 설정한다.
            'attention': DEFINES.attention, #  어텐션 지원 유무를 설정한다.
	        'teacher_forcing': DEFINES.teacher_forcing, # 학습시 디코더 인풋 정답 지원 유무 설정한다.
            'loss_mask': DEFINES.loss_mask, # PAD에 대한 마스크를 통한 loss를 제한 한다.
            'serving': DEFINES.serving # 모델 저장 및 serving 유무를 설정한다.
        })

    # 학습 실행
    classifier.train(input_fn=lambda: data.train_input_fn(
        train_input_enc, train_target_dec_length, train_target_dec, DEFINES.batch_size), steps=DEFINES.train_steps)
    # 서빙 기능 유무에 따라 모델을 Save 한다.
    if DEFINES.serving == True:
        save_model_path = classifier.export_savedmodel(
            export_dir_base=DEFINES.save_model_path,
            serving_input_receiver_fn=serving_input_receiver_fn)

    # 평가 실행
    eval_result = classifier.evaluate(input_fn=lambda: data.eval_input_fn(
        eval_input_enc,eval_target_dec, DEFINES.batch_size))
    print('\nEVAL set accuracy: {accuracy:0.3f}\n'.format(**eval_result))
Ejemplo n.º 11
0
def main():
    """Run the bot."""
    global update_id

    # Telegram Bot Authorization Token
    bot = telegram.Bot('auth')
    URL = "https://unopenedbox.com/develop/square/api.php"
    last_message = ""
    bootcount = 0
    lcount = 0
    readingold = False
    readingold_lastcount = 0
    now = datetime.datetime.now()
    # get the first pending update_id, this is so we can skip over it in case
    # we get an "Unauthorized" exception.

    # 데이터를 통한 사전 구성 한다.
    char2idx, idx2char, vocabulary_length = data.load_vocabulary()

    # 에스티메이터 구성한다.
    classifier = tf.estimator.Estimator(
        model_fn=ml.Model,  # 모델 등록한다.
        model_dir=DEFINES.check_point_path,  # 체크포인트 위치 등록한다.
        params={  # 모델 쪽으로 파라메터 전달한다.
            'hidden_size': DEFINES.hidden_size,  # 가중치 크기 설정한다.
            'layer_size': DEFINES.layer_size,  # 멀티 레이어 층 개수를 설정한다.
            'learning_rate': DEFINES.learning_rate,  # 학습율 설정한다.
            'teacher_forcing_rate':
            DEFINES.teacher_forcing_rate,  # 학습시 디코더 인풋 정답 지원율 설정
            'vocabulary_length': vocabulary_length,  # 딕셔너리 크기를 설정한다.
            'embedding_size': DEFINES.embedding_size,  # 임베딩 크기를 설정한다.
            'embedding': DEFINES.embedding,  # 임베딩 사용 유무를 설정한다.
            'multilayer': DEFINES.multilayer,  # 멀티 레이어 사용 유무를 설정한다.
            'attention': DEFINES.attention,  #  어텐션 지원 유무를 설정한다.
            'teacher_forcing':
            DEFINES.teacher_forcing,  # 학습시 디코더 인풋 정답 지원 유무 설정한다.
            'loss_mask': DEFINES.loss_mask,  # PAD에 대한 마스크를 통한 loss를 제한 한다.
            'serving': DEFINES.serving  # 모델 저장 및 serving 유무를 설정한다.
        })

    while 1:
        sleep(3)
        now = datetime.datetime.now()
        bootcount = bootcount + 1
        lcount = lcount + 1

        try:
            #data = {'a': 'penta_check', 'auth': 'a1s2d3f4g5h6j7k8l9', 'start_num' : '0', 'number' : '15'}
            #res = requests.post(URL, data=data)
            #answer = "[보고]" + res.json()[0]['description'];
            answer = ""

            if bootcount == 1:
                #answer = "다시 시작했습니다. Penta 버전 1.0.625 밀린 채팅을 읽는 중 입니다..."
                readingold = True
                readingold_lastcount = bootcount
            if readingold_lastcount < bootcount and readingold is True:
                readingold = False
                #bot.send_message(chat_id = -116418298, text="이전글 읽기 완료.")
            if last_message != answer and answer != "":
                bot.send_message(chat_id=-116418298, text=answer)
                last_message = answer
            if last_message == answer:
                tlm = ""
                last_user = 0
                last_talk = ""
                updates = bot.get_updates(offset=update_id)
                for i in updates:
                    if i.message:
                        if last_user != i.message.from_user.id:
                            last_talk = tlm
                            tlm = ""
                            last_user = i.message.from_user.id
                            # with open("./data_in/ChatBotData.csv", "a") as myfile:
                            #   myfile.write("\n")

                        if i.message.text is not None and tlm != "":
                            tlm = tlm + " " + i.message.text
                        # with open("./data_in/ChatBotData.csv", "a") as myfile:
                        #    myfile.write(" " + i.message.text)
                        if i.message.text is not None and tlm == "":
                            tlm = i.message.text
                            # with open("./data_in/ChatBotData.csv", "a") as myfile:
                            #  myfile.write(i.message.text)
                        update_id = i.update_id + 1
                        now_last_id = updates[-1].update_id

                        if tlm != "" and tlm is not None and now_last_id + 1 <= update_id:
                            readingold_lastcount = readingold_lastcount + 1
                            lcount = 0
                            if not readingold:

                                predic_input_enc, predic_input_enc_length = data.enc_processing(
                                    [tlm], char2idx)
                                predic_target_dec, _ = data.dec_target_processing(
                                    [""], char2idx)
                                # 예측을 하는 부분이다.
                                predictions = classifier.predict(
                                    input_fn=lambda: data.eval_input_fn(
                                        predic_input_enc, predic_target_dec,
                                        DEFINES.batch_size))
                                # 예측한 값을 인지 할 수 있도록
                                # 텍스트로 변경하는 부분이다.

                                aimessage = data.pred2string(
                                    predictions, idx2char)
                                if aimessage != "":
                                    bot.send_message(chat_id=-116418298,
                                                     text=aimessage)
        except IndexError:
            update_id = None
        except:
            if last_message != traceback.format_exc(
            ) and "Message text is empty" not in traceback.format_exc():

                bot.send_message(chat_id=-11641828,
                                 text="[오류] 오류가 발생했습니다. 점검이 필요합니다. \n" +
                                 traceback.format_exc())
                last_message = traceback.format_exc()

        logging.basicConfig(
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
Ejemplo n.º 12
0
def main(self):
    ## DATA_OUT_PATH가 없으면 생성, 있으면 그대로 폴더 사용
    data_out_path = os.path.join(os.getcwd(), DATA_OUT_PATH)
    os.makedirs(data_out_path, exist_ok = True)
    ## 단어 사전 불러오기
    word2idx, idx2word, vocabulary_length = data.load_vocabulary()
    ## 데이터 불러오기
    train_input, train_label, eval_input, eval_label = data.load_data()
    
    ## 인코더 입력, 디코더 입력, 디코더 타깃  훈련 데이터로 만들기
    train_input_enc, train_input_enc_length = data.enc_processing(train_input, word2idx)
    train_output_dec, train_input_dec_length = data.dec_input_processing(train_label, word2idx)
    
    train_target_dec = data.dec_target_processing(train_label, word2idx)
    
    ## 인코더 입력, 디코더 입력, 디코더 타깃  검증 데이터로 만들기
    eval_input_enc, eval_input_enc_length = data.enc_processing(eval_input, word2idx)
    eval_output_dec, eval_input_dec_length = data.dec_input_processing(eval_label, word2idx)
    
    eval_target_dec = data.dec_target_processing(eval_label, word2idx)
    
    ## 체크 포인트 설정
    ## data_out 폴더에 생성될 것
    check_point_path = os.path.join(os.getcwd(), DEFINES.check_point_path)
    os.makedirs(check_point_path, exist_ok = True)
    
    
    # Estimator 객체 생성
    classifier = tf.estimator.Estimator(model_fn = ml.model, ## 모델 불러오기
                                       model_dir = DEFINES.check_point_path,
                                       params = {
                                           'hidden_size': DEFINES.hidden_size,
                                           'layer_size': DEFINES.layer_size,
                                           'learning_rate': DEFINES.learning_rate,
                                           'vocabulary_length': vocabulary_length,
                                           'embedding_size': DEFINES.embeddding_size,
                                           'embedding': DEFINES.embedding,
                                           'multilayer': DEFINES.multilayer,
                                       })
    
    
    # Estimator로 학습 진행
    ## 필요 인자: 입력 함수, 스텝 
    classifier.train(input_fn = lambda: data.train_input_fn(
    train_input_enc, train_input_dec, train_target_dec, DEFINES.batch_size),
                    steps = DEFINES.train_steps)
    
    
    ## 검증 함수 정의
    eval_result = classifier.evaluate(input_fn = lambda: data.eval_input_fn(
    eval_input_enc, eval_input_dec, eval_target_dec, DEFINES.batch_size))
    
    ## 바로 성능 확인이 가능하도록 정확도 출력 함수 작성
    print('\nEVAL set accuracy: {accuracy:0.3f}\n'.format(**eval_result))
    
    
    # 결과 예측하기
    
    predic_input_enc, predic_input_enc_length = data.enc_processing(["Education is important"],
                                                                   word2idx)
    predic_input_dec, predic_input_dec_length = data.dec_input_processing([""], word2idx)
    predic_target_dec = data.dec_target_processing([""], word2idx)
    
    predictions = classifier.predict(
        input_fn = lambda: data.eval_input_fn(predic_input_enc, predic_input_dec,
                                             predic_target_dec, DEFINES.batch_size))
    
    data.pred2string(predictions, idx2word)
Ejemplo n.º 13
0
def main(self):
    data_out_path = os.path.join(os.getcwd(), DATA_OUT_PATH)
    os.makedirs(data_out_path, exist_ok=True)
    # 데이터를 통한 사전 구성 한다.
    char2idx, idx2char, vocabulary_length = data.load_vocabulary()

    # 현재 경로'./'에 현재 경로 하부에 
    # 체크 포인트를 저장한 디렉토리를 설정한다.
    check_point_path = os.path.join(os.getcwd(), DEFINES.check_point_path)
    # 디렉토리를 만드는 함수이며 두번째 인자 exist_ok가 
    # True이면 디렉토리가 이미 존재해도 OSError가 
    # 발생하지 않는다.
    # exist_ok가 False이면 이미 존재하면 
    # OSError가 발생한다.
    os.makedirs(check_point_path, exist_ok=True)
    # ----------------------------------
    tf.keras.backend.clear_session()
    os.environ["CUDA_VISIBLE_DEVICES"] = "0"
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    # ---------------------------------
    # 에스티메이터 구성한다.
    classifier = tf.estimator.Estimator(
        model_fn=ml.Model,  # 모델 등록한다.
        model_dir=DEFINES.check_point_path,  # 체크포인트 위치 등록한다.
        params={  # 모델 쪽으로 파라메터 전달한다.
            'embedding_size': DEFINES.embedding_size,
            'model_hidden_size': DEFINES.model_hidden_size,  # 가중치 크기 설정한다.
            'ffn_hidden_size': DEFINES.ffn_hidden_size,
            'attention_head_size': DEFINES.attention_head_size,
            'learning_rate': DEFINES.learning_rate,  # 학습율 설정한다.
            'vocabulary_length': vocabulary_length,  # 딕셔너리 크기를 설정한다.
            'embedding_size': DEFINES.embedding_size,  # 임베딩 크기를 설정한다.
            'layer_size': DEFINES.layer_size,
            'max_sequence_length': DEFINES.max_sequence_length,
            'xavier_initializer': DEFINES.xavier_initializer
        })

    if args.train:
        # 훈련 데이터와 테스트 데이터를 가져온다.
        train_input, train_label, eval_input, eval_label = data.load_data()

        # 훈련셋 인코딩 만드는 부분이다.
        train_input_enc, train_input_enc_length = data.enc_processing(train_input, char2idx)
        # 훈련셋 디코딩 입력 부분 만드는 부분이다.
        train_output_dec, train_output_dec_length = data.dec_output_processing(train_label, char2idx)
        # 훈련셋 디코딩 출력 부분 만드는 부분이다.
        train_target_dec = data.dec_target_processing(train_label, char2idx)

        # 평가셋 인코딩 만드는 부분이다.
        eval_input_enc, eval_input_enc_length = data.enc_processing(eval_input, char2idx)
        # 평가셋 인코딩 만드는 부분이다.
        eval_output_dec, eval_output_dec_length = data.dec_output_processing(eval_label, char2idx)
        # 평가셋 인코딩 만드는 부분이다.
        eval_target_dec = data.dec_target_processing(eval_label, char2idx)
        # 학습 실행
        classifier.train(input_fn=lambda: data.train_input_fn(
            train_input_enc, train_output_dec, train_target_dec, args.batch_size), steps=args.train_steps)
    
    # test 부분
    if args.test:
        q_sent = input('Review sentence > ').strip()
        predic_input_enc, predic_input_enc_length = data.enc_processing([q_sent], char2idx)
        # 학습 과정이 아니므로 디코딩 입력은
        # 존재하지 않는다.(구조를 맞추기 위해 넣는다.)
        predic_output_dec, predic_output_decLength = data.dec_output_processing([""], char2idx)
        # 학습 과정이 아니므로 디코딩 출력 부분도
        # 존재하지 않는다.(구조를 맞추기 위해 넣는다.)
        predic_target_dec = data.dec_target_processing([""], char2idx)

        
        for i in range(DEFINES.max_sequence_length):
            if i > 0:
                predic_output_dec, predic_output_decLength = data.dec_output_processing([answer], char2idx)
                predic_target_dec = data.dec_target_processing([answer], char2idx)
            # 예측을 하는 부분이다.
            predictions = classifier.predict(
                input_fn=lambda: data.eval_input_fn(predic_input_enc, predic_output_dec, predic_target_dec, 1))

            answer, finished = data.pred_next_string(predictions, idx2char)
            if finished:
                break
        print("summary: ", answer)
        '''
Ejemplo n.º 14
0
lastid = 0
with open("./everytime.txt", "r") as f:
    lastid = int(f.readline())  # read everything in the file

while 1:
    try:

        loadcount = 0
        everytime_list_url = "http://everytime.kr/find/board/article/list"
        everytime_art_url = "https://everytime.kr/find/board/comment/list"
        everytime_commentw_url = "https://everytime.kr/save/board/comment"
        cookie = "에브리타임 쿠키 정보."
        board_id = "374911"

        # 데이터를 통한 사전 구성 한다.
        char2idx, idx2char, vocabulary_length = data.load_vocabulary()

        # 에스티메이터 구성한다.
        classifier = tf.estimator.Estimator(
            model_fn=ml.Model,  # 모델 등록한다.
            model_dir=DEFINES.check_point_path,  # 체크포인트 위치 등록한다.
            params={  # 모델 쪽으로 파라메터 전달한다.
                'hidden_size': DEFINES.hidden_size,  # 가중치 크기 설정한다.
                'layer_size': DEFINES.layer_size,  # 멀티 레이어 층 개수를 설정한다.
                'learning_rate': DEFINES.learning_rate,  # 학습율 설정한다.
                'teacher_forcing_rate':
                DEFINES.teacher_forcing_rate,  # 학습시 디코더 인풋 정답 지원율 설정
                'vocabulary_length': vocabulary_length,  # 딕셔너리 크기를 설정한다.
                'embedding_size': DEFINES.embedding_size,  # 임베딩 크기를 설정한다.
                'embedding': DEFINES.embedding,  # 임베딩 사용 유무를 설정한다.
                'multilayer': DEFINES.multilayer,  # 멀티 레이어 사용 유무를 설정한다.
Ejemplo n.º 15
0
def main(self):
    data_out_path = os.path.join(os.getcwd(), DATA_OUT_PATH)
    os.makedirs(data_out_path, exist_ok=True)
    # 데이터를 통한  사전 구성
    char2idx, idx2char, vocabulary_length = data.load_vocabulary()
    # 훈련 데이터와 평가 데이터를 가져옴
    train_input, train_label, eval_input, eval_label = data.load_data()

    # 훈련셋 인코딩을 만듦
    train_input_enc, train_input_enc_length = data.enc_processing(
        train_input, char2idx)
    # 훈련셋 디코딩 출력 부분을 만듦
    train_target_dec, train_target_dec_length = data.dec_target_processing(
        train_label, char2idx)

    # 평가셋 인코딩을 만듦
    eval_input_enc, eval_input_enc_length = data.enc_processing(
        eval_input, char2idx)
    # 평가셋 디코딩 출력 부분을 만듦
    eval_target_dec, _ = data.dec_target_processing(eval_label, char2idx)

    # 현재 경로인 './' 하부에
    # 체크포인트를 저장한 디렉토리를 설정
    check_point_path = os.path.join(os.getcwd(), DEFINES.check_point_path)
    save_model_path = os.path.join(os.getcwd(), DEFINES.save_model_path)
    # 디렉터리를 만드는 함수이며 두 번째 인자인 exist_ok가
    # True이면 디렉터리가 이미 존재해도 OSError가 발생하지 않음
    # exist_ok가 False이면 이미 존재할 경우 OSError가 발생
    os.makedirs(check_point_path, exist_ok=True)
    os.makedirs(save_model_path, exist_ok=True)

    # 에스티메이터를 구성
    classifier = tf.estimator.Estimator(
        model_fn=ml.model,  # 모델 등록
        model_dir=DEFINES.check_point_path,  # 체크포인트의 위치 등록
        params={  # 모델 쪽으로 파라미터를 전달
            'hidden_size': DEFINES.hidden_size,  # 가중치 크기
            'layer_size': DEFINES.layer_size,  # 멀티 레이어 층 개수
            'learning_rate': DEFINES.learning_rate,  # 학습률 설정
            'teacher_forcing_rate': DEFINES.teacher_forcing_rate,  # 학습 시 디코더
            # 인풋 정답 지원율 설정
            'vocabulary_length': vocabulary_length,  # 딕셔너리 크기
            'embedding_size': DEFINES.embedding_size,  # 임베딩 크기
            'embedding': DEFINES.embedding,  # 임베딩 사용 여부
            'multilayer': DEFINES.multilayer,  # 멀티 레이어 사용 여부
            'attention': DEFINES.attention,  # 어텐션 지원 여부
            'teacher_forcing': DEFINES.teacher_forcing,  # 학습 시 디코더 인풋 정답 지원 여부
            'loss_mask': DEFINES.loss_mask,  # PAD에 대한 마스크를 통한 loss를 제한
            'serving': DEFINES.serving  # 모델 저장 및 serving 여부 설정
        })

    # 학습 실행
    classifier.train(input_fn=lambda: data.train_input_fn(
        train_input_enc, train_target_dec_length, train_target_dec, DEFINES.
        batch_size),
                     steps=DEFINES.train_steps)
    # 서빙 기능 여부에 따라 모델을 save
    if DEFINES.serving == True:
        save_model_path = classifier.export_savedmodel(
            export_dir_base=DEFINES.save_model_path,
            serving_input_receiver_fn=serving_input_receiver_fn)

    # 평가 실행
    eval_result = classifier.evaluate(input_fn=lambda: data.eval_input_fn(
        eval_input_enc, eval_target_dec, DEFINES.batch_size))
    print('\nEVAL set accuracy: {accuracy:0.3f}\n'.format(**eval_result))
Ejemplo n.º 16
0
def input_data(chat):
    tf.logging.set_verbosity(tf.logging.ERROR)
    arg_length = len(chat)

    if (arg_length < 2):
        raise Exception("Don't call us. We'll call you")

    # 데이터를 통한 사전 구성 한다.
    char2idx, idx2char, vocabulary_length = data.load_vocabulary()
    # 테스트용 데이터 만드는 부분이다.
    # 인코딩 부분 만든다.
    input = ""
    for i in chat[1:]:
        input += i
        input += " "

    predic_input_enc, predic_input_enc_length = data.enc_processing([input],
                                                                    char2idx)
    # 학습 과정이 아니므로 디코딩 입력은
    # 존재하지 않는다.(구조를 맞추기 위해 넣는다.)
    # 학습 과정이 아니므로 디코딩 출력 부분도
    # 존재하지 않는다.(구조를 맞추기 위해 넣는다.)
    predic_target_dec, _ = data.dec_target_processing([""], char2idx)

    if DEFINES.serving == True:
        # 모델이 저장된 위치를 넣어 준다.  export_dir
        predictor_fn = tf.contrib.predictor.from_saved_model(
            export_dir="./data_out/model/1541575161")
    else:
        # 에스티메이터 구성한다.
        classifier = tf.estimator.Estimator(
            model_fn=ml.Model,  # 모델 등록한다.
            model_dir=DEFINES.check_point_path,  # 체크포인트 위치 등록한다.
            params={  # 모델 쪽으로 파라메터 전달한다.
                'hidden_size': DEFINES.hidden_size,  # 가중치 크기 설정한다.
                'layer_size': DEFINES.layer_size,  # 멀티 레이어 층 개수를 설정한다.
                'learning_rate': DEFINES.learning_rate,  # 학습율 설정한다.
                'teacher_forcing_rate':
                DEFINES.teacher_forcing_rate,  # 학습시 디코더 인풋 정답 지원율 설정
                'vocabulary_length': vocabulary_length,  # 딕셔너리 크기를 설정한다.
                'embedding_size': DEFINES.embedding_size,  # 임베딩 크기를 설정한다.
                'embedding': DEFINES.embedding,  # 임베딩 사용 유무를 설정한다.
                'multilayer': DEFINES.multilayer,  # 멀티 레이어 사용 유무를 설정한다.
                'attention': DEFINES.attention,  #  어텐션 지원 유무를 설정한다.
                'teacher_forcing':
                DEFINES.teacher_forcing,  # 학습시 디코더 인풋 정답 지원 유무 설정한다.
                'loss_mask': DEFINES.loss_mask,  # PAD에 대한 마스크를 통한 loss를 제한 한다.
                'serving': DEFINES.serving  # 모델 저장 및 serving 유무를 설정한다.
            })

    if DEFINES.serving == True:
        predictions = predictor_fn({
            'input': predic_input_enc,
            'output': predic_target_dec
        })
        answer = data.pred2string(predictions, idx2char)
    else:
        # 예측을 하는 부분이다.
        predictions = classifier.predict(input_fn=lambda: data.eval_input_fn(
            predic_input_enc, predic_target_dec, DEFINES.batch_size))
        # 예측한 값을 인지 할 수 있도록
        # 텍스트로 변경하는 부분이다.
        answer = data.pred2string(predictions, idx2char)
    return answer
Ejemplo n.º 17
0
            training_command = (f"python train.py main "
                                f"data/imdb_sentiment_train_5k.jsonl "
                                f"data/imdb_sentiment_dev.jsonl "
                                f"--seq2vec-choice {seq2vec_name} "
                                f"--embedding-dim 50 "
                                f"--num-layers 4 "
                                f"--num-epochs {epochs} "
                                f"--suffix-name _{seq2vec_name}_5k_with_emb "
                                f"--pretrained-embedding-file data/glove.6B.50d.txt ")
            training_commands.append(training_command)
            continue

        model = load_pretrained_model(serialization_dir)
        models[seq2vec_name] = model

        vocab, _ = load_vocabulary(vocab_path)
        vocabs[seq2vec_name] = vocab

    if training_commands:
        print("\nFirst, please finish the missing model training using the following commands:")
        print("\n".join(training_commands))
        exit()


    original_instance = {"text_tokens": "the film performances were awesome".split()}
    updates = ["worst", "okay", "cool"]

    updated_instances = []
    for update in updates:
        updated_instance = copy.deepcopy(original_instance)
        updated_instance["text_tokens"][4] = update
Ejemplo n.º 18
0
    VOCAB_SIZE = 10000
    GLOVE_COMMON_WORDS_PATH = os.path.join("data", "glove_common_words.txt")

    print("Reading training instances.")
    train_instances = read_instances(args.train_data_file_path, MAX_NUM_TOKENS)
    print("Reading validation instances.")
    validation_instances = read_instances(args.validation_data_file_path,
                                          MAX_NUM_TOKENS)

    if args.load_serialization_dir:
        print(f"Ignoring the model arguments and loading the "
              f"model from serialization_dir: {args.load_serialization_dir}")

        # Load Vocab
        vocab_path = os.path.join(args.load_serialization_dir, "vocab.txt")
        vocab_token_to_id, vocab_id_to_token = load_vocabulary(vocab_path)

        # Load Model
        classifier = load_pretrained_model(args.load_serialization_dir)
    else:
        # Build Vocabulary
        with open(GLOVE_COMMON_WORDS_PATH, encoding='utf8') as file:
            glove_common_words = [
                line.strip() for line in file.readlines() if line.strip()
            ]
        vocab_token_to_id, vocab_id_to_token = build_vocabulary(
            train_instances, VOCAB_SIZE, glove_common_words)

        # Build Config and Model
        if args.model_name == "main":
            config = {
Ejemplo n.º 19
0
def predict(sentence):

    tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
    arg_length = len(sys.argv)

    # if (arg_length < 2):
    #     raise Exception("문장을 입력해주세요")

    # 데이터를 통한 사전 구성 한다.
    char2idx, idx2char, vocabulary_length = data.load_vocabulary()

    # 테스트용 데이터 만드는 부분이다.
    # 테스트로 넣은 문장이 들어온다 인코딩 부분 만든다.
    # input = ""
    # for i in sys.argv[1:]:
    #     input += i
    #     input += " "

    print('question:' + sentence)

    predic_input_enc, predic_input_enc_length = data.enc_processing([sentence],
                                                                    char2idx)
    # 학습 과정이 아니므로 디코딩 입력은
    # 존재하지 않는다.(구조를 맞추기 위해 넣는다.)
    # predic_output_dec = data.dec_input_processing([""], char2idx)
    # 학습 과정이 아니므로 디코딩 출력 부분도
    # 존재하지 않는다.(구조를 맞추기 위해 넣는다.)
    predic_target_dec, _ = data.dec_target_processing([""], char2idx)

    # 에스티메이터 구성한다.
    # 에스티메이터 구성한다.
    classifier = tf.estimator.Estimator(
        model_fn=ml.Model,  # 모델 등록한다.
        model_dir=DEFINES.check_point_path,  # 체크포인트 위치 등록한다.
        params={  # 모델 쪽으로 파라메터 전달한다.
            'hidden_size': DEFINES.hidden_size,  # 가중치 크기 설정한다.
            'layer_size': DEFINES.layer_size,  # 멀티 레이어 층 개수를 설정한다.
            'learning_rate': DEFINES.learning_rate,  # 학습율 설정한다.
            'teacher_forcing_rate':
            DEFINES.teacher_forcing_rate,  # 학습시 디코더 인풋 정답 지원율 설정
            'vocabulary_length': vocabulary_length,  # 딕셔너리 크기를 설정한다.
            'embedding_size': DEFINES.embedding_size,  # 임베딩 크기를 설정한다.
            'embedding': DEFINES.embedding,  # 임베딩 사용 유무를 설정한다.
            'multilayer': DEFINES.multilayer,  # 멀티 레이어 사용 유무를 설정한다.
            'attention': DEFINES.attention,  #  어텐션 지원 유무를 설정한다.
            'teacher_forcing':
            DEFINES.teacher_forcing,  # 학습시 디코더 인풋 정답 지원 유무 설정한다.
            'loss_mask': DEFINES.loss_mask,  # PAD에 대한 마스크를 통한 loss를 제한 한다.
            'serving': DEFINES.serving  # 모델 저장 및 serving 유무를 설정한다.
        })

    # 예측을 하는 부분
    predictions = classifier.predict(input_fn=lambda: data.eval_input_fn(
        predic_input_enc, predic_target_dec, DEFINES.batch_size))
    # 예측한 값을 인지 할 수 있도록
    # 텍스트로 변경하는 부분이다.
    answer = data.pred2string(predictions, idx2char)

    # 예측한 값을 인지 할 수 있도록
    # 텍스트로 변경하는 부분이다.
    print("answer: ", answer)

    return answer