Machine Learning (5) - Training and Testing Data

Rachel發表於2019-06-06

引言

Machine Learning 的最佳實踐是,拿到一個資料集, 將其按比例劃分, 取其中大部分資料做資料模型, 一小部分用來對分析出來的模型做測試. 原因是顯而易見的,如果用同樣的資料既做訓練又做測試,是沒有意義的。

實現的方法很簡單,使用 train_test_split()函式即可。

Machine Learning (5) - Training and Testing Data

正文

通過一個簡單的例子,看下 train_test_split() 函式的用法。

import pandas as pd

// 引入資料集
df = pd.read_csv('/Users/rachel/Downloads/py-master/ML/6_train_test_split/carprices.csv')

// 將資料集以圖形化的形式輸出
import matplotlib.pyplot as plt
%matplotlib inline
plt.scatter(df['Mileage'], df['Sell Price($)'])

Machine Learning (5) - Training and Testing Data

plt.scatter(df['Age(yrs)'], df['Sell Price($)'])

Machine Learning (5) - Training and Testing Data

X = df[['Age(yrs)', 'Mileage']]
y = df['Sell Price($)']

// 劃分資料, 30% 做測試, 加入 random_state=10 引數, 
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=10)

len(X_train) // 檢視建模資料的長度為 14
len(X_test) // 檢視測試資料的長度為 6

from sklearn.linear_model import LinearRegression
clf = LinearRegression()

// 訓練模型
clf.fit(X_train, y_train)

// 對於測試資料進行預測的結果
clf.predict(X_test) 
// 輸出
array([20668.52722622, 16762.33242213, 25160.18381011, 27209.30003936,
       37903.32633702, 14729.61531335])

// 測試資料的實際值
y_test
// 輸出
7     19300
10    18700
5     26750
6     32000
3     40000
18    12800
Name: Sell Price($), dtype: int64

// 模型準確度評估 0.9212422483776328
clf.score(X_test, y_test) 

相關文章