Skip to content

Commit

Permalink
노트북 번역
Browse files Browse the repository at this point in the history
  • Loading branch information
rickiepark committed Jul 15, 2021
1 parent 7c9980a commit d855b59
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 69 deletions.
30 changes: 15 additions & 15 deletions notebooks/black_box_explainer.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"# Explaining predictions\n",
"# 예측 설명하기\n",
"\n",
"Feature importance methods allow us to identify features which have proven useful in aggregate. We can also try to identify features that were important for a **specific example**. This is particularly useful in our case, since we'd like to use a model to make recommendations for a specific given input. Additionally, this method does not require the use of a model that exposes feature importance, and can thus work on black-box models. Here, we'll use a black box explainer called [LIME](https://github.com/marcotcr/lime).\n",
"특성 중요도 도구를 사용하면 전체적으로 유용하다고 판명된 특성을 구별할 수 있습니다. 또한 **특정 샘플**에 중요한 특성을 식별할 수도 있습니다. 머신러닝 에디터의 경우 모델을 사용해 주어진 특정 입력에 대한 추천을 만들기 때문에 이런 성질은 특히 유용합니다. 그외에도 이 방법은 특성 중요도를 제공하는 모델을 사용할 필요가 없습니다. 따라서 블랙 박스(black box) 모델에 사용할 수 있습니다. 여기서는 [LIME](https://github.com/marcotcr/lime)이라는 블랙 박스 설명 도구를 사용하겠습니다.\n",
"\n",
"We first load the data."
"먼저 데이터를 로드합니다."
]
},
{
Expand Down Expand Up @@ -49,7 +49,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Then, we add features and split the data."
"그다음 특성을 추가하고 데이터를 분할합니다."
]
},
{
Expand All @@ -66,7 +66,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"We load the pretrained model and vectorizer."
"사전 훈련된 모델과 벡터화 객체를 로드합니다."
]
},
{
Expand All @@ -85,7 +85,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"We vectorize the text and get features ready for our model"
"텍스트를 벡터화하고 모델을 위해 특성을 준비합니다."
]
},
{
Expand All @@ -111,7 +111,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, we use LIME to make functions that will explain a model's predictions for a **specific example**."
"이제 LIME을 사용해 **특정 샘플**에 대한 모델의 예측을 설명할 함수를 만듭니다."
]
},
{
Expand All @@ -136,7 +136,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Here, we are particularly interested in finding which type of content in the question our classifier relies on. We can do so by visualizing explanations for specific examples, as shown for two questions below."
"여기에서는 특히 분류기가 질문에 있는 어떤 종류의 컨텐츠에 의존하는지를 찾는 것에 관심이 있습니다. 아래의 예시처럼 특정 샘플에 대한 설명을 시각화하여 이를 확인할 수 있습니다."
]
},
{
Expand Down Expand Up @@ -74464,9 +74464,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"It would be valuable to get a sense for which words influence our model in many examples. To do so, we can sample multiple examples from the dataset, and average importances.\n",
"많은 샘플에서 어떤 단어가 모델에 영향을 미쳤는지 아는 것은 가치가 있습니다. 이를 위해 데이터셋에서 여러 샘플을 랜덤하게 추출하여 중요도를 평균합니다.\n",
"\n",
"Sampling more examples allows for a better estimate of the global word importance, but also takes longer. Below, I used 500 examples, which takes quite some time. Feel free to tweak this number."
"많은 샘플을 추출하면 단어 중요도를 더 잘 추정할 수 있지만 시간이 오래 걸립니다. 아래 코드에서 500개의 샘플을 사용했을 때 꽤 시간이 걸렸습니다. 이 숫자를 자유롭게 바꿔서 확인해 보세요."
]
},
{
Expand All @@ -74482,7 +74482,7 @@
" labels_to_sentences = defaultdict(list)\n",
" contributors = defaultdict(dict)\n",
" \n",
" # First, find contributing words to each class\n",
" # 먼저, 클래스별 단어의 가중치를 찾습니다\n",
" for sentence in sample_sentences:\n",
" probabilities = model_pipeline([sentence])\n",
" curr_label = probabilities[0].argmax()\n",
Expand All @@ -74496,7 +74496,7 @@
" else:\n",
" contributors[curr_label][word] = [contributing_weight] \n",
" \n",
" # average each word's contribution to a class, and sort them by impact\n",
" # 단어 가중치를 평균하고 크기에 따라 정렬합니다\n",
" average_contributions = {}\n",
" sorted_contributions = {}\n",
" for label,lexica in contributors.items():\n",
Expand Down Expand Up @@ -74524,7 +74524,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Now that we've run the explainer, I'll plot the most important words in aggregate and see if they seem like good words for the model to focus on."
"이제 설명 도구를 실행합니다. 전체적으로 가장 중요한 단어를 출력하고 모델에게 좋은 단어인지 알아 보겠습니다."
]
},
{
Expand Down Expand Up @@ -74599,9 +74599,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"These do not seem like features that would be relevant to a good question being asked. Words predictive of high score questions are simply the most common English words. Words predictive of a low score question seem to be about the type of writing (essay, Trilogies) and may be indicative of stackoverflow posting guidelines.\n",
"좋은 질문과 관련된 특성처럼 보이지 않습니다. 높은 점수의 질문을 예측하기 위해 사용한 단어는 그냥 흔히 사용하는 영어 단어입니다. 낮은 점수의 질문을 예측하기 위해 사용한 단어는 글의 형식에 관한 것 같습니다(markup, magazine). 아마도 스택익스체인지의 포스팅 가이드라인을 나타내는 것 같습니다.\n",
"\n",
"Regardless, this result may be a sign that our model is overfitting, or that our text vectorization process is not surfacing the most useful information."
"이 결과는 모델이 과대적합되었다는 신호입니다. 또는 텍스트 벡터화 처리 과정에서 가장 유용한 정보를 찾지 못했다는 뜻입니다."
]
}
],
Expand Down
61 changes: 28 additions & 33 deletions notebooks/clustering_data.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,18 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## Let's cluster our data\n",
"## 데이터 군집\n",
"\n",
"In this notebook, I'll give a brief overview of clustering methods, and show how to inspect clustering performance using umap. This notebook is mostly an application of scikit-learn's clustering tutorial [here].(https://scikit-learn.org/stable/auto_examples/cluster/plot_kmeans_silhouette_analysis.html#sphx-glr-auto-examples-cluster-plot-kmeans-silhouette-analysis-py)\n",
"이 노트북에서 군집(clustering)을 간단히 소개하고 umap을 사용해 군집의 성능을 조사하는 방법을 알아 보겠습니다. 이 노트북은 사이킷런의 군집 [튜토리얼](https://scikit-learn.org/stable/auto_examples/cluster/plot_kmeans_silhouette_analysis.html#sphx-glr-auto-examples-cluster-plot-kmeans-silhouette-analysis-py)을 참고했습니다.\n",
"\n",
"I will start by showing a manual approach, and then an automated sweep through cluster sizes along with an examination of silhouette scores."
"먼저 수동 방법을 알아 보고 그다음 실루엣 점수와 클러스터 크기를 사용해 자동 방법을 알아 보겠습니다."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"First, we load and format our data, and embed it."
"먼저 데이터를 로드하고 변환한 다음 임베딩합니다."
]
},
{
Expand Down Expand Up @@ -78,7 +78,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's cluster the data using [K means](https://en.wikipedia.org/wiki/K-means_clustering). K means requires us to input the desired number of clusters as a parameter. Let's start with three clusters, and visualize our results using UMAP by assigning each cluster a different color."
"[K 평균](https://en.wikipedia.org/wiki/K-means_clustering)을 사용해 데이터를 클러스터링해 보죠. K 평균을 사용하려면 원하는 클러스터 개수를 매개변수로 지정해야 합니다. 3개의 클러스터로 시작해 보겠습니다. 클러스터마다 다른 색깔을 입혀 UMAP으로 결과를 시각화합니다."
]
},
{
Expand All @@ -100,17 +100,17 @@
}
],
"source": [
"# Choose number of clusters and colormap\n",
"# 클러스터 개수와 컬러맵을 선택합니다\n",
"n_clusters=3\n",
"cmap = plt.get_cmap(\"Set2\")\n",
"fig = plt.figure(figsize=(16, 10))\n",
"\n",
"\n",
"# Fit clustering algorithm to our vectorized features\n",
"# 벡터화된 특성에 군집 알고리즘을 훈련합니다\n",
"clus = KMeans(n_clusters=n_clusters, random_state=10)\n",
"clusters = clus.fit_predict(vectorized_features)\n",
"\n",
"# Plot the dimentionality reduced features on a 2D plane\n",
"# 차원 축소된 특성을 2D 평면에 출력합니다\n",
"plt.scatter(umap_features[:, 0], umap_features[:, 1], \n",
" c=[cmap(x/n_clusters) for x in clusters], s=40, alpha=.4)\n",
"plt.title('UMAP projection of questions, colored by clusters', fontsize=14);\n",
Expand Down Expand Up @@ -175,7 +175,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Looking at this plot, it is unclear whether we have picked the right number of clusters. Certain region seem to be associated to a unique clusters, while others are split. Let's try out different values for the numbers of clusters, and plot the umap projection, as well as the [silhouette score and samples](https://en.wikipedia.org/wiki/Silhouette_(clustering)) for each."
"이 그래프에서는 올바른 클러스터 개수를 선택했는지 확실하지 않습니다. 어떤 영역은 특정 클러스터에 할당된 것 같지만 그렇지 않고 분할된 영역도 있습니다. 클러스터 개수를 바꾸어 시도해 보고 umap과 [실루엣 점수](https://en.wikipedia.org/wiki/Silhouette_(clustering))를 사용해 그래프를 그려 보겠습니다."
]
},
{
Expand Down Expand Up @@ -269,37 +269,32 @@
"to_clus = vectorized_features\n",
"\n",
"for n_clusters in range_n_clusters:\n",
" # Create a subplot with 1 row and 2 columns\n",
" # 1행 2열의 서브플롯을 만듭니다\n",
" fig, (ax1, ax2) = plt.subplots(1, 2)\n",
" fig.set_size_inches(18, 7)\n",
"\n",
" # The 1st subplot is the silhouette plot\n",
" # The silhouette coefficient can range from -1, 1 but in this example all\n",
" # lie within [-0.1, 1]\n",
" # 첫 번째 서브플롯은 실루엣 그래프입니다\n",
" # 실루엣 계수는 -1~1 사이이지만 이 예에서는 모두 [-0.1, 1] 사이에 있습니다\n",
" ax1.set_xlim([-.3, .4])\n",
" # The (n_clusters+1)*10 is for inserting blank space between silhouette\n",
" # plots of individual clusters, to demarcate them clearly.\n",
" # (n_clusters+1)*10는 클러스터 실루엣 그래프 사이의 공백을 위한 것입니다\n",
" ax1.set_ylim([0, len(to_clus) + (n_clusters + 1) * 10])\n",
"\n",
" # Initialize the clusterer with n_clusters value and a random generator\n",
" # seed of 10 for reproducibility.\n",
" # n_cluster와 재현을 위한 random_state를 지정하여 K 평균 객체를 초기화합니다\n",
" clusterer = KMeans(n_clusters=n_clusters, random_state=10)\n",
" cluster_labels = clusterer.fit_predict(to_clus)\n",
"\n",
" # The silhouette_score gives the average value for all the samples.\n",
" # This gives a perspective into the density and separation of the formed\n",
" # clusters\n",
" # silhouette_score 함수는 모든 샘플에 대한 평균을 반환합니다\n",
" # 이를 통해 만들어진 클러스터의 조밀함과 차별성을 판단합니다\n",
" silhouette_avg = silhouette_score(to_clus, cluster_labels, metric='cosine')\n",
" print(\"For n_clusters =\", n_clusters,\n",
" \"The average silhouette_score is :\", silhouette_avg)\n",
"\n",
" # Compute the silhouette scores for each sample\n",
" # 각 샘플에 대한 실루엣 점수를 계산합니다\n",
" sample_silhouette_values = silhouette_samples(to_clus, cluster_labels, metric='cosine')\n",
"\n",
" y_lower = 10\n",
" for i in range(n_clusters):\n",
" # Aggregate the silhouette scores for samples belonging to\n",
" # cluster i, and sort them\n",
" # 클러스터 i에 속한 샘플의 실루엣 점수를 찾아 정렬합니다\n",
" ith_cluster_silhouette_values = \\\n",
" sample_silhouette_values[cluster_labels == i]\n",
"\n",
Expand All @@ -313,32 +308,32 @@
" 0, ith_cluster_silhouette_values,\n",
" facecolor=color, edgecolor=color, alpha=0.7)\n",
"\n",
" # Label the silhouette plots with their cluster numbers at the middle\n",
" # 실루엣 그래프에 클러스터 번호로 레이블을 매깁니다\n",
" ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))\n",
"\n",
" # Compute the new y_lower for next plot\n",
" y_lower = y_upper + 10 # 10 for the 0 samples\n",
" # 다음 그래프를 위해 새로운 y_lower를 계산합니다\n",
" y_lower = y_upper + 10 # 샘플일 0개일 경우를 위해 10을 더함\n",
"\n",
" ax1.set_title(\"The silhouette plot for the various clusters.\")\n",
" ax1.set_xlabel(\"The silhouette coefficient values\")\n",
" ax1.set_ylabel(\"Cluster label\")\n",
"\n",
" # The vertical line for average silhouette score of all the values\n",
" # 평균 실루엣 점수로 수직선을 그립니다\n",
" ax1.axvline(x=silhouette_avg, color=\"red\", linestyle=\"--\")\n",
"\n",
" ax1.set_yticks([]) # Clear the yaxis labels / ticks\n",
" ax1.set_yticks([]) # y축 레이블을 삭제합니다\n",
" ax1.set_xticks([-0.3, -0.2, -0.1, 0, 0.2, 0.4, 0.6, 0.8, 1])\n",
"\n",
" # 2nd Plot showing the actual clusters formed\n",
" # 2차원 평면에 실제 클러스터를 그립니다\n",
" colors = cmap(cluster_labels.astype(float) / n_clusters)\n",
" ax2.scatter(umap_features[:, 0], umap_features[:, 1], marker='.', s=30, lw=0, alpha=0.7,\n",
" c=colors, edgecolor='k')\n",
"\n",
" # Labeling the clusters\n",
" # 클러스터에 레이블을 부여합니다\n",
" centerss = clusterer.cluster_centers_\n",
" print(centerss.shape)\n",
" centers = umap_embedder.transform(centerss)\n",
" # Draw white circles at cluster centers\n",
" # 클러스터 중심에 하얀 원을 그립니다\n",
" ax2.scatter(centers[:, 0], centers[:, 1], marker='o',\n",
" c=\"white\", alpha=1, s=200, edgecolor='k')\n",
"\n",
Expand All @@ -359,9 +354,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"The aggregate silhouette score is often too high level of a metric to judge clustering quality. To show a more nuanced view, silhouette plots display each individual data point's silhouette score broken down by cluster.\n",
"하나의 실루엣 점수는 군집 품질을 평가하기에는 너무 고수준의 지표입니다. 조금 더 세밀한 정보를 얻기 위해서 개별 데이터 포인트의 실루엣 점수를 클러스터별로 그릴 수 있습니다.\n",
"\n",
"In a perfect situation, most points within a cluster would have a silhouette score that is close to 1. In our example, while no number of clusters seems optimal, three and four clusters produce silhouette plots with the largest proportion of points receiving a positive score. For readers that want to explore clustering further, I recommend experimenting with other approaches such as DBSCAN or MeanShift (see [sklearn](https://scikit-learn.org/stable/modules/clustering.html) for examples)."
"완벽한 상황에서 클러스터 안의 대부분 포인트는 1에 가까운 실루엣 점수를 가질 것입니다. 이 예제에서는 최적의 클러스터는 없는 것 같습니다. 하지만 세 개와 네 개의 클러스터는 대부분의 포인트가 양수 점수를 가진 실루엣 그래프를 그립니다. 군집에 대해 더 자세히 알고 싶다면 DBSCAN이나 MeanShift 같은 다른 알고리즘을 살펴 보세요(사이킷런의 [군집 알고리즘](https://scikit-learn.org/stable/modules/clustering.html))."
]
}
],
Expand Down
Loading

0 comments on commit d855b59

Please sign in to comment.