【问题标题】:plot hyperplane (separator line) using weights of line and bias? (single layer perceptron)?使用线和偏差的权重绘制超平面(分隔线)? (单层感知器)?
【发布时间】:2017-02-07 03:16:49
【问题描述】:

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

我有 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')

#height of females and males 
X_1 = []
#weight of female and males 
X_2 = []
#labels 0 males and 1 females 
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)

# Train the perceptron object (net)
net.fit(inputs[['Height','Weight']],inputs['Targets'])
# Output the values
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)

# Calc the hyperplane (decision boundary)
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]

# Plot the hyperplane
plt.plot(xx, yy, 'k-')
plt.show()

但我的图表看起来像这样

而我实际上没有线的图形看起来像那样。我不知道我做错了什么

【问题讨论】:

  • 一方面,您的xy 似乎混淆了:您从ylim 计算x,然后将x 绘制为x
  • 我明白了,谢谢你的提示

标签: matplotlib machine-learning neural-network


【解决方案1】:

替换

ymin, ymax = plt.ylim() 

 xmin, xmax = plt.xlim() 

所以与计算超平面相关的部分看起来像这样

# Calc the hyperplane (decision boundary)
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] 

【讨论】:

    猜你喜欢
    • 2023-03-11
    • 2018-01-09
    • 1970-01-01
    • 2015-09-26
    • 2011-06-22
    • 2020-11-04
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    相关资源
    最近更新 更多