python逻辑回归小练习

from sklearn.linear_model import LogisticRegression
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

file_name = 'iris.csv'
names = ['separ-length', 'separ-width','petal-length','petal-width','class']
data = pd.read_csv(file_name,names=names)
array = data.values
# 为了可视化,仅用前两个特征
x = array[:, 0:2]
y = array[:, 4]
Y = np.zeros((150,1))
for i in range(0,150):
    if y[i] == 'Iris-setosa':
        Y[i] = 0
    elif y[i] == 'Iris-versicolor':
        Y[i] = 1
    else:
        Y[i] = 2




logreg = LogisticRegression()
logreg.fit(x,y)
# 画图
N, M = 500, 500  # 横纵采样率
x1_min, x1_max = x[:,0].min(), x[:,0].max()
x2_min, x2_max = x[:,1].min(), x[:,1].max()
t1 = np.linspace(x1_min, x1_max, N)
t2 = np.linspace(x2_min, x2_max, M)
x1, x2 = np.meshgrid(t1, t2)                  # 生成网格采样
x_test = np.stack((x1.flat, x2.flat),axis=1)  #  测试点为网格中的每一个点

y_hat = logreg.predict(x_test)   # 预测值
y_hat = y_hat.reshape(x1.shape)   # 输出性质与输入形状一致
Y_hat = np.zeros((N,M))
for i in range(0,500):
    for j in range(0,500):
        if y_hat[i,j] == 'Iris-setosa':
            Y_hat[i,j] = 0
        elif y_hat[i,j] == 'Iris-versicolor':
            Y_hat[i,j] = 1
        else:
            Y_hat[i,j] = 2


plt.pcolormesh(x1,x2,Y_hat)   # 预测值显示
plt.scatter(x[:,0],x[:,1], c=Y, edgecolors='k') # 样本显示
plt.xlabel('Separ-Length')
plt.ylabel('Separ-Width')
plt.xlim(x1_min, x1_max)
plt.ylim(x2_min, x2_max)
plt.grid()
plt.show()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值