> For the complete documentation index, see [llms.txt](https://soojle.gitbook.io/project/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://soojle.gitbook.io/project/undefined-2/undefined-4/lda.md).

# LDA 모델 학습 및 구현

## 개요

본 항목에서는 데이터 크롤러로 수집된 세종대학교와 관련된 모든 문서에 대하여 학습을 수행하고 토픽을 예측할 LDA 모델의 구현 과정에 대하여 서술한다.

## 학습 과정 명세

### HyperParameter

LDA 모델을 학습시키기 위한 하이퍼 파리미터는 다음과 같다.

**지속적으로 수정 예정**

| 파라미터 명      | 설명                    |
| ----------- | --------------------- |
| NUM\_TOPICS | 군집화를 수행할 총 토픽 수       |
| PASSES      | 전체 코퍼스에서 모델을 학습시키는 빈도 |
| iteration   | 각각 문서에 대해서 루프 반복 횟수   |
| POST\_LIMIT | 학습에 포함될 최소 글자수 제한     |

### Corpus 변환 과정

LDA 모델이 학습할 수 있도록 DB 내에 존재하는 모든 문서 데이터를 Copus로 변환하는 작업을 수행해야 한다.

#### DB 내의 데이터에 대하여 전처리 과정 수행

각 문서를 코퍼스로 변환하기 전에 여러 조건을 검토하여 해당 데이터가 학습 모델에 적용시킬지에 대한 전처리 과정을 수행한다.

```python
for post in posts:
		# 코퍼스 전처리 조건
		if post['info'].startswith("everytime") and len(post['post']) < EVERY_POST_LIMIT:
			continue
		if post['info'].startswith("navercafe") and len(post['title']) < NAVER_TITLE_LIMIT:
			continue
		if len(post['title'] + post['post']) < TOTAL_POST_LIMIT:
			continue
		if post['info'] in ["everytime_은밀한","main_bidding","everytime_끝말잇기 ", "everytime_퀴어 ","everytime_애니덕후 "]:
			continue
		if post['info'].startswith("everytime") and coll.find({"info":post['info']}).count() < 500:
			continue
		#
		token = post['token'] + post['tag']
		temp = pd.DataFrame({"text":[token]})
		df = df.append(temp, ignore_index = True)
```

확정된 문서를 바탕으로 코퍼스 변환 작업을 수행한다. 반환된 게시물의 토큰에 대하여 새로운 토큰을 모델의 딕셔너리에 추가하고, 해당 토큰을 딕셔너리 식별 값으로 변환하여 코퍼스를 생성한다.

```python
df = get_posts_df(col, idx, split_doc, update)
tokenized_doc = df['text']
dictionary.add_documents(tokenized_doc)
corpus += [dictionary.doc2bow(text) for text in tokenized_doc]
```

### 학습

수행된 코퍼스와 사전에 결정된 하이퍼 파라미터 인자를 사용하여 LDA 학습을 수행한다.

```python
ldamodel = LdaMulticore(
				corpus,
				num_topics = num_topics,
				id2word = dictionary,
				passes = PASSES,
				workers = WORKERS,
				iterations = ITERATION
				)
```

## 소스 코드 배포

{% embed url="<https://github.com/iml1111/SJ_AI>" %}

### **실행 요구사항**

| 분류   | 설명          |
| ---- | ----------- |
| 플랫폼  | Github      |
| 라이센스 | MIT License |

| 분류    | 버전명          |
| ----- | ------------ |
| 개발 언어 | Python 3.7.1 |

| 라이브러리 요구사항               |
| ------------------------ |
| attrs==19.1.0            |
| boto==2.49.0             |
| boto3==1.9.223           |
| botocore==1.12.223       |
| certifi==2019.6.16       |
| chardet==3.0.4           |
| colorama==0.4.1          |
| docutils==0.15.2         |
| funcy==1.13              |
| future==0.17.1           |
| gensim==3.8.0            |
| idna==2.8                |
| importlib-metadata==0.20 |
| Jinja2==2.10.1           |
| jmespath==0.9.4          |
| joblib==0.13.2           |
| JPype1==0.7.0            |
| konlpy==0.5.1            |
| MarkupSafe==1.1.1        |
| more-itertools==7.2.0    |
| nltk==3.4.5              |
| numexpr==2.7.0           |
| numpy==1.17.1            |
| packaging==19.1          |
| pandas==0.25.1           |
| pluggy==0.12.0           |
| py==1.8.0                |
| pyLDAvis==2.1.2          |
| pyparsing==2.4.2         |
| pytest==5.1.2            |
| python-dateutil==2.8.0   |
| pytz==2019.2             |
| requests==2.22.0         |
| s3transfer==0.2.1        |
| scipy==1.3.1             |
| six==1.12.0              |
| smart-open==1.8.4        |
| urllib3==1.25.3          |
| wcwidth==0.1.7           |
| zipp==0.6.0              |
| atomicwrites==1.3.0      |
