ML 100day fiveday(邏輯迴歸、數據歸一化、評估預測、matplotlib數據展示)

在這裏插入圖片描述***
注意一點就是,訓練模型的參數是一批***

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv(‘C:\Users\Administrator\Desktop\ml 100day\Social_Network_Ads.csv’)
dataset.head()

User ID Gender Age EstimatedSalary Purchased
0 15624510 Male 19 19000 0
1 15810944 Male 35 20000 0
2 15668575 Female 26 43000 0
3 15603246 Female 27 57000 0
4 15804002 Male 19 76000 0
#劃分XY
X = dataset.iloc[:, [2, 3]].values
Y = dataset.iloc[:,4].values
#使用model_selection來劃分訓練集和測試集
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.25, random_state

#Feature Scaling,歸一化,縮小範圍,加速梯度下降收斂(注意:針對樹類算法沒有必要)
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()

#相同規則進行訓練 而不是X_test = sc.fit_transform(X_test)l
X_train = sc.fit_transform(X_train) 注意這裏fit_transform和transform
X_test = sc.transform(X_test)

#logistic Regression to the Train set
from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression()
classifier.fit(X_train, y_train)

#使用訓練好的模型預測值
y_pred = classifier.predict(X_test)

#評估預測:我們預測了測試集。現在我們將評估模型是否正確的學習和理解。因此這個混淆矩陣包含我們模型的正確和錯誤的預測
#生成混淆矩陣,只有在對角線上的纔是預測正確的數據
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test,y_pred)

from matplotlib.colors import ListedColormap
X_set,y_set=X_train,y_train

#numpy.meshgrid()——生成網格點座標矩陣。
X1,X2=np. meshgrid(np. arange(start=X_set[:,0].min()-1, stop=X_set[:, 0].max()+1, step=0.01),
np. arange(start=X_set[:,1].min()-1, stop=X_set[:,1].max()+1, step=0.01))
#contour和contourf都是畫三維等高線圖的,不同點在於contourf會對等高線間的區域進行填充
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(),X2.ravel()]).T).reshape(X1.shape),
alpha = 0.75, cmap = ListedColormap((‘red’, ‘green’)))
plt.xlim(X1.min(),X1.max())
plt.ylim(X2.min(),X2.max())
for i,j in enumerate(np. unique(y_set)):
plt.scatter(X_set[y_setj,0],X_set[y_setj,1],
c = ListedColormap((‘red’, ‘green’))(i), label=j)

plt. title(’ LOGISTIC(Training set)’)
plt. xlabel(’ Age’)
plt. ylabel(’ Estimated Salary’)
plt. legend()
plt. show()
在這裏插入圖片描述

在這裏插入圖片描述

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