2

ロジスティック回帰の結果の分布図を散布図に追加するにはどうすればよいですか? 分類子の決定境界を示す、色付きの 0/1 ゾーンが必要です。

import pandas as pd
import numpy as np
import pylab as pl
import statsmodels.api as sm

# Build X, Y from file
f = open('ex2data2.txt')
lines = f.readlines()
x1 = []
x2 = []
y = []
for line in lines:
    line = line.replace("\n", "")
    vals = line.split(",")
    x1.append(float(vals[0]))
    x2.append(float(vals[1]))
    y.append(int(vals[2]))

x1 = np.array(x1)
x2 = np.array(x2)
y = np.array(y)

x = np.vstack([x1, x2]).T

# Scatter plot 0/1s
pos_mask = y == 1
neg_mask = y == 0
pos_x1 = x1[pos_mask]
neg_x1 = x1[neg_mask]
pos_x2 = x2[pos_mask]
neg_x2 = x2[neg_mask]
pl.clf()
pl.scatter(pos_x1, pos_x2, c='r')
pl.scatter(neg_x1, neg_x2, c='g')

# Run logistic regression
logit = sm.Logit(y, x)
result = logit.fit()
result.params
result.predict([1.0, 1.0])

# Now I want to add a countour for 0/1 regression results to the scatter plot.
4

1 に答える 1

5

私は答えようとしますが、私の答えについて理解する必要があるいくつかの仮定があり、それはあなたのコードに当てはまる場合と当てはまらない場合があります。

私の輸入品:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

X次のような機能が含まれています。

print type(X)
<type 'numpy.ndarray'>

次のように 102,2 です。

print X
[[-13.15490196 -23.        ]
[-22.95490196 -25.        ]
[-12.75490196  -8.        ]
[  0.14509804  -6.        ]
.
.
.

ytrainこの場合はブール値ですが、同じように 0/1 を実行できます。

print type(ytrain)
<type 'numpy.ndarray'>

51です、

print (train)
[False False False False  True  True  True  True  True  True False  True
False  True  True  True False False False  True  True  True  True  True
False False False False  True  True  True  True  True  True False  True
False  True  True  True False False False False False  True  True  True
False  True False]

そして最後clfにモデルが含まれています。私の場合は適合モデルです。また、scikit Learn の LogisticRegression を使用しています。これはclf.predict_proba 、ラベルと輪郭を作成するために必要な情報を提供することに依存しています。私はあなたが使用している正確なパッケージに精通していませんが、これを覚えておいてください.

# evenly sampled points
x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 50),
                     np.linspace(y_min, y_max, 50))
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())

#plot background colors
ax = plt.gca()
Z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]
Z = Z.reshape(xx.shape)
cs = ax.contourf(xx, yy, Z, cmap='RdBu', alpha=.5)
cs2 = ax.contour(xx, yy, Z, cmap='RdBu', alpha=.5)
plt.clabel(cs2, fmt = '%2.1f', colors = 'k', fontsize=14)

# Plot the points
ax.plot(Xtrain[ytrain == 0, 0], Xtrain[ytrain == 0, 1], 'ro', label='Class 1')
ax.plot(Xtrain[ytrain == 1, 0], Xtrain[ytrain == 1, 1], 'bo', label='Class 2')

# make legend
plt.legend(loc='upper left', scatterpoints=1, numpoints=1)

結果は次のようになります。

ここに画像の説明を入力

于 2013-11-19T01:13:01.500 に答える