04.15 최종 프롬프트 완성 후 api활용 파생변수 생성 시작

2024. 4. 15. 23:58프로젝트/빵맛집 추천서비스 웹배포

 

01 "자치구" 선택 : 데이터셋 축소 해결 과정


1. 전담 튜터님과 튜터님의 상담을 받고 데이터 축소를 확정했다.

- 크롤링으로 약 20만건의 데이터를 수집했고, 한정된 시간 안에 리뷰 텍스트의 긍부정 분석을 통해 파생 변수를 생성하려다 보니 llm api를 활용하기로 결정했다.

- 최종 프로젝트는 군집화를 통해 비슷한 베이커리도 추천하는 검색서비스를 목적으로 한다. 검색 서비스의 정확도를 위해 욕심을 내다보니 api 모델 업그레이드를 원하게 됐다.

- 팀원이 합의 가능한 예산의 한도(최대 20만원)를 정했고 4.0으로 모든 자치구에 적용하면 추정된 결제금액이 150만원이었다. 예산 문제로 많은 고민과 기준을 세웠다.

- 어중간하게 결과를 내면 군집화의 결과를 제대로 분석할 수 없다는 의견과 하나의 구라도 정확한 서비스를 제공하며 다른 구로 확장 가능성을 염두에 두자는 의견이 일치했다.

- 우리팀이 최종으로 선택한 자치구는? 서울의 중심 자치구이며 기차역과 가까운 자치구 중 유입인구가 가장 많은 "서울특별시 중구"로 정했다.

 

2. gpt 모델버전 변경에 따른 프롬프트 제작

- 3.5모델에서 다시 4.0으로 변경했다.

- 4.0의 차이는 내가 원하는 형식으로 일정하게 결과 출력이 가능하다는 것이다.

- 웹서비스로 1차적 수정을 거치고, 테스트.csv와 api를 통해 실험을 했다.

- 완성된 프롬프트로 프로젝트를 한단계 더 진행할 수 있었다.

 

02 전담 튜터님 피드백 추가(도움이 많이 됐다.)


 

# 튜터님 상담 내용 더보기

더보기

- 추천이랑 검색이랑 작동 방식이 비슷하다.
- 우리의 프로젝트는 검색에 더 가까워 보인다.
- 특정 키워드를 바탕으로 비슷한 상품을 찾는 것이기 때문에 검색과 비슷해보인다.
- 검색은 결국 필터링하는 것이다. 프로젝트를 이런 관점에서 보면 좋지 않을까?
- 결국 토픽 기반의 추천이 될 것이다.
- 리뷰에서 비건을 찾아서 보여주는 과정이 낫지 않을까?

 

- 엘라스틱 서치: 검색할 때 많이 쓰는 것.
- 각 문서에 대해서 웹 페이지에서 문서들에 대한 정보가 있으니
- nlp 토크나이저: 형태소 단위로 쪼개는 것이다.
- 키워드 관련성 같은거 nlp 워드투백 같은거 비건과 유사한 단어를 집계할 수 있고

 

- 저라면? 일단 단순히 일단 비건이란 단어가 있는지 얼마나 있는지 알 수 있으니까
- seu같은거 상단에 노출되는 / 여러 지표 계산한 랭킹 계산 / 랭킹 최상단 고민 많이
- 토크나이저는 시간이 많이 소요될 것 같아서 다른 (우회) 방법을 고민할 것이다.
- 빵집리뷰는 문서들이 복잡하지 않으니까, 리뷰가 복잡하지 않으니까
- 토픽기반으로 유저에게 어떻게 제공할것인가, ui기반으로 어떻게 효율적 제공할지 고민
- 규칙 기반의 처리, 유저에게 어떻게 실제로 제공될 것인가를 고민한다.
- 유저가 어떤 의도로 비건빵을 검색했을까?, 어떤 결과를 기대할까? 생각해본다.

- 상점 몇 백개, 리뷰 몇천~몇만개도 충분하고 실제로 군집화를 많이 하는 수이다.
- 비용 문제 때문이라도, 하나라도 정확하게 하라.

 

- 해야할 건 가상 시나리오(비건 사용자라면), 필터, 랭킹 세 가지다.
- 기존에 나와있는 도구를 가지고 하면 시간 안에 클리어하지 못하는 것도 생각해야 된다.
- 그냥 여러분이 생각할 수 있는 도구를 가지고 했으면 해서 기술을 특정하지 않는 것이다.

- 단순히 리뷰 많은 것, 비건 많이 언급 되는 것을 필터링한다고 생각해본다.
- 프로젝트의 차별점을 ux관점에서 둔다고 생각해본다.
- 애매하게 기술적으로 접근하지 말자 산으로 가기 쉽다. (산으로 가는 경우를 많이 봤다.)
- 개인화 추천을 하고 싶은건 아니니까 "추천 모델" 이라는 단어 빼는게 좋겠다.

- 면접에서, 기업 입장에서 오해하기 쉬움. 꼬투리 잡히기 쉽다.
- 개인화 추천이란 건 고객의 데이터가 있어야 한다는데 우리는 아니다.

 

03 프롬프트 완성


1. 웹으로 실험하면서 만든 프롬프트

From now on, you must do three things: 1) Analyze the keywords in the bakery reviews in detail and assign integer scores ranging from -100 to +100 for all 25 characteristics. 2) 'Positive-Negative score': Assign 'P' if the entire review text is positive, or if it's impossible to determine. Assign 'N' if it is negative. 3) 'Unique menu item name': If there is a unique menu item specific to the store, output text as an exception at the end. If not, output 'None'. 'Characteristic conditions': 1) First, check if there are keywords related to the characteristic, if yes, assign True. 2) If True, assign scores closer to -100 for negative sentiments and closer to +100 for positive sentiments. 3) When the score is 0, Double-check to ensure accuracy. 4) The 'Pets' keyword must be related to the 'customer's' 'pet'. Wild animals do not qualify. 5) 'Wait': Assign negative scores as the customer waits longer. 6) The word '맛집' is very important to 'The bread is delicious'. 7) Infer and judge similar languages. 8) Characteristics that are unrelated or indeterminable are scored as 0. 9) 'View' is highly related to the 'scenery' characteristic. 10) Judgments must be based solely on keywords in the review. 11) Do not provide any further explanation, only scores. 12) 'Desserts' are also included in 'bread'. 13) Distinctly identify the sentence's subject. 14) 'The price is high' carries a negative connotation. 15) 'Mediocre' has a slightly negative connotation. 'Characteristics': 'The bread is delicious', 'The beverage is delicious', 'Vegan', 'No senior zone', 'No kids zone', 'Pets are allowed', 'Uses whole wheat', 'Nice view', 'Good atmosphere', 'Friendly', 'The store is clean', 'The restroom is clean', 'Parking available', 'The store is spacious', 'Plenty of seats', 'The seating is comfortable', 'There is a special menu', 'Photogenic', 'The music is good', 'Reservation is possible', 'Unique concept', 'The interior is beautiful', 'Good value for money', 'There is a wait', 'Good for health'. 'Additional score to be outputted': 'Positive-Negative score', 'Unique menu item name'. 'Output Rules': 1) Examples are as follows: '+98', '+32', '+3', '-23', '0', '+75', '-51', '-5', '+27', '+70', '+100', '-100', '-16', '-7', '+99', '+35', '+31', '-2', '0', '+70', '-54', '+26', '+94', '+36', '+1'. 'Additional score to be outputted': 'P', 'Unique menu item name' : 'bread name' 2) Make outputs as array format. 3) Print it in a single line. 4) If there is no mention, do not assume. <'Is that accurate?'>

Review:

- 팀원과 함께 수정하면서 여기서 참고해야할 문장을 가져다 사용했다.

 

# 감정분석: 정보가 부족하거나 모호한 상황에서 긍정의 분석 결과를 도출한다.
분석적으로 긍부정을 판단할 수 없는 경우 'P'를 넣는 게 맞다.

 

From now on, you must do three things: 1) Analyze the keywords in the bakery reviews in detail and assign integer scores ranging from -100 to +100 for all 25 characteristics. 2) 'Positive-Negative score': Assign 'P' if the entire review text is positive, or if it's impossible to determine. Assign 'N' if it is negative. 3) 'Unique menu item name': If there is a unique menu item specific to the store, output text as an exception at the end. If not, output 'None'. 'Characteristic conditions': 1) First, check if there are keywords related to the characteristic, if yes, assign True. 2) If True, assign scores closer to -100 for negative sentiments and closer to +100 for positive sentiments. 3) When the score is 0, Double-check to ensure accuracy. 4) The 'Pets' keyword must be related to the 'customer's' 'pet'. Wild animals do not qualify. 5) 'Wait': Assign negative scores as the customer waits longer. 6) The word '맛집' is very important to 'The bread is delicious'. 7) Infer and judge similar languages. 8) Characteristics that are unrelated or indeterminable are scored as 0. 9) 'View' is highly related to the 'scenery' characteristic. 10) Judgments must be based solely on keywords in the review. 11) Do not provide any further explanation, only scores. 12) 'Desserts' are also included in 'bread'. 13) Distinctly identify the sentence's subject. 14) 'The price is high' carries a negative connotation. 15) 'Mediocre' has a slightly negative connotation. 'Characteristics': 'The bread is delicious', 'The beverage is delicious', 'Vegan', 'No senior zone', 'No kids zone', 'Pets are allowed', 'Uses whole wheat', 'Nice view', 'Good atmosphere', 'Friendly', 'The store is clean', 'The restroom is clean', 'Parking available', 'The store is spacious', 'Plenty of seats', 'The seating is comfortable', 'There is a special menu', 'Photo', 'The music is good', 'Reservation is possible', 'Unique concept', 'The interior is beautiful', 'Price', 'There is a wait', 'Good for health'. 'Additional score to be outputted': 'Positive-Negative score', 'Unique menu item name'. 'Output Rules': 1) Examples are as follows: '+98', '+32', '+3', '-23', '0', '+75', '-51', '-5', '+27', '+70', '+100', '-100', '-16', '-7', '+99', '+35', '+31', '-2', '0', '+70', '-54', '+26', '+94', '+36', '+1'. 'Additional score to be outputted': 'P', 'Unique menu item name' : 'bread name' 2) Make outputs as array format. 3) Print it in a single line.

- photo, price 변경 추가.

- 마지막에 있는 '문장에 있는 것으로만 판단해' 류가 결과에 영향을 크게 미친다.

- 팀원과 함께 '주어가 없으면 빵으로 생각해'라고 했는데 이것도 추가했다 삭제.

 

2. 실제 사용된 프롬프트

system_prompt = """You must:1. Analyze keywords in detail from the provided bakery reviews and assign scores for all 27 characteristics. For characteristics 1 through 25, output scores between -100 and +100. The 'Pets' keyword must be related to the 'customer's' 'pet'. Wild animals do not qualify. 2. Read the input review text and determine the 26th characteristic, the emotional index, as either 0 or 1. 1 indicates a positive evaluation, and 0 indicates a negative evaluation. If the emotional index cannot be determined, give it a 1. 3. For the 27th characteristic, 'special menu item name', output the name of the special bread mentioned in the review in the order of the characteristics. If none, output 'None'. 4. The result should be output as a list of numbers only. Output example: [40, 50, 0, 0, 0, 10, -5, 0, 10, 0, 10, 30, -70, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 'bread name'] Characteristics: 'delicious bread', 'delicious drinks', 'vegan', 'no senior zone', 'no kids zone', 'pets allowed', 'uses whole wheat', 'good view', 'good atmosphere', 'friendly', 'clean store', 'clean restrooms', 'parking available', 'spacious store', 'plenty of seating', 'comfortable seating', 'special menu available', 'photo', 'good music', 'reservation available', 'unique concept', 'beautiful interior', 'price', 'waiting', 'healthy', 'overall review emotional score', 'special menu item name' **Please make sure to output the results in the format shown in the example.** ** No explanation is needed.**
"""

- 모두의 피땀 눈물이 완성 되었다. 결과물 중에 가장 만족스럽다.

- 아쉬운 점은 gpt는 아직 사람의 검증과 같은 마무리가 필요하다.

 

3. 숫자만 나올 때 참고하기

더보기
01 'The bread is delicious'
02 'The beverage is delicious'
03 'Vegan'
04 'No senior zone'
05 'No kids zone'

06 'Pets are allowed'
07 'Uses whole wheat'
08'Nice view'
09 'Good atmosphere'
10 'Friendly'

11 'The store is clean'
12 'The restroom is clean'
13 'Parking available'
14 'The store is spacious'
15 'Plenty of seats'

16 'The seating is comfortable'
17'There is a special menu'
18 'Photogenic'
19 'The music is good'
20 'Reservation is possible'

21 'Unique concept'
22 'The interior is beautiful'
23 'Good value for money'
24 'There is a wait'
25 'Good for health'

 

04 기타 프로젝트 기록


# 매니저님: 예산을 얼마 예상했는데 > 얼마 나와서 > 축소를 했다는 이유를 프로젝트에 넣어서 가져간다. 예산을 절감하기 위해 고민한 과정을 명확하게 가져가는 것이 중요하다.

# 공공데이터포털 기준으로 종로구 1,760개의 문화재, 중구 1,687개의 문화재가 있는데 이 수치에는 관광지도 포함되어 있어서 문화재로만 볼 수 없다는 단점이 있다.

 

# 컬럼내용 모두보기

pd.set_option('display.max_columns', 30)


# 토큰 코드 (함수 안에 들어가면 전역 변수 사용해야 한다.)

total_bill_USD = (response.usage.prompt_tokens*0.01 +response.usage.completion_tokens*0.03)/1000
# 24.04.15 기준 환율 1USD = 1383.50 KRW
total_bill_KRW = total_bill_USD*1383.50
print("총 소모 비용 : {} 원".format(total_bill_KRW))


# 허깅페이스 무료 긍부정 분석 해보기

- 튜터님의 조언: 15,000개의 데이터로도 군집화는 충분하다.

# 리뷰텍스트 1000개에 6.9달러. 약 7달러가 소모된다.

- 15,000개의 데이터라면 최소 103.5달러이고 그 이상 여유롭게 잡는다.


# 남은 15,000개의 리뷰텍스트를 7000개, 5000개, 3000개로 나눠 진행한다.

- 팀원마다 토큰이 나뉘어져 있다.