逻辑回归处理数据分类

import  numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import  matplotlib as mpl
import matplotlib.patches as mpaches
%matplotlib inline
from  sklearn.pipeline  import Pipeline
from  sklearn.neighbors  import KNeighborsClassifier
from  sklearn.linear_model  import  LogisticRegression #逻辑回归
from  sklearn.preprocessing  import StandardScaler,PolynomialFeatures
path=r"C:\Users\Tsinghua-yincheng\Desktop\SZday94\data\iris.data"
data=pd.read_csv(path,header=None)
data

在这里插入图片描述

data[4]=pd.Categorical(data[4]).codes #第四列,类型转化为编号
data

在这里插入图片描述

x,y=np.split(data.values,(4,),axis=1) #列的维度,进行数据切割
x
y

在这里插入图片描述
在这里插入图片描述

x=x[:,:2] #选择两个特征
x

在这里插入图片描述

lr=Pipeline([("sc",StandardScaler()),
             ("poly",PolynomialFeatures(degree=2)),
             ("clf",LogisticRegression())]) #处理数据
lr.fit(x,y.ravel()) #训练数据
y_new=lr.predict(x)#预测数据
np.mean(y_new==y.ravel()) #精确度为81%

lr=Pipeline([("sc",StandardScaler()),
             ("poly",PolynomialFeatures(degree=2)),
             ("clf",KNeighborsClassifier())]) #处理数据
lr.fit(x,y.ravel()) #训练数据
y_new=lr.predict(x)#预测数据
np.mean(y_new==y.ravel()) #精确度为82.6%

lr=Pipeline([("sc",StandardScaler()),
             ("poly",PolynomialFeatures(degree=2)),
             ("clf",LogisticRegression())]) #处理数据
lr.fit(x,y.ravel()) #训练数据
y_new=lr.predict(x)#预测数据
np.mean(y_new==y.ravel()) #精确度为82.6%

在这里插入图片描述

y_new_prob=lr.predict_proba(x) #预测
y_new_prob

在这里插入图片描述

#绘图
N,M=500,500#横纵数据采样
x1_min,x1_max=x[:,0].min(),x[:,0].max() #第一列的范围
x2_min,x2_max=x[:,1].min(),x[:,1].max() #第2列的范围
t1=np.linspace(x1_min,x1_max,N)
t2=np.linspace(x2_min,x2_max,M) #数据切割500份
x1,x2=np.meshgrid(t1,t2)#生成表格,
x_test=np.stack((x1.flat,x2.flat),axis=1) #测试的点

mpl.rcParams['font.sans-serif'] = ['simHei']
mpl.rcParams['axes.unicode_minus'] = False#中文乱码

#两个颜色列表
cmp_light=mpl.colors.ListedColormap(["#77AABB",
                                     "#7700BB",
                                     "#77AAFF"])
cmp_dark=mpl.colors.ListedColormap(["g","r","b"])

y_new=lr.predict(x_test)#预测数据
y_new=y_new.reshape(x1.shape) #调整形状

plt.figure(facecolor="w")
plt.pcolormesh(x1,x2,y_new,cmap=cmp_light) #预测的绘图
plt.scatter(x[:,0],x[:,1],c=y,edgecolors="k",s=50,
            cmap=cmp_dark) #绘制样本
plt.xlim(x1_min,x1_max)
plt.ylim(x2_min,x2_max) #设置边界
plt.xlabel("列1 特征1")
plt.ylabel("列2 特征2")
plt.grid()

plt.legend()
plt.title("回归分类")
plt.show()

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青灯有味是儿时

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值