Machine Learning&Deep Learning/NLP
Python - brown corpus에서 frequency가 float 형태로 나오는 문제
yuzumuzu
2023. 5. 2. 15:08
따봉 챗지피티야 고마워
Mission
브라운코퍼스에서, 연달아 나타나는 2개의 단어에 대해서, 각 카테고리 별로 몇번 나타나는지를 출력해 주는 함수를 정의하고자 한다.
My Code
from nltk.corpus import brown
def freq2word(word1,word2):
genres=brown.categories()
for genre in genres:
#brown corpus의 단어들 중 'genre' 카테고리에 있는 단어쌍 저장하기
bigrams=list(nltk.bigrams(brown.words(categories=genre))
#빈도수 받을 변수 생성
fdist=nltk.FreqDist(bigram for bigram in bigrams)
#fdist의 빈도수 받아내기
freq=fdist.freq((word1,word2))
print(category,':', freq)
Problem
빈도순데 왜 결괏값이 float 형태이며 1이하로 나오는가! 챗지피티야 도와줘
The reason that freq has a float type is because it is being calculated by dividing the frequency of the bigram (word1, word2) by the total number of bigrams in the corpus. In your code, fdist.freq((word1, word2)) returns a float value between 0 and 1, representing the frequency of the bigram in the corpus. This is different from fdist[(word1, word2)], which would return an integer representing the count of occurrences of the bigram in the corpus.
우와아
The freq() function returns a float value between 0 and 1 하기 때문에 빈도 분포만 받아서 바로 출력하면 인티저로 출현횟수만 나오나보다.
해결
from nltk.corpus import brown
def fdist2word(word1, word2):
categories = brown.categories()
for category in categories:
bigrams = list(nltk.bigrams(brown.words(categories=category)))
fdist = nltk.FreqDist(bigram for bigram in bigrams)
freq = fdist[(word1, word2)]
print(f'({category}:{freq})')