【发布时间】:2018-12-14 07:21:45
【问题描述】:
我正在尝试使用 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'
帮我解决这个问题。
提前致谢。
【问题讨论】:
-
您发布的错误很容易解决,但是由于您的
X是二维的,所以您a)不能使用np.polyfit和b)我不知道您想如何绘制数据(2D -> 1D,这将是一个 3D 图),所以我不确定你想要实现什么。 -
嘿@cheersmate,你能建议我解决这个问题的方法吗?
-
关于 a) 和 b) 的问题呢?
-
你不能适应字符串。你的
Y_label应该是0s 和1s 而不是"0"s 和"1"s。
标签: python numpy matplotlib plot logistic-regression