机器学习代码学习(二)->>AND(与)

下面代码为: .ipynb文件, 可以在Jupyter上运行
题目为:
给了两个.csv文件(一个训练, 一个测试)
训练(x>0且y>0)与其他分开
要求找出一条线进行分类(二分法)

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

data = pd.read_csv('C:\\input\\AND.csv')
data_t = pd.read_csv('C:\\input\\AND(TEST).csv')
X = data.iloc[:, [0, 1]].values #使用0跟1列的資料
Y = data.iloc[:, 2].values #使用2列的資料

X_t = data_t.iloc[:, [0, 1]].values #使用0跟1列的資料
Y_t = data_t.iloc[:, 2].values #使用2列的資料
 
logreg =linear_model.LogisticRegression(C=10000) # C = 1/alpha
logreg.fit(X, Y)
a=logreg.score(X, Y)
b=logreg.score(X_t, Y_t)
print("logistic_train={}".format(a))
print("logistic_test={}".format(b))
# 繪製決策邊界。為此,我們將為每個顏色分配一個顏色
# 指向網格[x_min,m_max所]:[Y_MIN,Y_MAX]
x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
h = .02  # 網格中的步長
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) #根據給定的坐標向量創建坐標矩陣
Z = logreg.predict(np.c_[xx.ravel(), yy.ravel()])  #按colunm來組合
Z = Z.reshape(xx.shape) #找出0及1的座標位置
plt.figure(figsize=(15, 5))
plt.subplot(121)
plt.pcolormesh(xx, yy, Z, cmap='RdBu')
plt.scatter(X[:, 0], X[:, 1], c=Y, edgecolors='k', cmap=plt.cm.Paired)
plt.xlabel('x')
plt.ylabel('y')
plt.title("train")
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())


x_min_t, x_max_t = X_t[:, 0].min() - .5, X_t[:, 0].max() + .5
y_min_t, y_max_t = X_t[:, 1].min() - .5, X_t[:, 1].max() + .5
h = .02  # 網格中的步長
xx_t, yy_t = np.meshgrid(np.arange(x_min_t, x_max_t, h), np.arange(y_min_t, y_max_t, h)) #根據給定的坐標向量創建坐標矩陣
Z_t = logreg.predict(np.c_[xx_t.ravel(), yy_t.ravel()])  #按colunm來組合
Z_t = Z_t.reshape(xx_t.shape) #找出0及1的座標位置
plt.subplot(122)
plt.pcolormesh(xx_t, yy_t, Z_t, cmap='RdBu')
plt.scatter(X_t[:, 0], X_t[:, 1], c=Y_t, edgecolors='k', cmap=plt.cm.Paired)
plt.xlabel('x')
plt.ylabel('y')

plt.show()



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Laura_Wangzx

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

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

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

打赏作者

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

抵扣说明:

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

余额充值