公開日:2019-08-15
最終更新日:2019-08-26
最終更新日:2019-08-26
skl02-0:準備
Daveはこれまでにラーメンを90食試してきた.次のデータramen.csvはDaveのラーメンに対する評価履歴データである.以下のデータをdataディレクトリに配置したうえで,次のコードを実行しよう.
ramen.csv:ラーメンに対する評価履歴データ(データIDid,こってり度richness {0-100},評価値rating {0-100})
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
>>> import numpy as np >>> import pandas as pd >>> >>> # データの読込み >>> ramen = pd.read_csv('data/ramen.csv', index_col=0) >>> >>> feature_names = np.array(ramen.columns[:-1]) >>> >>> ramen_X = np.array(ramen[feature_names]) >>> ramen_y = np.array(ramen['rating']) >>> >>> # 全データをランダムに学習データ80%とテストデータ20%に分割 >>> n = len(ramen_X) >>> m = int(n * 0.2) >>> np.random.seed(0) >>> indices = np.random.permutation(n) >>> ramen_X_train = ramen_X[indices[:-m]] >>> ramen_y_train = ramen_y[indices[:-m]] >>> ramen_X_test = ramen_X[indices[-m:]] >>> ramen_y_test = ramen_y[indices[-m:]] |
skl02-1:
LinearRegressionのインポートLinearRegressionをインポートしよう.
難易度:★
| ミッション | 説明 |
|---|---|
| 1 | LinearRegressionをインポートする. |
skl02-2:
LinearRegressionオブジェクトの生成LinearRegressionオブジェクトを生成しよう.
難易度:★
| ミッション | 説明 |
|---|---|
| 1 | LinearRegression()コンストラクタを呼び出す. |
| 2 | 生成したLinearRegressionオブジェクトをregrとする. |
skl02-3:学習
学習データを基にregrにより学習しよう.
難易度:★★
| ミッション | 説明 |
|---|---|
| 1 | LinearRegression.fit()メソッドを使う. |
skl02-4:回帰係数の取得
回帰係数を取得しよう.
難易度:★★
| ミッション | 説明 |
|---|---|
| 1 | LinearRegression.coef_属性を使う. |
skl02-5:予測
regrによりテストデータに対してラベルを予測しよう.
難易度:★★
| ミッション | 説明 |
|---|---|
| 1 | LinearRegression.predict()メソッドを使う. |
skl02-6:平均二乗誤差の取得
regrのテストデータに対する平均二乗誤差を取得しよう.
難易度:★
| ミッション | 説明 |
|---|---|
| 1 | LinearRegression.predict()メソッドを使う. |
| 2 | numpy.mean()関数を使う. |
skl02-7:予測精度の取得
regrのテストデータに対する予測精度を取得しよう.
難易度:★
| ミッション | 説明 |
|---|---|
| 1 | LinearRegression.score()メソッドを使う. |
skl02-8:学習モデルの可視化
次のコードはregrによる学習モデルを可視化するものである.次のコードをskl02_plt.pyというファイル名で保存し,python3コマンドで実行しよう.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from sklearn.linear_model import LinearRegression # data ramen = pd.read_csv('data/ramen.csv', index_col=0) feature_names = np.array(ramen.columns[:-1]) ramen_X = np.array(ramen[feature_names]) ramen_y = np.array(ramen['rating']) # train, predict regr = LinearRegression() regr.fit(ramen_X, ramen_y) ramen_y_pred = regr.predict(ramen_X) # plot x_min = 0 x_max = 100 y_min = 0 y_max = 100 xx, yy = np.mgrid[x_min:x_max:200j, y_min:y_max:200j] plt.scatter(ramen_X, ramen_y, color='#FF8888', edgecolors='k') plt.plot(ramen_X, ramen_y_pred, color='#000000', linewidth=3) plt.title("ramen") plt.xlabel('richness') plt.ylabel('rating') plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.show() |
難易度:★
| ミッション | 説明 |
|---|---|
| 1 | python3コマンドでskl02_plt.pyを実行する. |