You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ML-For-Beginners/translations/ja/4-Classification/1-Introduction/solution/R/lesson_10-R.ipynb

724 lines
30 KiB

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

{
"nbformat": 4,
"nbformat_minor": 2,
"metadata": {
"colab": {
"name": "lesson_10-R.ipynb",
"provenance": [],
"collapsed_sections": []
},
"kernelspec": {
"name": "ir",
"display_name": "R"
},
"language_info": {
"name": "R"
},
"coopTranslator": {
"original_hash": "2621e24705e8100893c9bf84e0fc8aef",
"translation_date": "2025-09-04T02:45:11+00:00",
"source_file": "4-Classification/1-Introduction/solution/R/lesson_10-R.ipynb",
"language_code": "ja"
}
},
"cells": [
{
"cell_type": "markdown",
"source": [
"# 分類モデルを構築する: 美味しいアジア料理とインド料理\n"
],
"metadata": {
"id": "ItETB4tSFprR"
}
},
{
"cell_type": "markdown",
"source": [
"## 分類の入門: データのクリーンアップ、準備、可視化\n",
"\n",
"この4つのレッスンでは、古典的な機械学習の基本的な焦点である*分類*を探求します。アジアとインドの素晴らしい料理に関するデータセットを使い、さまざまな分類アルゴリズムを実践していきます。お腹が空いてきましたか?\n",
"\n",
"<p>\n",
" <img src=\"../../images/pinch.png\"\n",
" width=\"600\"/>\n",
" <figcaption>これらのレッスンでパンアジア料理を祝おう!画像提供: Jen Looper</figcaption>\n",
"\n",
"<!--![これらのレッスンでパンアジア料理を祝おう!画像提供: Jen Looper](../../../../../../translated_images/pinch.b33c0ba76f284aad94a3c4e3ed83e13ed1e17fbcf4db8ca8583c3a0c135e2e99.ja.png)-->\n",
"\n",
"分類は[教師あり学習](https://wikipedia.org/wiki/Supervised_learning)の一形態で、回帰手法と多くの共通点を持っています。分類では、アイテムがどの`カテゴリ`に属するかを予測するモデルを訓練します。機械学習がデータセットを使って値や名前を予測することだとすれば、分類は一般的に次の2つのグループに分けられます: *二値分類*と*多クラス分類*。\n",
"\n",
"覚えておきましょう:\n",
"\n",
"- **線形回帰**は、変数間の関係を予測し、新しいデータポイントがその線に対してどこに位置するかを正確に予測するのに役立ちました。例えば、*9月と12月でカボチャの価格がいくらになるか*を予測することができました。\n",
"\n",
"- **ロジスティック回帰**は、「二値カテゴリ」を発見するのに役立ちました。この価格帯では、*このカボチャはオレンジ色か、それともオレンジ色ではないか*\n",
"\n",
"分類では、データポイントのラベルやクラスを決定するためにさまざまなアルゴリズムを使用します。この料理データを使って、材料のグループを観察することで、その料理の起源を特定できるかどうかを見てみましょう。\n",
"\n",
"### [**講義前のクイズ**](https://gray-sand-07a10f403.1.azurestaticapps.net/quiz/19/)\n",
"\n",
"### **イントロダクション**\n",
"\n",
"分類は、機械学習研究者やデータサイエンティストの基本的な活動の1つです。単純な二値値の分類「このメールはスパムかどうかから、コンピュータビジョンを使用した複雑な画像分類やセグメンテーションまで、データをクラスに分類し、それに質問を投げかける能力は常に有用です。\n",
"\n",
"科学的に言い換えると、分類手法は、入力変数と出力変数の関係をマッピングする予測モデルを作成します。\n",
"\n",
"<p>\n",
" <img src=\"../../images/binary-multiclass.png\"\n",
" width=\"600\"/>\n",
" <figcaption>分類アルゴリズムが扱う二値問題と多クラス問題。インフォグラフィック提供: Jen Looper</figcaption>\n",
"\n",
"データをクリーンアップし、可視化し、機械学習タスクの準備を始める前に、データを分類するために機械学習を活用するさまざまな方法について少し学びましょう。\n",
"\n",
"[統計学](https://wikipedia.org/wiki/Statistical_classification)に由来する古典的な機械学習を使用した分類では、`喫煙者`、`体重`、`年齢`などの特徴を使用して、*X病を発症する可能性*を判断します。以前に行った回帰演習と同様の教師あり学習手法として、データにはラベルが付けられており、MLアルゴリズムはそのラベルを使用してデータセットのクラスまたは「特徴」を分類し、グループや結果に割り当てます。\n",
"\n",
"✅ 料理に関するデータセットを想像してみてください。多クラスモデルではどのような質問に答えられるでしょうか?二値モデルではどのような質問に答えられるでしょうか?特定の料理がフェヌグリークを使用する可能性があるかどうかを判断したい場合はどうでしょう?また、スターアニス、アーティチョーク、カリフラワー、ホースラディッシュが入った食材袋を渡された場合、それで典型的なインド料理を作れるかどうかを知りたい場合は?\n",
"\n",
"### **「分類器」にこんにちは**\n",
"\n",
"この料理データセットに対して私たちが尋ねたい質問は、実際には**多クラスの質問**です。なぜなら、扱う可能性のある国の料理が複数あるからです。一連の材料が与えられた場合、それらのデータはどのクラスに適合するでしょうか?\n",
"\n",
"Tidymodelsは、解決したい問題の種類に応じて、データを分類するためのさまざまなアルゴリズムを提供します。次の2つのレッスンでは、これらのアルゴリズムのいくつかについて学びます。\n",
"\n",
"#### **前提条件**\n",
"\n",
"このレッスンでは、データをクリーンアップし、準備し、可視化するために以下のパッケージが必要です:\n",
"\n",
"- `tidyverse`: [tidyverse](https://www.tidyverse.org/)は、データサイエンスをより速く、簡単に、そして楽しくするために設計された[Rパッケージのコレクション](https://www.tidyverse.org/packages)です。\n",
"\n",
"- `tidymodels`: [tidymodels](https://www.tidymodels.org/)フレームワークは、モデリングと機械学習のための[パッケージのコレクション](https://www.tidymodels.org/packages/)です。\n",
"\n",
"- `DataExplorer`: [DataExplorerパッケージ](https://cran.r-project.org/web/packages/DataExplorer/vignettes/dataexplorer-intro.html)は、EDAプロセスとレポート生成を簡素化し自動化することを目的としています。\n",
"\n",
"- `themis`: [themisパッケージ](https://themis.tidymodels.org/)は、不均衡データを扱うための追加のレシピステップを提供します。\n",
"\n",
"以下のコマンドでこれらをインストールできます:\n",
"\n",
"`install.packages(c(\"tidyverse\", \"tidymodels\", \"DataExplorer\", \"here\"))`\n",
"\n",
"または、以下のスクリプトを使用して、このモジュールを完了するために必要なパッケージがインストールされているか確認し、欠けている場合はインストールします。\n"
],
"metadata": {
"id": "ri5bQxZ-Fz_0"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"suppressWarnings(if (!require(\"pacman\"))install.packages(\"pacman\"))\r\n",
"\r\n",
"pacman::p_load(tidyverse, tidymodels, DataExplorer, themis, here)"
],
"outputs": [],
"metadata": {
"id": "KIPxa4elGAPI"
}
},
{
"cell_type": "markdown",
"source": [
"後でこれらの素晴らしいパッケージを読み込み、現在のRセッションで利用可能にします。これは単なる説明のためであり、`pacman::p_load()`はすでにそれを行っています)\n"
],
"metadata": {
"id": "YkKAxOJvGD4C"
}
},
{
"cell_type": "markdown",
"source": [
"## 演習 - データをクリーンアップしてバランスを取る\n",
"\n",
"このプロジェクトを始める前に、最初のタスクとしてデータをクリーンアップし、**バランスを取る**ことで、より良い結果を得る準備をしましょう。\n",
"\n",
"それでは、データを確認してみましょう!🕵️\n"
],
"metadata": {
"id": "PFkQDlk0GN5O"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Import data\r\n",
"df <- read_csv(file = \"https://raw.githubusercontent.com/microsoft/ML-For-Beginners/main/4-Classification/data/cuisines.csv\")\r\n",
"\r\n",
"# View the first 5 rows\r\n",
"df %>% \r\n",
" slice_head(n = 5)\r\n"
],
"outputs": [],
"metadata": {
"id": "Qccw7okxGT0S"
}
},
{
"cell_type": "markdown",
"source": [
"面白いですね!見たところ、最初の列は一種の`id`列のようです。データについてもう少し情報を得ましょう。\n"
],
"metadata": {
"id": "XrWnlgSrGVmR"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Basic information about the data\r\n",
"df %>%\r\n",
" introduce()\r\n",
"\r\n",
"# Visualize basic information above\r\n",
"df %>% \r\n",
" plot_intro(ggtheme = theme_light())"
],
"outputs": [],
"metadata": {
"id": "4UcGmxRxGieA"
}
},
{
"cell_type": "markdown",
"source": [
"出力から、`2448`行と`385`列があり、欠損値が`0`であることがすぐにわかります。また、1つの離散的な列、*cuisine* が含まれています。\n",
"\n",
"## 演習 - 料理について学ぶ\n",
"\n",
"ここから作業がより興味深いものになっていきます。料理ごとのデータ分布を見ていきましょう。\n"
],
"metadata": {
"id": "AaPubl__GmH5"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Count observations per cuisine\r\n",
"df %>% \r\n",
" count(cuisine) %>% \r\n",
" arrange(n)\r\n",
"\r\n",
"# Plot the distribution\r\n",
"theme_set(theme_light())\r\n",
"df %>% \r\n",
" count(cuisine) %>% \r\n",
" ggplot(mapping = aes(x = n, y = reorder(cuisine, -n))) +\r\n",
" geom_col(fill = \"midnightblue\", alpha = 0.7) +\r\n",
" ylab(\"cuisine\")"
],
"outputs": [],
"metadata": {
"id": "FRsBVy5eGrrv"
}
},
{
"cell_type": "markdown",
"source": [
"料理の種類は有限ですが、データの分布は均一ではありません。それを修正することができます!その前に、もう少し探索してみましょう。\n",
"\n",
"次に、各料理を個別のtibbleに割り当て、それぞれの料理にどれだけのデータ行、列があるかを確認してみましょう。\n",
"\n",
"> [tibble](https://tibble.tidyverse.org/) は、現代的なデータフレームです。\n",
"\n",
"<p >\n",
" <img src=\"../../images/dplyr_filter.jpg\"\n",
" width=\"600\"/>\n",
" <figcaption>@allison_horstによるアートワーク</figcaption>\n"
],
"metadata": {
"id": "vVvyDb1kG2in"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Create individual tibble for the cuisines\r\n",
"thai_df <- df %>% \r\n",
" filter(cuisine == \"thai\")\r\n",
"japanese_df <- df %>% \r\n",
" filter(cuisine == \"japanese\")\r\n",
"chinese_df <- df %>% \r\n",
" filter(cuisine == \"chinese\")\r\n",
"indian_df <- df %>% \r\n",
" filter(cuisine == \"indian\")\r\n",
"korean_df <- df %>% \r\n",
" filter(cuisine == \"korean\")\r\n",
"\r\n",
"\r\n",
"# Find out how much data is available per cuisine\r\n",
"cat(\" thai df:\", dim(thai_df), \"\\n\",\r\n",
" \"japanese df:\", dim(japanese_df), \"\\n\",\r\n",
" \"chinese_df:\", dim(chinese_df), \"\\n\",\r\n",
" \"indian_df:\", dim(indian_df), \"\\n\",\r\n",
" \"korean_df:\", dim(korean_df))"
],
"outputs": [],
"metadata": {
"id": "0TvXUxD3G8Bk"
}
},
{
"cell_type": "markdown",
"source": [
"## **演習 - dplyrを使って料理ごとの主要な食材を発見する**\n",
"\n",
"ここではデータをさらに深掘りして、料理ごとに典型的な食材が何かを学びます。料理間で混乱を引き起こすような繰り返しのデータを取り除く必要があるので、この問題について学んでいきましょう。\n",
"\n",
"Rで`create_ingredient()`という関数を作成し、食材のデータフレームを返すようにします。この関数では、まず役に立たない列を削除し、食材をその出現回数で並べ替えます。\n",
"\n",
"Rにおける関数の基本構造は以下の通りです\n",
"\n",
"`myFunction <- function(arglist){`\n",
"\n",
"**`...`**\n",
"\n",
"**`return`**`(value)`\n",
"\n",
"`}`\n",
"\n",
"R関数の簡潔な入門は[こちら](https://skirmer.github.io/presentations/functions_with_r.html#1)で確認できます。\n",
"\n",
"それでは早速始めましょう!これまでのレッスンで学んだ[dplyrの動詞](https://dplyr.tidyverse.org/)を活用します。復習として:\n",
"\n",
"- `dplyr::select()`: **列**を選択して保持または除外するのに役立ちます。\n",
"\n",
"- `dplyr::pivot_longer()`: データを「縦長」に変換し、行数を増やして列数を減らすのに役立ちます。\n",
"\n",
"- `dplyr::group_by()`と`dplyr::summarise()`: 異なるグループの要約統計を見つけ、それをきれいなテーブルにまとめるのに役立ちます。\n",
"\n",
"- `dplyr::filter()`: 条件を満たす行のみを含むデータのサブセットを作成します。\n",
"\n",
"- `dplyr::mutate()`: 列を作成または変更するのに役立ちます。\n",
"\n",
"Allison Horstによる[*アート*満載のlearnrチュートリアル](https://allisonhorst.shinyapps.io/dplyr-learnr/#section-welcome)では、dplyrTidyverseの一部の便利なデータ整形関数が紹介されていますので、ぜひチェックしてみてください。\n"
],
"metadata": {
"id": "K3RF5bSCHC76"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Creates a functions that returns the top ingredients by class\r\n",
"\r\n",
"create_ingredient <- function(df){\r\n",
" \r\n",
" # Drop the id column which is the first colum\r\n",
" ingredient_df = df %>% select(-1) %>% \r\n",
" # Transpose data to a long format\r\n",
" pivot_longer(!cuisine, names_to = \"ingredients\", values_to = \"count\") %>% \r\n",
" # Find the top most ingredients for a particular cuisine\r\n",
" group_by(ingredients) %>% \r\n",
" summarise(n_instances = sum(count)) %>% \r\n",
" filter(n_instances != 0) %>% \r\n",
" # Arrange by descending order\r\n",
" arrange(desc(n_instances)) %>% \r\n",
" mutate(ingredients = factor(ingredients) %>% fct_inorder())\r\n",
" \r\n",
" \r\n",
" return(ingredient_df)\r\n",
"} # End of function"
],
"outputs": [],
"metadata": {
"id": "uB_0JR82HTPa"
}
},
{
"cell_type": "markdown",
"source": [
"では、この関数を使って、料理ごとの人気のある材料トップ10を確認してみましょう。`thai_df`で試してみましょう。\n"
],
"metadata": {
"id": "h9794WF8HWmc"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Call create_ingredient and display popular ingredients\r\n",
"thai_ingredient_df <- create_ingredient(df = thai_df)\r\n",
"\r\n",
"thai_ingredient_df %>% \r\n",
" slice_head(n = 10)"
],
"outputs": [],
"metadata": {
"id": "agQ-1HrcHaEA"
}
},
{
"cell_type": "markdown",
"source": [
"前のセクションでは、`geom_col()`を使用しましたが、`geom_bar`を使って棒グラフを作成する方法も見てみましょう。詳しくは`?geom_bar`を参照してください。\n"
],
"metadata": {
"id": "kHu9ffGjHdcX"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Make a bar chart for popular thai cuisines\r\n",
"thai_ingredient_df %>% \r\n",
" slice_head(n = 10) %>% \r\n",
" ggplot(aes(x = n_instances, y = ingredients)) +\r\n",
" geom_bar(stat = \"identity\", width = 0.5, fill = \"steelblue\") +\r\n",
" xlab(\"\") + ylab(\"\")"
],
"outputs": [],
"metadata": {
"id": "fb3Bx_3DHj6e"
}
},
{
"cell_type": "markdown",
"source": [
"日本語のデータでも同じことをしましょう\n"
],
"metadata": {
"id": "RHP_xgdkHnvM"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Get popular ingredients for Japanese cuisines and make bar chart\r\n",
"create_ingredient(df = japanese_df) %>% \r\n",
" slice_head(n = 10) %>%\r\n",
" ggplot(aes(x = n_instances, y = ingredients)) +\r\n",
" geom_bar(stat = \"identity\", width = 0.5, fill = \"darkorange\", alpha = 0.8) +\r\n",
" xlab(\"\") + ylab(\"\")\r\n"
],
"outputs": [],
"metadata": {
"id": "019v8F0XHrRU"
}
},
{
"cell_type": "markdown",
"source": [
"中国料理はどうですか?\n"
],
"metadata": {
"id": "iIGM7vO8Hu3v"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Get popular ingredients for Chinese cuisines and make bar chart\r\n",
"create_ingredient(df = chinese_df) %>% \r\n",
" slice_head(n = 10) %>%\r\n",
" ggplot(aes(x = n_instances, y = ingredients)) +\r\n",
" geom_bar(stat = \"identity\", width = 0.5, fill = \"cyan4\", alpha = 0.8) +\r\n",
" xlab(\"\") + ylab(\"\")"
],
"outputs": [],
"metadata": {
"id": "lHd9_gd2HyzU"
}
},
{
"cell_type": "markdown",
"source": [],
"metadata": {
"id": "ir8qyQbNH1c7"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Get popular ingredients for Indian cuisines and make bar chart\r\n",
"create_ingredient(df = indian_df) %>% \r\n",
" slice_head(n = 10) %>%\r\n",
" ggplot(aes(x = n_instances, y = ingredients)) +\r\n",
" geom_bar(stat = \"identity\", width = 0.5, fill = \"#041E42FF\", alpha = 0.8) +\r\n",
" xlab(\"\") + ylab(\"\")"
],
"outputs": [],
"metadata": {
"id": "ApukQtKjH5FO"
}
},
{
"cell_type": "markdown",
"source": [
"最後に、韓国の材料をプロットします。\n"
],
"metadata": {
"id": "qv30cwY1H-FM"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Get popular ingredients for Korean cuisines and make bar chart\r\n",
"create_ingredient(df = korean_df) %>% \r\n",
" slice_head(n = 10) %>%\r\n",
" ggplot(aes(x = n_instances, y = ingredients)) +\r\n",
" geom_bar(stat = \"identity\", width = 0.5, fill = \"#852419FF\", alpha = 0.8) +\r\n",
" xlab(\"\") + ylab(\"\")"
],
"outputs": [],
"metadata": {
"id": "lumgk9cHIBie"
}
},
{
"cell_type": "markdown",
"source": [
"データビジュアライゼーションから、異なる料理の区別を曖昧にする最も一般的な食材を、`dplyr::select()`を使って除外することができます。\n",
"\n",
"みんなが大好きな米、ニンニク、そしてショウガ!\n"
],
"metadata": {
"id": "iO4veMXuIEta"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Drop id column, rice, garlic and ginger from our original data set\r\n",
"df_select <- df %>% \r\n",
" select(-c(1, rice, garlic, ginger))\r\n",
"\r\n",
"# Display new data set\r\n",
"df_select %>% \r\n",
" slice_head(n = 5)"
],
"outputs": [],
"metadata": {
"id": "iHJPiG6rIUcK"
}
},
{
"cell_type": "markdown",
"source": [
"## レシピを使ったデータの前処理 👩‍🍳👨‍🍳 - 不均衡データの対処 ⚖️\n",
"\n",
"<p >\n",
" <img src=\"../../images/recipes.png\"\n",
" width=\"600\"/>\n",
" <figcaption>@allison_horstによるイラスト</figcaption>\n",
"\n",
"このレッスンが料理に関するものであることを考えると、`recipes`を文脈に合わせて考える必要があります。\n",
"\n",
"Tidymodelsはもう一つ便利なパッケージを提供しています。それがデータ前処理用のパッケージ、`recipes`です。\n"
],
"metadata": {
"id": "kkFd-JxdIaL6"
}
},
{
"cell_type": "markdown",
"source": [
"もう一度、私たちの料理の分布を見てみましょう。\n"
],
"metadata": {
"id": "6l2ubtTPJAhY"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Distribution of cuisines\r\n",
"old_label_count <- df_select %>% \r\n",
" count(cuisine) %>% \r\n",
" arrange(desc(n))\r\n",
"\r\n",
"old_label_count"
],
"outputs": [],
"metadata": {
"id": "1e-E9cb7JDVi"
}
},
{
"cell_type": "markdown",
"source": [
"ご覧の通り、料理の種類の数にはかなりの偏りがあります。韓国料理はタイ料理の約3倍です。データの不均衡は、モデルの性能に悪影響を及ぼすことがよくあります。例えば、二値分類を考えてみてください。データの大半が一つのクラスに偏っている場合、機械学習モデルはそのクラスを頻繁に予測する傾向があります。これは、そのクラスのデータが多いからです。データを均衡化することで、この偏りを取り除くことができます。多くのモデルは観測数が均等であるときに最も良い性能を発揮し、不均衡なデータでは苦戦する傾向があります。\n",
"\n",
"不均衡なデータセットに対処する方法は主に2つあります\n",
"\n",
"- 少数派クラスの観測値を追加する: `オーバーサンプリング` 例: SMOTEアルゴリズムを使用する\n",
"\n",
"- 多数派クラスの観測値を削除する: `アンダーサンプリング`\n",
"\n",
"では、`recipe`を使って不均衡なデータセットに対処する方法を示してみましょう。レシピは、データ分析の準備をするためにデータセットに適用すべき手順を記述した設計図のようなものと考えることができます。\n"
],
"metadata": {
"id": "soAw6826JKx9"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Load themis package for dealing with imbalanced data\r\n",
"library(themis)\r\n",
"\r\n",
"# Create a recipe for preprocessing data\r\n",
"cuisines_recipe <- recipe(cuisine ~ ., data = df_select) %>% \r\n",
" step_smote(cuisine)\r\n",
"\r\n",
"cuisines_recipe"
],
"outputs": [],
"metadata": {
"id": "HS41brUIJVJy"
}
},
{
"cell_type": "markdown",
"source": [
"前処理のステップを分解して説明します。\n",
"\n",
"- `recipe()`をフォーミュラと共に呼び出すことで、`df_select`データを参照として変数の*役割*をレシピに伝えます。例えば、`cuisine`列は`outcome`の役割を割り当てられ、他の列は`predictor`の役割を割り当てられています。\n",
"\n",
"- [`step_smote(cuisine)`](https://themis.tidymodels.org/reference/step_smote.html)は、少数派クラスの新しい例をこれらのケースの最近傍を使用して合成的に生成するレシピステップの*仕様*を作成します。\n",
"\n",
"さて、前処理されたデータを確認したい場合は、[**`prep()`**](https://recipes.tidymodels.org/reference/prep.html)と[**`bake()`**](https://recipes.tidymodels.org/reference/bake.html)を使用する必要があります。\n",
"\n",
"`prep()`: トレーニングセットから必要なパラメータを推定し、それを他のデータセットに適用できるようにします。\n",
"\n",
"`bake()`: 前処理済みのレシピを取り、それを任意のデータセットに適用します。\n"
],
"metadata": {
"id": "Yb-7t7XcJaC8"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Prep and bake the recipe\r\n",
"preprocessed_df <- cuisines_recipe %>% \r\n",
" prep() %>% \r\n",
" bake(new_data = NULL) %>% \r\n",
" relocate(cuisine)\r\n",
"\r\n",
"# Display data\r\n",
"preprocessed_df %>% \r\n",
" slice_head(n = 5)\r\n",
"\r\n",
"# Quick summary stats\r\n",
"preprocessed_df %>% \r\n",
" introduce()"
],
"outputs": [],
"metadata": {
"id": "9QhSgdpxJl44"
}
},
{
"cell_type": "markdown",
"source": [
"料理の分布を確認し、不均衡なデータと比較してみましょう。\n"
],
"metadata": {
"id": "dmidELh_LdV7"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Distribution of cuisines\r\n",
"new_label_count <- preprocessed_df %>% \r\n",
" count(cuisine) %>% \r\n",
" arrange(desc(n))\r\n",
"\r\n",
"list(new_label_count = new_label_count,\r\n",
" old_label_count = old_label_count)"
],
"outputs": [],
"metadata": {
"id": "aSh23klBLwDz"
}
},
{
"cell_type": "markdown",
"source": [
"おいしい!データはきれいでバランスが取れていて、とても美味しそうです😋!\n",
"\n",
"> 通常、レシピはモデリングの前処理として使用され、データセットをモデリングに適した状態にするために適用すべき手順を定義します。この場合、手動でレシピを評価する代わりに、通常は `workflow()` が使用されます(これまでのレッスンで既に見てきた通りです)。\n",
">\n",
"> そのため、tidymodels を使用する際には、通常 **`prep()`** や **`bake()`** を使う必要はありませんが、レシピが期待通りに動作しているか確認するために便利な関数です。今回のケースでも同様です。\n",
">\n",
"> **`new_data = NULL`** を指定して準備済みのレシピを **`bake()`** すると、レシピを定義した際に提供したデータが、前処理ステップを経た状態で戻ってきます。\n",
"\n",
"それでは、このデータを次回以降のレッスンで使用するためにコピーを保存しましょう:\n"
],
"metadata": {
"id": "HEu80HZ8L7ae"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Save preprocessed data\r\n",
"write_csv(preprocessed_df, \"../../../data/cleaned_cuisines_R.csv\")"
],
"outputs": [],
"metadata": {
"id": "cBmCbIgrMOI6"
}
},
{
"cell_type": "markdown",
"source": [
"この新しいCSVは、ルートデータフォルダーにあります。\n",
"\n",
"**🚀チャレンジ**\n",
"\n",
"このカリキュラムにはいくつかの興味深いデータセットが含まれています。`data`フォルダーを掘り下げて、バイナリまたは多クラス分類に適したデータセットが含まれているか確認してみましょう。このデータセットに対してどのような質問をしますか?\n",
"\n",
"## [**講義後のクイズ**](https://gray-sand-07a10f403.1.azurestaticapps.net/quiz/20/)\n",
"\n",
"## **復習と自己学習**\n",
"\n",
"- [themisパッケージ](https://github.com/tidymodels/themis)をチェックしてみましょう。不均衡なデータに対処するために他にどのような手法が使えるでしょうか?\n",
"\n",
"- Tidy modelsの[参考ウェブサイト](https://www.tidymodels.org/start/)。\n",
"\n",
"- H. WickhamとG. Grolemundによる[*R for Data Science: Visualize, Model, Transform, Tidy, and Import Data*](https://r4ds.had.co.nz/)。\n",
"\n",
"#### 感謝:\n",
"\n",
"[`Allison Horst`](https://twitter.com/allison_horst/)に感謝します。彼女はRをより親しみやすく魅力的にする素晴らしいイラストを作成してくれました。彼女の[ギャラリー](https://www.google.com/url?q=https://github.com/allisonhorst/stats-illustrations&sa=D&source=editors&ust=1626380772530000&usg=AOvVaw3zcfyCizFQZpkSLzxiiQEM)でさらに多くのイラストを見ることができます。\n",
"\n",
"[Cassie Breviu](https://www.twitter.com/cassieview)と[Jen Looper](https://www.twitter.com/jenlooper)に感謝します。彼女たちはこのモジュールの元となるPython版を作成してくれました♥\n",
"\n",
"<p >\n",
" <img src=\"../../images/r_learners_sm.jpeg\"\n",
" width=\"600\"/>\n",
" <figcaption>@allison_horstによるアートワーク</figcaption>\n"
],
"metadata": {
"id": "WQs5621pMGwf"
}
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n---\n\n**免責事項**: \nこの文書は、AI翻訳サービス [Co-op Translator](https://github.com/Azure/co-op-translator) を使用して翻訳されています。正確性を期すよう努めておりますが、自動翻訳には誤りや不正確な部分が含まれる可能性があります。元の言語で記載された原文が正式な情報源とみなされるべきです。重要な情報については、専門の人間による翻訳を推奨します。本翻訳の利用に起因する誤解や誤認について、当方は一切の責任を負いません。\n"
]
}
]
}