第L3周:机器学习|逻辑回归 LogisticRegression

🍨 本文为[🔗365天深度学习训练营]中的学习记录博客
🍖 原作者:[K同学啊]

1、数据预处理

1-1、导入库

import numpy  as np
import pandas as pd
import matplotlib.pyplot as plt

1-2、导入数据

dataset = pd.read_csv(r"D:\资料\365deep_learning\1.机器学习\Social_Network_Ads.csv")
dataset

X = dataset.iloc[ : , [2,3]].values
Y = dataset.iloc[ : ,4].values

X.shape, Y.shape

1-3、 将数据集分成训练集和测试集 

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=0)

X_train.shape,Y_train.shape

2、逻辑回归模型 

from sklearn.linear_model import LogisticRegression

classifier = LogisticRegression()
classifier.fit(X_train, Y_train)

3、预测结果 

Y_pred = classifier.predict(X_test)

4、评估预测结果 

4-1、训练集可视化

from matplotlib.colors import ListedColormap

X_set, y_set = X_train,Y_train

x = np.arange(start=X_set[:,0].min()-1, 
              stop=X_set[:, 0].max()+1, 
              step=0.01)

y = np.arange(start=X_set[:,1].min()-1, 
              stop=X_set[:,1].max()+1, 
              step=100)

x.shape, y.shape

#把x,y绑定为网格的形式
X1,X2 =np. meshgrid(x,y)

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_set==j,0],
                X_set[y_set==j,1],
                color = ListedColormap(['red', 'green'])(i), 
                label=j)

plt.title('LOGISTIC(Training set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()

 

4-2、测试集可视化

X_set, y_set = X_test,Y_pred

x = np.arange(start=X_set[:,0].min()-1, stop=X_set[:, 0].max()+1, step=0.01)
y = np.arange(start=X_set[:,1].min()-1, stop=X_set[:,1].max()+1, step=100)
#把x,y绑定为网格的形式
X1,X2=np. meshgrid(x,y)

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_set==j,0],
                X_set[y_set==j,1],
                color = ListedColormap(('red', 'green'))(i), 
                label=j)

plt. title('LOGISTIC(Test set)')
plt. xlabel('Age')
plt. ylabel('Estimated Salary')
plt. legend()
plt. show()

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值