2016-04-29 19 views
0

私はPythonを使って2つのクラスと関連する予測確率を与えられたこのイメージをクラシファイアから再作成しようとしています。私は主に直線を得るように、それはしかし働いていない sigmoid curveScikitlearnでシグモイド確率曲線をプロットする方法は?

私はこのような何かを見たいと思っています。 **注:私はこのデータが現在疑わしいか悪いかを知っています。私は入力&モデルを調整する必要があるが、プロットを見たいと思った

基本的に、私は "0"クラスに関してすべてであるようにpredict_proba()出力を "修正"したいと思ったそれは "1"クラスを予測し、 "0"クラスの確率は1-(1classProbability)であり、95%予測はクラス "1"が5%変化するようになります。 。 enter image description here

ここの:predicition値とシグモイドっぽい何かで終わるが

は残念ながら、私はこれで終わります私は確率シグモイドプロットするために(失敗した)しようとしている私のpythonのチャンク:以下、参考のため

########################### 
## I removed my original Python code because it was very, very wrong so as to avoid any confusion. 
########################### 

は、私は私のPythonのモデルに複製しようとしているMATLABでプロットしたものです。

%Build the model 
mdl = fitglm(X, Y, 'distr', 'binomial', 'link', 'logit') 
%Build the sigmoid model 
B = mdl.Coefficients{:, 1}; 
Z = mdl.Fitted.LinearPredictor 
yhat = glmval(B, X, 'logit'); 
figure, scatter(Z, yhat), hold on, 
gscatter(Z, zeros(length(X),1)-0.1, Y) % plot original classes 
hold off, xlabel('\bf Z'), grid on, ylim([-0.2 1.05]) 
title('\bf Predicted Probability of each record') 

答えて

0

あり、これを行うために、よりニシキヘビの方法は、おそらくですが、ここで私が最後に思い付くことができたものです。

(データはこの場合には十分に分離されていない、覚えておいてください、その曲線はシグモイド曲線上0.50ポイントで区切られたクラスを持つ伝統的な外観を持っているdoen't。)

############################################################################# 
#### Draws a sigmoid probability plot from prediction results ############### 
############################################################################# 
import matplotlib.pyplot as plt 
import numpy as np 
print ('-'*40) 

# make the predictions (class) and also get the prediction probabilities 
y_train_predict = clf.predict(X_train) 
y_train_predictProbas = clf.predict_proba(X_train) 
y_train_predictProbas = y_train_predictProbas[:, 1] 

y_test_predict = clf.predict(X_test) 
y_test_predictProbas = clf.predict_proba(X_test) 
y_test_predictProbas = y_test_predictProbas[:, 1] 

#Get the thetas from the model 
thetas = clf.coef_[0] 
intercept = clf.intercept_[0] 
print 'thetas=' 
print thetas 
print 'intercept=' 
print intercept 

#Display the predictors and their associated Thetas 
for idx, x in enumerate(thetas): 
    print "Predictor: " + str(labels[idx+1]) + "=" + str(x) 

#append intercept to thetas (because scikitlearn doesn't normally output theta0 
interceptAndThetas = np.append([intercept],thetas) 
X_testWithThetaZero = [] 
for row in X_test: 
    X_testWithThetaZero.append(np.append([1],row)) 

#Calculate the dot product for plotting the sigmoid 
dotProductResult = []  
for idx, x in enumerate(X_testWithThetaZero): 
    dotProductResult.append(np.dot(x, interceptAndThetas))  


fig, ax1 = plt.subplots() 

wrongDotProducts = [] 
rightDotProducts = [] 
#Build the plot 
for idx in range(0,len(dotProductResult)): 
    #plot the predicted value on the sigmoid curve 
    if y_test[idx] == 1: 
     ax1.scatter(dotProductResult[idx], y_test_predictProbas[idx], c=['green'],linewidths=0.0) 
    else: 
     ax1.scatter(dotProductResult[idx], y_test_predictProbas[idx], c=['black'],linewidths=0.0) 

    #plot the actual 
    if y_test[idx] == 1: 
     ax1.scatter(dotProductResult[idx], y_test[idx], c=['green'],linewidths=0.0) 
     #determine which ones are "wrong" so we can make a histogram 
     if y_test_predictProbas[idx] < 0.5: 
      wrongDotProducts.append(dotProductResult[idx]) 
     else: 
      rightDotProducts.append(dotProductResult[idx]) 
    else: 
     ax1.scatter(dotProductResult[idx], y_test[idx], c=['black'],linewidths=0.0) 
     #determine which ones are "wrong" so we can make a histogram 
     if y_test_predictProbas[idx] > 0.5: 
      wrongDotProducts.append(dotProductResult[idx]) 
     else: 
      rightDotProducts.append(dotProductResult[idx])   

#plt.xlim([-0.05, numInstances + 0.05]) 
plt.ylim([-0.05, 1.05]) 
plt.xlabel('x') 
plt.grid(which="major", axis='both',markevery=0.10) # which='major', 
plt.ylabel('Prediction Probability') 
plt.title('Sigmoid Curve & Histogram of Predictions') 


## Add a histogram to show where the correct/incorrect prediction distributions 
ax2 = ax1.twinx() 
ax2.hist(wrongDotProducts, bins=[-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7], hatch="/", color="black", alpha=0.2) 
ax2.hist(rightDotProducts, bins=[-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7], hatch="\\", color="green", alpha=0.2) 

ax2.set_ylabel('Histogram Count of Actual Class\n1=Green 0=Black') 
ax2.set_xlabel('') 
ax2.set_title('') 
plt.show()  

enter image description here