Результаты регрессии KNN приводят к отсутствию MSE на тренировочном наборе (sklearn) - PullRequest
0 голосов
/ 15 ноября 2018

Используя sklearn и пытаясь оценить функцию регрессии KNN с помощью приведенного ниже кода:

def cross_validate(X,y,n_neighbors, test_size=0.20):
    training_mses = []
    test_mses = []

    n = X.shape[ 0]
    test_n = int( np.round( test_size * n, 0))

    indices = np.arange(n)
    random.shuffle( indices)

    test_indices = indices[ 0:test_n]
    training_indices = indices[test_n:]


    X_test, y_test = X[test_indices], y[test_indices]
    X_train,y_train = X[training_indices], y[training_indices]

    knn = neighbors.KNeighborsRegressor(n_neighbors=n_neighbors, weights = "distance",
                                    algorithm = 'brute')
    model = knn.fit(X_train,y_train)
    y_hat = model.predict( X_train)
    training_mse = mse( y_train - y_hat)

    model2 = knn.fit(X_test,y_test)
    y_hat = model2.predict( X_test)
    test_mse = mse( y_test - y_hat)

    return training_mse, test_mse 

Я сделал нечто подобное с линейной регрессией.Разница, которую я обнаружил, состоит в том, что когда я запускаю его по регрессии KNN, training_mse и test_mse оба равны 0. Если я использую тестовые данные на модели, снабженной обучающим набором, это дает мне значение mse, которое не равно нулю.Но я просто не верю, что установленные значения для тренировочного и тестового набора совпадают с наблюдаемыми значениями.Что я делаю неправильно?Функция, которую я пытался эмулировать, приведена ниже и дает ненулевые значения для mse:

def cross_validate( formula, data, test_size=0.20):
    training_mses = []
    test_mses = []

    n = data.shape[ 0]
    test_n = int( np.round( test_size * n, 0))

    indices = deepcopy( data.index).values
    random.shuffle( indices)

    test_indices = indices[ 0:test_n]
    training_indices = indices[test_n:]

    test_set = data.ix[ test_indices]
    training_set = data.ix[ training_indices]

    y, X = patsy.dmatrices( formula, training_set, return_type="matrix")
    model = linear.LinearRegression( fit_intercept=False).fit( X, y)
    y_hat = model.predict( X)

    training_mse = mse( y - y_hat)

    y, X = patsy.dmatrices( formula, test_set, return_type="matrix")
    y_hat = model.predict( X)

    test_mse = mse( y - y_hat)

    return training_mse, test_mse
...