자작 카드 프로그램 sklearn 안은 의합 우도 검사입니다

2234 단어 nlp
이것은 열연표의 독립성 검사입니다. (텍스트에 대한)
import pandas as pd
#X = np.array([[1,0,1,0],[0,0,1,0],[0,1,1,0],[1,1,1,1],[1,0,1,0],[0,0,1,0]])
import numpy as np
import warnings
from numpy import mat
from scipy import special, stats
from scipy.sparse import issparse
from sklearn.preprocessing import LabelBinarizer
from sklearn.utils.extmath import safe_sparse_dot, row_norms
from sklearn.base import BaseEstimator
from sklearn.preprocessing import LabelBinarizer
from sklearn.utils import (as_float_array, check_array, check_X_y, safe_sqr,
                     safe_mask)
from sklearn.utils.extmath import safe_sparse_dot, row_norms
from sklearn.utils.validation import check_is_fitted



def my_chisquare(f_obs, f_exp):
    
    f_obs = np.asarray(f_obs, dtype=np.float64)

    k = len(f_obs)
    # Reuse f_obs for chi-squared statistics
    chisq = f_obs
    chisq -= f_exp
    chisq **= 2
    with np.errstate(invalid="ignore"):
        chisq /= f_exp
    chisq = chisq.sum(axis=0)
    return chisq


def my_chi2(X, y):
    
    X = check_array(X, accept_sparse='csr')
    if np.any((X.data if issparse(X) else X) < 0):
        raise ValueError("Input X must be non-negative.")


    Y = LabelBinarizer().fit_transform(y)
    if Y.shape[1] == 1:
        Y = np.append(1 - Y, Y, axis=1)


    
    observed1 = safe_sparse_dot(Y.T, X)          # n_classes * n_features
    
    feature_count = X.sum(axis=0).reshape(1, -1)
    class_prob = Y.mean(axis=0).reshape(1, -1)
    expected1 = np.dot(class_prob.T, feature_count)
    feature_count2 = (X.shape[0]-feature_count).reshape(1,-1)   # X.shape[0]  len(X)
    expected2 = np.dot(class_prob.T, feature_count2)
    expected = np.concatenate([expected1,expected2],axis=0)
    
    y_num0 = (Y.sum(axis = 0).reshape(1,-1))[0,0]       #        
    y_num1 = (Y.sum(axis = 0).reshape(1,-1))[0,1] 
    C = y_num0-observed1[0].reshape(1,-1)
    D = y_num1-observed1[1].reshape(1,-1)
    observed2 = np.concatenate([observed1,C,D],axis=0)
    
    
    return my_chisquare(observed2, expected)

my_chi2([[1,0,1,0],[0,0,1,0],[0,1,1,0],[1,1,1,1],[1,0,1,0],[0,0,1,0]],['yes','yes','no','yes','no','no'])

좋은 웹페이지 즐겨찾기