python - 绘制字符串数组 numpy 和 matplotlib

标签 python numpy matplotlib plot logistic-regression

我正在尝试使用 Matplotlib 和 Numpy 绘制逻辑回归模型
这是我的代码,

X = [[181, 80, 44], [177, 70, 43], [160, 60, 38], [154, 54, 37], [166, 65, 40]]

Y = ['male', 'male', 'female', 'female', 'male']

我已经尝试过,但没有按预期工作。

Y_label = []
for x in range(0,len(Y)):
    if Y[x] == 'male': 
        Y_label.append('1')
    else : Y_label.append('0')


fit = np.polyfit(X,Y_label,1)
fit_fn = np.poly1d(fit) 
# fit_fn is now a function which takes in x and returns an estimate for y

plt.plot(X,Y_label, 'yo', X, fit_fn(X), '--k')
plt.xlim(0, 5)
plt.ylim(0, 12)
plt.show()

运行此代码时出现错误

Traceback (most recent call last):
  File "/home/logistic_regression.py", line 27, in <module>
    fit = np.polyfit(X,Y_label,1)
  File "/usr/lib/python2.7/dist-packages/numpy/lib/polynomial.py", line 543, in polyfit
    y = NX.asarray(y) + 0.0
TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'float'

帮我解决这个问题。
提前致谢。

最佳答案

我已将您的 ployfit 函数(因为它不适用于 >1D 数据)更改为 sklearn 中的逻辑回归。 我们必须使用 3D 绘图,因为 X 是三维的。如果我们的预测正确,我就给出绿色,否则给出红色。

此外,我建议使用 sklearn Y_label 中的标签编码器。

import numpy as np
X = np.array([[181, 80, 44], [177, 70, 43], [160, 60, 38], [154, 54, 37], [166, 65, 40]])

Y = ['male', 'male', 'female', 'female', 'male']

from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = plt.axes(projection='3d')

Y_label = []
for x in range(0,len(Y)):
    if Y[x] == 'male': 
        Y_label.append(1)
    else : Y_label.append(0)

from sklearn.linear_model import LogisticRegression
reg = LogisticRegression().fit(X, Y_label)

crt_pred = Y_label ==reg.predict(X)
ax.scatter3D(X[crt_pred,0],X[crt_pred,1],X[crt_pred,2],s=50,c='g')
ax.scatter3D(X[~crt_pred,0],X[~crt_pred,1],X[~crt_pred,2],s=50,c='r')

plt.show()

enter image description here

要了解更多信息,请查看此 link

关于python - 绘制字符串数组 numpy 和 matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53775131/

相关文章:

python - 如何使用 ctypes.windll.user32.SetWindowsHookExW Hook ctypes.windll.user32.MessageBoxW?

python - 从 numpy 中 nd 数组的末尾取出一个切片

python - numpy 与 python : convert 3d array to 2d

python - 在Python中的图形上创建框

python - 在mean()之后绘图

Python Regex - 从两个 '*' 之间的字符串中查找内容

python - wtforms隐藏字段值

python - 如何将图例标题的一部分加粗(不是整个图例标题)

python - 在 apply 函数内使用定义函数的输入参数

python - 安装 nimfa 时出现问题(Python 矩阵分解库)