[AI 모델 탐험기] #5 오만과 편견

Changyeop·2021년 5월 6일
2
post-thumbnail

해당 글은 제가 커먼컴퓨터에서 재직 중에 작성한 글이며 회사 공식 블로그에도 올라오고 있으며, dleunji님께서 AI Network Forum에 작성하신 글을 블로그 형식에 맞춰 수정한 글입니다

제가 오늘 소개드릴 모델은 소설 ‘오만과 편견’을 가지고 학습한 모델입니다. 프로젝트를 바로 확인해 보시고 싶으신 분들은 다음 링크를 참조해주세요

학습된 모델 사용해 보기 (TabTab) : https://link.ainize.ai/3vIdIuG

Demo : https://link.ainize.ai/3erIEtz

API : https://ainize.ai/scy6500/GPT2-PrideAndPrejudice?branch=main


소설을 읽을 때 소설이 내가 원하는 방향과 다르게 흘러가 ‘아 이야기가 이렇게 흘러갔다면…’ 이라는 생각을 해보신 적이 있나요? 이 답답함을 해소하기 위해 AI 모델에 소설을 학습하여 직접 이야기를 바꿔보겠습니다.

제가 선택한 소설은 오만과 편견입니다. 이 소설은 여주인공인 Elizabeth는 Darcy와의 첫 만남에서 그가 오만하다고 느꼈고, 점차 편견이 굳어져 엇갈리게 됩니다. 그러나 무수한 사건들을 거치며 Darcy는 그의 오만을 내려놓고, Elizabeth는 오해를 풀며 마침내 두 사람은 사랑에 빠진다는 내용입니다. 만약 사건의 결과가 달라진다면 그 두사람의 사랑은 이루어졌을까요?

If

  • 만약 두 사람이 첫 만남에 오해하지 않았더라면
  • Darcy를 험담하는 Wickham을 믿지 않았다면
  • Darcy가 Elizabeth에게 편지를 보내지 않았더라면
  • Wickham과 Elizabeth의 여동생 Lydia가 야반도주를 하지 않았다면

이를 알아보기 위해 ‘오만과 편견’을 가지고 학습해보겠습니다.

오만과 편견

‘오만과 편견’의 원문은 Project Gutenburg 에서 무료로 구하였습니다. 그리고 고전 소설로 이미 저작권이 만료되어 데이터 학습 및 각색에 문제가 없음을 확인하였습니다.

데이터 전처리를 위해 데이터를 살펴보겠습니다. 데이터에 각 챕터의 헤딩, 불필요한 개행 문자가 있군요. 제거하겠습니다. 대신 소설임을 감안하여 쌍따옴표(“”)는 그대로 남겨두었습니다.

file_name = "Pride and Prejudice.txt"
f = open(file_name, "rt", encoding='utf-8')
file = f.readlines()
f.close()
sentences = []
start = 0
for line in file:
		# To know the beginning of the volumes
    if line == ("PRIDE & PREJUDICE.\\n"):
        start = 1
        continue
    elif start == 0:
        continue
		# Remove CHAPTER heading
    elif line.startswith("CHAPTER"):
        continue
		# Remove CRLF
    elif line == "\\n":
        continue
		# To know the end of CHAPTER
    elif line.startswith("END OF"):
        start = 0
        continue
		# To know the end of data
    elif line == "       *       *       *       *       *":
        break
    # To remove symbols
    line = line.replace("_", "")
    line = line.replace("--", " ")
		# To remove unnecessary space
    line = line.strip()
		# After remove CRLF, create a space between the sentences
    line = line + " "
    sentences.append(line)
training_data = ''.join(sentences)
training_file = open('preprocess_pp.txt',"w")
training_file.write(training_data)
training_file.close()

소설가가 되어보자

  • Ainize의 DEMO 사용하기

우선 이 모델을 코드없이 사용해보겠습니다.

Ainize에서 제공하는 DEMO 페이지에서 각색하고 싶은 내용을 입력후 Summit 버튼을 누르면 각색된 내용을 확인할 수 있습니다. 위에서 사용한 데모는 link에서 사용할 수 있습니다.

  • Ainize의 API 사용하기

이번에는 Ainize에서 제공하는 API를 사용하여 모델을 사용해보겠습니다. API에 관한 내용은 link에서 확인할 수 있습니다.

base_text = input("base text : ")
length = input("length : ")
files = {
    "text": (None, base_text),
    "length": (None, length)
}
response = requests.post("https://main-gpt2-pride-and-prejudice-scy6500.endpoint.ainize.ai/generate", files=files)
status_code = response.status_code
if status_code == 200:
  result = response.json()["0"]
  print("result :\\n", result)
elif status_code == 400:
  print("Bad Request Error")
elif status_code == 429:
  print("Too many requests")
elif status_code == 500:
  print("Server-side Error")

이와 같은 방식으로 호출할 수 있으며 link에서도 사용해볼 수 있습니다.

  • 직접 모델을 학습하여 사용하기

이번에는 Teachable NLP를 통해 GPT-2 모델을 Fine-Tuning 하여 모델을 사용해보겠습니다.

Teachable-NLP에 전처리 과정을 마친 데이터를 넣고 Model size는 Small 로, epoch는 5로 설정한 뒤 GPT-2 모델을 Fine-tuning 하였습니다. 트레이닝 과정이 종료되면, Test your model 을 클릭합니다.

클릭하면 열리는 TabTab 화면 에서 ‘오만과 편견’을 각색해보실 수 있습니다.

저는 이 소설을 읽으며 Elizabeth는 Darcy와 춤춘 후 바로 사랑에 빠지면 어떨까 라는 생각이 들어서 이 내용을 가지고 스토리를 전개해보겠습니다. 그랬더니

Mr. Darcy was nice and danced only once with Elizabeth. That was all. He liked nothing else but the dancing." "Indeed," said Elizabeth gravely, "but dancing means dancing. It means thinking what you think." And so she did. With some degree of amusement, and the most earnestness, she began in earnest with these remarks: "You see, I think, a slight change in Mr. Bennet's manner; but I think it is due to his taste for dancing which has given him an advantage in his own society. When I was young, and not much better acquainted with Mr. Bennet, than with him himself, I tried to imitate him and learn his manners; and I was obliged to lose it. The object, moreover, is to be in the habit of dancing, and Mr. Bingley is a very good fellow; and I must confess that I had been at first the little more surprised I was when I was asked to join him, for, while Mr. Bingley danced, he gave a little account of dancing.

와 같은 결과를 얻을 수 있었습니다. 과연 그들의 로맨스는 어떤 방향으로 흘러갈까요? 오만과 편견을 마음껏 각색해보세요!

레퍼런스

  1. [Teachable NLP] New Pride and Prejudice with GPT-2
  2. Pride and Prejudice by Jane Austen
  3. Pride and Prejudice Ainize
  4. Pride and Prejudice TabTab
  5. Teachable NLP

AI 네트워크는 블록체인 기반 플랫폼으로 인공지능 개발 환경의 혁신을 목표로 하고 있습니다. 수백만 개의 오픈 소스 프로젝트가 라이브로 구현되는 글로벌 백엔드 인프라를 표방합니다.

최신 소식이 궁금하시다면 아래 커뮤니케이션 채널을 참고해주시기 바랍니다. 다시 한 번 감사합니다.

AI네트워크 공식 홈페이지: https://ainetwork.ai/

공식 텔레그램: https://t.me/ainetwork_kr

아이나이즈(Ainize): https://ainize.ai

유튜브: https://www.youtube.com/channel/UCnyBeZ5iEdlKrAcfNbZ-wog

페이스북:https://www.facebook.com/ainetworkofficial/

포럼:https://forum.ainetwork.ai/

AIN Price chart: https://coinmarketcap.com/currencies/ai-network/onchain-analysis/

profile
성창엽(24)/???

0개의 댓글