通過簡單示例來理解什麼是機器學習

 

1 什麼是機器學習

什麼是機器學習?

這個問題不同的人員會有不同的理解。我個人覺得,用大白話來描述機器學習,就是讓計算機能夠通過一定方式的學習和訓練,選擇合適的模型,在遇到新輸入的數據時,可以找出有用的信息,並預測潛在的需求。最終反映的結果就是,好像計算機或者其他設備跟人類一樣具有智能化的特徵,能夠快速識別和選擇有用的信息。

機器學習通常可以分爲三個大的步驟,即 輸入、整合、輸出,可以用下圖來表示大致的意思:

2 機器學習示例(scikit-learn)

在python語言中,scikit-learn是一個開源的機器學習庫。下面以sklearn爲例,來簡單描述機器學習的過程。

2.1 加載數據

通常第一步是獲取相關數據,並進行相應的處理,使之可以在後續過程中使用。

from sklearn import datasets
  • 加載iris數據集並查看相關信息
# 加載數據集
iris = datasets.load_iris()

# print(iris)
print(type(iris))
print(iris.keys())

# 查看部分數據
print(iris.data[ :5, :])
# print(iris.data)
<class 'sklearn.datasets.base.Bunch'>
dict_keys(['DESCR', 'data', 'feature_names', 'target', 'target_names'])
[[ 5.1  3.5  1.4  0.2]
 [ 4.9  3.   1.4  0.2]
 [ 4.7  3.2  1.3  0.2]
 [ 4.6  3.1  1.5  0.2]
 [ 5.   3.6  1.4  0.2]]
# 查看數據維度大小
print(iris.data.shape)

# 數據屬性
print(iris.feature_names)

# 特徵名稱
print(iris.target_names)

# 標籤
print(iris.target)
(150, 4)
['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']
['setosa' 'versicolor' 'virginica']
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2
 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
 2 2]

2.2 選擇機器學習模型or算法

在獲取數據,並將數據整理好後,需要選擇合適的模型or算法來進行訓練。
機器學習的模型有很多種,這裏不作討論,且每種模型的參數選擇也是很大的一門學問。

from sklearn import svm

svm_classifier = svm.SVC(gamma=0.1, C=100)

# 預測結果得分很低
# svm_classifier = svm.SVC(gamma=10000, C=0.001)

# 定義測試集的數據量大小
N = 10

# 訓練集
train_x = iris.data[:-N, :]
train_y = iris.target[ :-N]

# 測試集
test_x = iris.data[ :N, :]
y_true = iris.target[:N]

# 訓練數據模型
svm_classifier.fit(train_x, train_y)
SVC(C=100, cache_size=200, class_weight=None, coef0=0.0,
  decision_function_shape=None, degree=3, gamma=0.1, kernel='rbf',
  max_iter=-1, probability=False, random_state=None, shrinking=True,
  tol=0.001, verbose=False)
  • 將訓練好的模式進行測試
y_pred = svm_classifier.predict(test_x)
  • 查看測試結果
from sklearn.metrics import accuracy_score

print(accuracy_score(y_true, y_pred))
1.0

2.3 將訓練好的模型進行應用,即預測

  • 保存模型
import pickle

with open('svm_model_iris.pkl', 'wb') as f:
    pickle.dump(svm_classifier, f)
  • 加載模型進行應用
import numpy as np
# np.random.seed(9)

with open('svm_model_iris.pkl', 'rb') as f:
    model = pickle.load(f)

random_samples_index = np.random.randint(0,150,6)
random_samples = iris.data[random_samples_index, :]
random_targets = iris.target[random_samples_index]

random_predict = model.predict(random_samples)

print('真實值:', random_targets)
print('預測值:', random_predict)
真實值: [1 1 1 0 2 2]
預測值: [1 1 1 0 2 2]

閒談

預測的結果好不好,直接體現出機器學習模型選擇的優劣。對於機器學習這門高深的學問,我還有許多需要進一步學習的地方,歡迎一起交流,共同進步。

最後分享網上的一張圖,來看看如何理解Machine Learning。

如果您喜歡我的文章,歡迎關注微信公衆號:Python數據之道(ID:PyDataRoad)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章