Как разделить тестовые и обучающие данные для графика границы решения? - PullRequest
0 голосов
/ 21 июня 2020

Я пытаюсь построить график границы решения, используя некоторые переменные. Я знаю, что мне нужно разделить данные на тестовые и обучающие данные, а затем построить границу решения, что можно сделать с помощью строки x_train, x_test, однако, похоже, я столкнулся с проблемой. Ниже я также покажу свои ошибки.

def LogReg2D0732():
    GDP = np.array(GDPArr) # Temp
    Support = np.array(SupportArr) #Income
    Score = np.array(list(map(ScoreConvert, ScoreArr))) #Sales
    
    X = GDP
    X = np.vstack((X,Support)) # var x samples
    y = Score 
    
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    
    # use sci-kit learn
    clf = LogisticRegression(fit_intercept=True, C = 1e15) # instantiate
    clf.fit(X.T, y) # do the fit
    print("Coef ", clf.intercept_, clf.coef_) # print some attributes
    xx, yy = np.mgrid[np.min(GDP):np.max(GDP):0.01, np.min(Support):np.max(Support):0.01]
    gridxy = np.c_[xx.ravel(), yy.ravel()]
    probs = clf.predict_proba(gridxy)[:,1].reshape(xx.shape)
    f, ax = plt.subplots(figsize=(12, 8))
    contour = ax.contourf(xx, yy, probs, 25, cmap="RdBu", vmin=0, vmax=1)
    ax_c = f.colorbar(contour) # for the probability range
    ax_c.set_ticks([0, 1/4, 1/2, 3/4, 1]) # and values
    idx = np.where(y==1); idx = np.reshape(idx,np.shape(idx)[1]) # tuple>list
    y1 = X[:,idx]
    idx = np.where(y==0); idx = np.reshape(idx,np.shape(idx)[1]) # tuple>list
    y0 = X[:,idx]
    ax.scatter(y1[0,:], y1[1,:], c='cyan') # light blue
    ax.scatter(y0[0,:], y0[1,:], c='pink')
    plt.title('GDP against Social support')
    plt.xlabel('GDP')
    plt.ylabel('Social Support')
    plt.savefig('LR2D.svg')
    plt.show()

    # compute AUC
    probsa = clf.predict_proba(X.T)
    probsa = probsa[:, 1] # only the positive samples
    auc = roc_auc_score(y, probsa)
    print("Area under curve:", auc)
    #fpr, tpr, thresholds = roc_curve(y, probsa)
    fpr, tpr, thresholds = roc_curve(y, probsa, drop_intermediate=False)
    plt.plot(fpr, tpr, color='sienna', label='ROC')
    plt.plot([0, 1], [0, 1], color='seagreen', linestyle='dotted') # no skill
    plt.xlabel('False Positive Rate, Specificity')
    plt.ylabel('True Positive Rate, Sensitivity')
    plt.title('Receiver Operating Characteristic (ROC) Plot')
    plt.legend()
    plt.savefig('LRauc.svg')
    plt.show() 
LogReg2D0732()#Logistic Regression


ValueError                                Traceback (most recent call last)
<ipython-input-21-31361159fc28> in <module>
     48     plt.savefig('LRauc.svg')
     49     plt.show()
---> 50 LogReg2D0732()#Logistic Regression

<ipython-input-21-31361159fc28> in LogReg2D0732()
      8     y = Score
      9 
---> 10     X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
     11 
     12     # use sci-kit learn

~/opt/anaconda3/lib/python3.7/site-packages/sklearn/model_selection/_split.py in train_test_split(*arrays, **options)
   2116         raise TypeError("Invalid parameters passed: %s" % str(options))
   2117 
-> 2118     arrays = indexable(*arrays)
   2119 
   2120     n_samples = _num_samples(arrays[0])

~/opt/anaconda3/lib/python3.7/site-packages/sklearn/utils/validation.py in indexable(*iterables)
    246     """
    247     result = [_make_indexable(X) for X in iterables]
--> 248     check_consistent_length(*result)
    249     return result
    250 

~/opt/anaconda3/lib/python3.7/site-packages/sklearn/utils/validation.py in check_consistent_length(*arrays)
    210     if len(uniques) > 1:
    211         raise ValueError("Found input variables with inconsistent numbers of"
--> 212                          " samples: %r" % [int(l) for l in lengths])
    213 
    214 

ValueError: Found input variables with inconsistent numbers of samples: [2, 156]

Я также не совсем понимаю ошибку, которая говорит о несогласованном количестве образцов [2,156]. Дайте мне знать, как решить эту проблему.

1 Ответ

0 голосов
/ 28 июня 2020

Ошибка при создании раскола. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) Ошибка означает, что форма массивов не та. Проверьте эту ссылку на наличие подобных проблем.

...