Skip to content

Commit

Permalink
노트북 번역
Browse files Browse the repository at this point in the history
  • Loading branch information
rickiepark committed Jul 31, 2021
1 parent 32686f3 commit 5e627bb
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 73 deletions.
87 changes: 42 additions & 45 deletions notebooks/README.md
Original file line number Diff line number Diff line change
@@ -1,64 +1,61 @@
This folder contains notebooks showcasing concepts covered in the book.
Most of the examples only use one of the subfolders in archive
(the one that contains data for writers.stackexchange.com).
노트북 폴더에는 책에서 다루는 개념을 위한 예제 코드를 담고 있습니다. 대부분의 예제는 아카이브(writers.stackexchange.com 데이터)에 있는 서브폴더 중 하나만 사용합니다.

I've included a processed version of the data as a `.csv` for convenience.
번거로움을 줄이기 위해 전처리된 데이터를 `.csv` 파일로 포함시켰습니다.

If you want to generate this data yourself, or generate it for another subfolder,
you should:
직접 이 데이터를 생성하고 싶거나 다른 폴더에 데이터를 생성하고 싶다면 다음을 참고하세요:

- Download a subfolder from the stackoverflow [archives][archives]
- 스택익스체인지 [아카이브][archives]에서 한 서브폴더를 다운로드합니다.

- Run `parse_xml_to_csv` to convert it to a DataFrame
- `parse_xml_to_csv`을 실행해 데이터프레임으로 변환합니다.

- Run `generate_model_text_features` to generate a DataFrames with precomputed features
- `generate_model_text_features`을 실행해 미리 계산된 특성을 포함한 데이터프레임을 생성합니다.

[archives]: https://archive.org/details/stackexchange

The notebooks belong to a few categories of concepts, described below.
이 노트북들은 다음과 같은 몇 개의 카테고리로 나눌 수 있습니다.

### Data Exploration and Transformation
### 데이터 탐색과 변환

- [Dataset Exploration][DatasetExploration]
- [Splitting Data][SplittingData]
- [Vectorizing Text][VectorizingText]
- [Clustering Data][ClusteringData]
- [Tabular Data Vectorization][TabularDataVectorization]
- [Exploring Data To Generate Features][ExploringDataToGenerateFeatures]
- [데이터셋 탐색][DatasetExploration]
- [데이터 분할][SplittingData]
- [텍스트 벡터화][VectorizingText]
- [데이터 군집][ClusteringData]
- [표 데이터 벡터화][TabularDataVectorization]
- [특성 생성을 위한 데이터 탐색][ExploringDataToGenerateFeatures]

### Initial Model Training and Performance Analysis
### 초기 모델 훈련과 성능 분석

- [Train Simple Model][TrainSimpleModel]
- [Comparing Data To Predictions][ComparingDataToPredictions]
- [Top K][TopK]
- [Feature Importance][FeatureImportance]
- [Black Box Explainer][BlackBoxExplainer]
- [간단한 모델 훈련][TrainSimpleModel]
- [데이터와 예측 비교Comparing Data To Predictions][ComparingDataToPredictions]
- [ K][TopK]
- [특성 중요도][FeatureImportance]
- [블랙 박스 설명 도구][BlackBoxExplainer]

### Improving the Model
### 모델 향상

- [Second Model][SecondModel]
- [Third Model][ThirdModel]
- [두 번째 모델][SecondModel]
- [세 번째 모델][ThirdModel]

### Model Comparison
### 모델 비교

- [Comparing Models][ComparingModels]
- [모델 비교][ComparingModels]

### Generating Suggestions from Models
### 모델을 사용한 추천 생성

- [Generating Recommendations][GeneratingRecommendations]
- [추천 생성][GeneratingRecommendations]

[BlackBoxExplainer]: ./black_box_explainer.ipynb
[ClusteringData]: ./clustering_data.ipynb
[ComparingDataToPredictions]: ./comparing_data_to_predictions.ipynb
[ComparingModels]: ./comparing_models.ipynb
[DatasetExploration]: ./dataset_exploration.ipynb
[ExploringDataToGenerateFeatures]: ./exploring_data_to_generate_features.ipynb
[FeatureImportance]: ./feature_importance.ipynb
[GeneratingRecommendations]: ./generating_recommendations.ipynb
[SecondModel]: ./second_model.ipynb
[SplittingData]: ./splitting_data.ipynb
[TabularDataVectorization]: ./tabular_data_vectorization.ipynb
[ThirdModel]: ./third_model.ipynb
[TopK]: ./top_k.ipynb
[TrainSimpleModel]: ./train_simple_model.ipynb
[VectorizingText]: ./vectorizing_text.ipynb
[BlackBoxExplainer]: ./notebooks/black_box_explainer.ipynb
[ClusteringData]: ./notebooks/clustering_data.ipynb
[ComparingDataToPredictions]: ./notebooks/comparing_data_to_predictions.ipynb
[ComparingModels]: ./notebooks/comparing_models.ipynb
[DatasetExploration]: ./notebooks/dataset_exploration.ipynb
[ExploringDataToGenerateFeatures]: ./notebooks/exploring_data_to_generate_features.ipynb
[FeatureImportance]: ./notebooks/feature_importance.ipynb
[GeneratingRecommendations]: ./notebooks/generating_recommendations.ipynb
[SecondModel]: ./notebooks/second_model.ipynb
[SplittingData]: ./notebooks/splitting_data.ipynb
[TabularDataVectorization]: ./notebooks/tabular_data_vectorization.ipynb
[ThirdModel]: ./notebooks/third_model.ipynb
[TopK]: ./notebooks/top_k.ipynb
[TrainSimpleModel]: ./notebooks/train_simple_model.ipynb
[VectorizingText]: ./notebooks/vectorizing_text.ipynb
55 changes: 27 additions & 28 deletions notebooks/vectorizing_text.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"# Vectorizing text\n",
"# 텍스트 벡터화하기\n",
"\n",
"As you may expect it, the goal of vectorizing text is to transform text input into a numerical representation. Ideally, this numerical representation should carry semantic meaning that make it easier for an ML model to detect patterns in a corpus of text.\n",
"예상했겠지만 텍스트 벡터화의 목표는 텍스트 입력을 수치 표현으로 변환하는 것입니다. 이상적으로는 이 수치 표현이 머신러닝 모델이 텍스트에 있는 패턴을 쉽게 감지할 수 있도록 의미있는 정보를 나타내야합니다.\n",
"\n",
"There are multiple ways to vectorize text. I'll demonstrate two here:\n",
"- TF-IDF, which builds vectors for documents based on relative word frequency within the given corpus\n",
"- Pretrained models which leverage information from other corpuses\n",
"텍스트를 벡터화하는 방법에는 여러 가지가 있습니다. 여기서는 두 가지를 소개합니다:\n",
"- TF-IDF는 주어진 말뭉치에서 단어의 상대적인 등장 횟수를 기반으로 문서를 벡터화합니다.\n",
"- 사전 훈련된 모델로 다른 말뭉치의 정보를 활용합니다.\n",
"\n",
"We start by loading the data, and getting a training and test split as we saw in [splitting data](https://github.com/hundredblocks/ml-powered-applications/blob/master/notebooks/splitting_data.ipynb)."
"데이터 분할 [노트북](https://github.com/rickiepark/ml-powered-applications/blob/master/notebooks/splitting_data.ipynb)에서처럼 데이터를 로드하고 훈련 세트와 테스트 세트로 분할합니다."
]
},
{
Expand Down Expand Up @@ -51,9 +51,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## TF-IDF on ngrams\n",
"## TF-IDF\n",
"\n",
"[TF-IDF](https://en.wikipedia.org/wiki/Tf%E2%80%93idf) creates embeddings based on the relative frequency of each word in each document as compared to the corpus as a whole. We create TF-IDF embeddings using sklearn below."
"[TF-IDF](https://en.wikipedia.org/wiki/Tf%E2%80%93idf)는 전체 말뭉치와 비교하여 문서에 있는 각 단어의 상대적인 빈도를 기반으로 임베딩을 만듭니다. `sklearn`을 사용해 TF-IDF를 만듭니다."
]
},
{
Expand All @@ -77,8 +77,8 @@
"source": [
"questions = train_author[train_author[\"is_question\"]]\n",
"raw_text = questions[\"body_text\"]\n",
"# Extract a label to use as a color on our plots. \n",
"# This label does not need to be the same label as the one for the classifier.\n",
"# 그래프에 컬러로 표시할 레이블을 추출합니다.\n",
"# 이 레이블은 분류기를 위한 레이블과 같을 필요는 없습니다.\n",
"sent_labels = questions[\"AcceptedAnswerId\"].notna()\n",
"\n",
"sent_labels.value_counts()"
Expand All @@ -101,12 +101,11 @@
}
],
"source": [
"# Create an instance of a tfidf vectorizer, \n",
"# We could use CountVectorizer for a non normalized version\n",
"# tfidf 객체를 만듭니다.\n",
"vectorizer = TfidfVectorizer(ngram_range=(1, 2), min_df=5, max_features=2**21)\n",
"\n",
"# Fit our vectorizer to questions in our dataset\n",
"# Returns an array of vectorized text\n",
"# 데이터셋에 있는 질문에 적용합니다.\n",
"# 벡터화된 배열을 반환합니다.\n",
"bag_of_words = vectorizer.fit_transform(raw_text)\n",
"\n",
"bag_of_words.shape"
Expand All @@ -116,7 +115,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"We have now vectorized our text. This process is also called embedding, and the resulting vectors are often referred to as embeddings. We can visualize the embeddings by projecting them to two dimensions using a dimensionality reducing technique such as PCA, t-SNE or [UMAP](https://umap-learn.readthedocs.io/en/latest/). We use UMAP here."
"이제 텍스트를 벡터화했습니다. 이 과정을 임베딩이라 부르지만 결과 벡터를 임베딩이라고도 합니다. 임베딩 벡터를 PCA, t-SNE, [UMAP](https://umap-learn.readthedocs.io/en/latest/) 등과 같은 차원 축소 기법을 사용해 2차원에 투영하여 시각화할 수 있습니다. 여기서는 UMAP을 사용합니다."
]
},
{
Expand Down Expand Up @@ -155,16 +154,16 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"This is a simplified representation of our data (the actual vectors are much larger than two dimensions), but can help discern trends, or with future labeling efforts. As you add features, it can be valuable to visualize embeddings to estimate whether classes look more separated."
"데이터를 간결하게 표혔했지만 트렌드를 보거나 향후 레이블링을 하는데 도움이 됩니다(실제 벡터는 2차원보다 훨씬 큽니다). 특성을 추가할 때 클래스 분할이 잘 되는지 확인하기 위해 임베딩을 시각화할 가치가 있습니다."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Pre-trained word embeddings\n",
"## 사전 훈련딘 단어 임베딩\n",
"\n",
"For this second approach, we load existing word vectors that were trained on a much larger corpus, which allows us to leverage general information from outside of our corpus. We will do so using the `spacy` library."
"두 번째 방법은 매우 큰 말뭉치에서 훈련된 기존 단어 벡터를 로드하여 현재 말뭉치를 넘어서 일반적인 정보를 활용하는 것입니다. `spacy` 라이브러리를 사용해 이를 수행해 보죠."
]
},
{
Expand All @@ -182,9 +181,9 @@
"metadata": {},
"outputs": [],
"source": [
"# Load a large model, and disable pipeline unnecessary parts for our task\n",
"# This speeds up the vectorization process significantly\n",
"# See https://spacy.io/models/en#en_core_web_lg for details about the model\n",
"# 라지 모델을 로드하고 이 작업에 불필요한 요소를 제외합니다.\n",
"# 이렇게 하면 벡터화 과정의 속도를 크게 높일 수 있습니다.\n",
"# 모델에 대한 자세한 내용은 https://spacy.io/models/en#en_core_web_lg 을 참고하세요.\n",
"nlp = spacy.load('en_core_web_lg', disable=[\"parser\", \"tagger\", \"ner\", \"textcat\", \"lemmatizer\"])"
]
},
Expand All @@ -194,9 +193,9 @@
"metadata": {},
"outputs": [],
"source": [
"# Get the vector for each of our questions\n",
"# By default, the vector returned is the average of all vectors in the sentence\n",
"# See https://spacy.io/usage/vectors-similarity for more\n",
"# 각 질문에 대한 벡터를 얻습니다.\n",
"# 기본적으로 반환된 벡터는 문장에 있는 모든 벡터의 평균입니다.\n",
"# 자세한 내용은 https://spacy.io/usage/vectors-similarity 을 참고하세요.\n",
"spacy_emb = train_author[train_author[\"is_question\"]][\"body_text\"].apply(lambda x: nlp(x).vector)\n",
"embeddings = np.vstack(spacy_emb)"
]
Expand All @@ -215,7 +214,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's visualize the pretrained embeddings using UMAP"
"UMAP을 사용해 사전 훈련된 임베딩을 시각화해 보죠."
]
},
{
Expand Down Expand Up @@ -249,11 +248,11 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"The topology of our dataset looks different because our embedding method is different. The underlying data however, is the same.\n",
"임베딩 방법이 다르기 때문에 이 데이터셋의 위상이 다릅니다. 하지만 내재된 데이터는 동일합니다.\n",
"\n",
"Different embedding methods will cause a dataset to be represented differently. When using embeddings trained only on your data, documents that use the same vocabulary will be embedded close to each other. Using models trained on other corpuses however allows you to leverage information from these corpuses. With these models, semantically similar sentences may be embedded close to each other even if their vocabulary is completely different.\n",
"임베딩 방법이 다르면 데이터셋을 다르게 표현하게 됩니다. 현재 데이터에서 훈련된 임베딩을 사용할 때 동일한 어휘를 사용한 문서가 가깝게 임베딩될 것입니다. 하지만 다른 말뭉치에서 훈련된 모델을 사용하면 이 말뭉치의 정보를 활용할 수 있습니다. 이런 모델을 사용하면 완전히 다른 어휘를 사용하도라도 의미적으로 비슷한 문장이 서로 가깝게 임베딩될 수 있습니다.\n",
"\n",
"Changing the way you vectorize your data can often have a significant impact on model performance."
"데이터 벡터화 방식을 바꾸면 모델 성능에 큰 영향을 끼치는 경우가 종종 있습니다."
]
}
],
Expand Down

0 comments on commit 5e627bb

Please sign in to comment.