使用线的权重和偏置绘制超平面(分隔线)?(单层感知器)?

我需要根据身高和体重绘制分隔线,以使用单层感知器的输出区分男性和女性。

我有一个名为data.txt的文件,其中包含两个特征(身高和体重)以及性别,0表示男性,1表示女性

例如:

|---------------------|------------------|------|
|      150.5          |     5.2          |   1  |
|---------------------|------------------|------|
|      142.8          |     4.0          |   0  |
|---------------------|------------------|------|
|      150.5          |     5.2          |   1  |
|---------------------|------------------|------|
|      190            |     5.7          |   0  |
|---------------------|------------------|------|
import numpy as np
from sklearn import svm
import matplotlib.pyplot as plt
from sklearn.linear_model import perceptron
from pandas import *
import fileinput
f = fileinput.input('data.txt')
#女性和男性的身高 X_1 = []
#女性和男性的体重 X_2 = []
#标签 0 表示男性,1 表示女性 Y = []
for line in f:
    temp = line.split(",")
    if str(temp[2]) == '0\n' :
        X_1.append(round(float(temp[0]),2))
        X_2.append(round(float(temp[1]),2))
        Y.append(0)
    else:
        X_1.append(round(float(temp[0]), 2))
        X_2.append(round(float(temp[1]), 2))
        Y.append(1)
print len(X_1)
print len(Y)
inputs = DataFrame({'Height' : X_1,
'Weight' : X_2,
'Targets' : Y})
colormap = np.array(['r', 'b'])
net = perceptron.Perceptron(n_iter=1000, verbose=0, random_state=None, fit_intercept=True, eta0=0.002)
# 训练感知器对象(net)
net.fit(inputs[['Height','Weight']],inputs['Targets'])
# 输出值
print "Coefficient 0 " + str(net.coef_[0, 0])
print "Coefficient 1 " + str(net.coef_[0, 1])
print "Bias " + str(net.intercept_)
plt.scatter(inputs.Height,inputs.Weight, c=colormap[inputs.Targets],s=20)
# 计算超平面(决策边界)
ymin, ymax = plt.ylim()
w = net.coef_[0]
a = -w[0] / w[1]
xx = np.linspace(ymin, ymax)
yy = a * xx - (net.intercept_[0]) / w[1]
# 绘制超平面
plt.plot(xx, yy, 'k-')
plt.show()

但是我的图表看起来像这样 带有分隔线的图表

而我实际没有线的图表看起来是这样的。我不知道我做错了什么 输入图像描述


回答:

替换

ymin, ymax = plt.ylim() 

 xmin, xmax = plt.xlim() 

因此,与计算超平面相关的部分将如下所示

# 计算超平面(决策边界)
xmin, xmax = plt.xlim()
w = net.coef_[0]
a = -w[0] / w[1]
xx = np.linspace(xmin, xmax)
yy = a * xx - (net.intercept_[0]) / w[1] 

输入图像描述

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注