따꿍의 프로젝트

모델 선정 및 사용 방법 조사 본문

웹프로젝트/자기주도진로설계프로젝트

모델 선정 및 사용 방법 조사

공장 주인 따꿍 2025. 9. 17. 09:00

모델 선정

huggingface에 bart-large-cnn 모델이 가장 잘 쓰이는 요약 모델이길래 사용하기로 결심하였다. 

팀원들에게 물어보니 아무리 영어로 키워진 모델이라도 잘만 프롬프팅 하면 한국어도 잘 요약한다고 해서 그냥 써보기로 했다. 

 

0. 허깅페이스는 무엇인가?(huggingface.co)

허깅페이스(Hugging Face)는 인공 지능(AI) 분야에서 자연어 처리(NLP)를 중심으로 한 다양한 딥러닝 모델과 도구들을 제공하는 회사.  오픈소스 라이브러리인 'Transformers'를 통해 유명해짐. 이 라이브러리는 다양한 전처리 방법, 모델 아키텍처(BERT, GPT, T5 등), 그리고 후처리 방법을 포함하여 NLP 분야에서 광범위하게 사용.

- AI관련 깃허브 느낌

- 내가 만든 모델/데이터셋을 Public, private로 올릴수 있고, Public일 경우 누구나 내가 올려놓은 데이터셋, 모델을 사용할수 있음

- 당연히 다른 사람이 만든 언어모델이 Public으로 공개되어 있다면, 나는 해당 모델을 기반으로 파인 튜닝이 가능함.

전처리(Preprocessing)
모델에 입력하기 전에 데이터를 다듬는 과정 예시: 텍스트: 특수문자 제거, 불필요한 공백 제거, 토큰화(tokenization) 이미지: 크기 조정, 정규화(normalization), 흑백 변환 표 데이터: 결측치 처리, 스케일링, 인코딩
👉 목적: 데이터를 모델이 이해하기 좋은 형태로 바꾸기

후처리(Postprocessing)
모델이 출력한 결과를 사람이 쓰기 좋은 형태로 바꾸는 과정 예시: 텍스트 요약 결과: 불필요한 토큰(예: <pad>) 제거, 문법적으로 자연스럽게 다듬기 분류 결과: 확률 벡터 → 가장 높은 확률 라벨 선택 이미지 결과: 색상 복원, 디코딩, 후처리 필터링
👉 목적: 모델 결과를 사람이 바로 사용할 수 있도록 정리하기

 

 


 

'YOUR_TOKEN_HERE'에는 huggingface에서 꺼내왔는 토큰을 넣어준다


이런 모델들은 이미 한국어 넣어도 잘 요약하기 때문에 파인튜닝할 필요가 없다고 한다. 

그래서 프롬프팅이 뭔지 알아봤다.

 

Great question 🙌 — prompting is the practice of telling a language model what you want it to do by giving it carefully designed text instructions (a prompt).

Think of it like talking to a very smart but literal assistant: the way you phrase the request often determines the quality of the answer.

 

 

  • Different prompts → very different outputs.
  • With good prompting, you can avoid retraining and still get the model to follow your needs.
  • Prompting is often the first step before fine-tuning — test whether you can solve the problem with clever instructions alone.

General Prompting Strategies

1. Be explicit & specific

  • Bad: “Tell me about dogs.”
  • Better: “Give me a 3-sentence description of dogs as pets, focusing on their personality.”

2. Set the role or persona

  • “You are a professional lawyer. Summarize this contract in plain English.”
  • Models follow roles surprisingly well

3. Few-shot prompting

  • Provide examples of input → output so the model learns the pattern.

4. Chain-of-thought prompting

  • Ask the model to reason step by step.
  • “Solve this math problem step by step before giving the final answer.”
  • Helps reduce mistakes in logic-heavy tasks.

5. “Let’s think step by step” trick

  • Even just adding that phrase makes models more careful.
  • Example: “Before answering, let’s think step by step.”

6. Delimit inputs clearly

  • Use special markers (```, <<< >>>, [TEXT], etc.) so the model knows exactly what is input vs. instruction.
 
Summarize the following in 1 sentence: <<< The tall rocky mountains surrounding the river house many thrilling hiking trails with breathtaking views. >>>

 

 

7. Constrain the output format

  • “Answer in JSON with fields: title, summary, keywords.”
  • “Give exactly 3 bullet points, each under 10 words.”

8. Use “meta” prompts

  • Tell the model how to think.
  • “First, identify the problem. Then list possible solutions. Finally, give the best solution.”

9. Iterative refinement

  • Start broad, then refine.
    1. “Give me a rough draft of a speech about AI safety.”
    2. “Make it shorter and more formal.”
    3. “Add a persuasive closing line.”

10. Error-correction prompting

  • Ask the model to check or improve its own output.
  • “Rewrite the above paragraph to be more concise and professional.

You’d need to prompt a summarization model even though its primary function is to summarize, because prompting helps the model understand exactly what kind of summary you want. Think of it like giving instructions rather than just handing it a text. Here’s why prompting matters:

1. Guiding the style or focus

A generic summarization model doesn’t know whether you want:

  • A short summary (1–2 sentences)
  • A detailed summary (paragraph-length)
  • A bullet-point list
  • A summary focusing on specific aspects, like financial results, technical points, or emotions

Example prompt:

“Summarize this article in three bullet points focusing on environmental impact.”

2. Clarifying format

Some models can generate plain text, lists, or even structured outputs (JSON, tables). If you don’t prompt for format, it may give a summary that’s inconvenient for your use case.

Example prompt:

“Summarize this text as a JSON object with keys title and summary.”

3. Improving relevance

Even summarization models can include irrelevant details if the text is long or complex. Prompting can nudge the model to prioritize important info.

Example prompt:

“Summarize the following text, keeping only key findings and recommendations.”

4. Handling ambiguous or multi-topic texts

When an article covers multiple topics, the model may need guidance to focus on the topic you care about.

Example prompt:

“Summarize the section about marketing strategy, ignoring the financial data.”

TL;DR:

Prompting a summarization model isn’t about “teaching it to summarize” — it already can. Prompting is about telling it how to summarize, in what style, and with what focus.


⭐ 근데 내가 가지고 있는 모델은 어떤 텍스트 넣으면 맨날 같은 결과가 나오던데?
"더 길게 요약해줘", "조금만 더 자세하게 요약해줘" 이런 기능 없는것 같았는데

프럼프팅을 어떻게 하는걸까? 지원하긴 할까?

 

1. Deterministic output

  • bart-large-cnn uses beam search for decoding by default, which tends to produce the most likely summary.
  • That’s why it always gives the same output for the same input.

You can make it a little less deterministic using parameters like:

  • num_beams: controls how many alternative paths the model considers.
  • do_sample=True and top_k/top_p: makes it generate slightly different summaries each time.

2. No built-in instructions

  • BART summarization isn’t instruction-tuned. It won’t inherently respond to prompts like “make it longer” or “focus on the marketing points.”
  • It just takes text → produces a summary.

You can try workarounds:

  • Prepend instructions in the input text:This sometimes nudges the model to include more relevant info, but it’s not guaranteed.
  •  
    "Summarize the following text in detail focusing on key marketing insights: [article here]"
  • Fine-tune the model yourself on examples where the summary has the style/length you want.

3. Alternatives if you need more control

If you want length, style, or focus control reliably:

  • Use instruction-tuned models like flan-t5-large or llama-2-chat.
  • These models can take natural language prompts like:
  • “Summarize this in 5 bullet points focusing on technical details.”

근데 아무리 해도 프롬프팅이 가능한 껀덕지가 안 보이길래 찾아보니까

Models like facebook/bart-large-cnn are pretrained summarization models, so out of the box they always do a generic summarization. That’s why you’re seeing the same output every time you feed in the same text. They don’t have built-in “style” or “focus” controls in the same way an instruction-tuned model would.

Here’s the breakdown:

 

1. Deterministic output

  • bart-large-cnn uses beam search for decoding by default, which tends to produce the most likely summary.
  • That’s why it always gives the same output for the same input.

You can make it a little less deterministic using parameters like:

  • num_beams: controls how many alternative paths the model considers.
  • do_sample=True and top_k/top_p: makes it generate slightly different summaries each time.

2. No built-in instructions

  • BART summarization isn’t instruction-tuned. It won’t inherently respond to prompts like “make it longer” or “focus on the marketing points.”
  • It just takes text → produces a summary.

결론

다른 모델을 선택하거나...

건빵이가 조언하기를, Gemini AI API를 사용해보라고 하길래 그걸 함 사용해볼 생각이다.

 

네, 맞습니다! API를 불러와서 코드로 구현하는 것도 당연히 가능합니다. ✅

웹사이트에서 하는 것과 동일한 기능을 Google AI Gemini API를 사용해서 직접 개발하는 애플리케이션에 통합할 수 있습니다.

API를 사용하면 파일을 업로드하고, 해당 파일을 기반으로 Gemini 모델에게 요약이나 질문을 요청하는 과정을 자동화할 수 있습니다.

Gemini API로 파일 요약하는 Python 코드 예시

아래는 Python 코드를 사용해 파일을 업로드하고 요약을 요청하는 예시입니다.

1. 라이브러리 설치

먼저 Google AI Python SDK를 설치해야 합니다.

Bash
 
pip install -q google-generativeai

2. API 키 발급 및 설정

API를 사용하려면 API 키가 필요합니다. 아래 링크에서 API 키를 발급받을 수 있습니다.

3. Python 코드 실행

아래 코드는 lecture_notes.txt라는 예시 파일을 업로드하고, Gemini Pro 모델에게 요약을 요청하는 전체 과정입니다.

Python
 
import google.generativeai as genai
import os

# --- 1. API 키 설정 ---
# 실제 키로 바꿔주세요. 
# 더 안전한 방법은 os.environ.get("GEMINI_API_KEY")처럼 환경 변수를 사용하는 것입니다.
# 여기서는 간단한 설명을 위해 직접 키를 입력하는 방식을 보여드립니다.
# genai.configure(api_key="YOUR_API_KEY") 

# Google Colab을 사용한다면 아래 코드로 쉽게 키를 설정할 수 있습니다.
from google.colab import userdata
genai.configure(api_key=userdata.get('GEMINI_API_KEY'))


# --- 2. 요약할 파일 준비 (예시) ---
# 'lecture_notes.txt'라는 이름으로 예시 파일을 만듭니다.
with open("lecture_notes.txt", "w") as f:
    f.write("""
    머신러닝 프로젝트 진행 순서

    1. 문제 정의: 해결하고자 하는 비즈니스 문제를 명확히 정의한다. 예측할 대상이 무엇인지 결정하는 단계.
    2. 데이터 수집: 모델 학습에 필요한 데이터를 모은다. 내부 데이터베이스, 외부 API, 웹 크롤링 등 다양한 소스를 활용.
    3. 데이터 전처리 및 탐색(EDA): 수집한 데이터의 품질을 높이는 과정. 결측치 처리, 이상치 제거, 데이터 정규화 등을 수행. 데이터의 패턴과 인사이트를 파악.
    4. 모델 선택 및 학습: 해결할 문제에 적합한 머신러닝 모델(예: 선형 회귀, 랜덤 포레스트, 신경망)을 선택하고, 준비된 데이터로 모델을 학습시킨다.
    5. 모델 평가: 학습된 모델의 성능을 평가 지표(예: 정확도, 정밀도, 재현율)를 통해 측정한다. 과적합 여부를 반드시 확인.
    6. 모델 배포 및 모니터링: 성능이 검증된 모델을 실제 서비스 환경에 배포한다. 배포 후에도 지속적으로 성능을 모니터링하고 필요시 모델을 업데이트한다.
    """)

# --- 3. 파일 API에 업로드 ---
# File API를 사용해 파일을 Gemini 서버에 업로드합니다.
print("파일 업로드 중...")
uploaded_file = genai.upload_file(path="lecture_notes.txt", display_name="강의 노트")
print(f"파일 업로드 완료: {uploaded_file.uri}")


# --- 4. 모델 설정 및 프롬프트 전송 ---
# 파일을 처리할 수 있는 gemini-1.5-pro-latest 또는 gemini-pro-vision 모델을 사용합니다.
model = genai.GenerativeModel('models/gemini-1.5-pro-latest')

# 프롬프트에 업로드한 파일과 요청사항을 함께 전달합니다.
prompt = [
    "첨부된 강의 노트 파일의 핵심 내용을 글머리 기호(bullet point) 형식으로 요약해줘.",
    uploaded_file, # 여기에 업로드된 파일 객체를 넣어줍니다.
]

# --- 5. 요약 결과 생성 및 출력 ---
response = model.generate_content(prompt)

# 생성된 텍스트에서 마크다운을 제거하여 깔끔하게 출력합니다.
from IPython.display import display, Markdown
display(Markdown(response.text))

# --- 6. (선택사항) 업로드한 파일 삭제 ---
genai.delete_file(uploaded_file.name)
print(f"파일 '{uploaded_file.display_name}' 삭제 완료.")

코드의 핵심 원리

  1. genai.upload_file(): 내 컴퓨터에 있는 파일을 Google 서버로 업로드하고, 파일에 대한 참조(reference)를 받습니다.
  2. prompt = ["요청사항 텍스트", uploaded_file]: 프롬프트를 구성할 때, 텍스트뿐만 아니라 업로드된 파일 객체 자체를 리스트에 함께 넣어 보냅니다.
  3. model.generate_content(prompt): 모델은 텍스트와 파일 내용을 모두 이해하고 요청에 맞는 답변을 생성합니다.

이처럼 API를 사용하면 웹사이트에서 수동으로 하던 작업을 코드를 통해 자동화하고, 다른 서비스와 연동하는 등 훨씬 더 다양하게 활용할 수 있습니다.


중간 성과 발표

https://www.canva.com/design/DAG0s6-sO0E/cqOoL7nipNZQh18qJCdvmw/edit?locale=en&ui=eyJBIjp7IkUiOnsiQSI6dHJ1ZX19fQ