'数据帧'对象没有属性' ravel'转换目标变量时?

时间:2018-02-17 13:07:14

标签: python numpy logistic-regression sklearn-pandas

我正在使用子集数据集进行逻辑回归。在拆分数据集并拟合模型后,我收到以下错误消息:

/Users/Eddie/anaconda/lib/python3.4/site-packages/sklearn/utils/validation.py:526: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel(). y = column_or_1d(y, warn=True)

所以我使用target_newrdn = target_newrdn.ravel()来修改我的目标变量,但它给了我这个:

AttributeError: 'DataFrame' object has no attribute 'ravel'

我想知道问题是什么,我该如何解决?有人可以帮忙吗?

我的代码:

    from sklearn.datasets import fetch_covtype
    import numpy as np
    import pandas as pd

    from sklearn.utils import shuffle
    from sklearn.model_selection import train_test_split

    cov = fetch_covtype()
    cov_data = pd.DataFrame(cov.data)
    cov_target = pd.DataFrame(cov.target)

    data_newrdn = cov_data.head(n=10000)
    target_newrdn = cov_target.head(n=10000)


    target_newrdn = target_newrdn.ravel() ## I thought this could fix it??


    X_train2, X_test2, y_train2, y_test2 = train_test_split(data_newrdn, 
    target_newrdn, random_state=42)

    scaler.fit(X_train2)
    X_train_scaled2 = scaler.transform(X_train2)

    # Logistic Regression
    param_grid = {'C': [0.001, 0.01, 0.1, 1, 10, 100, 1000]}
    print(param_grid)
    grid = GridSearchCV(LogisticRegression(), param_grid, cv=kfold) 
    grid.fit(X_train_scaled2, y_train2)
    print("Best cross-validation score w/ kfold: 
    {:.2f}".format(grid.best_score_))
    print("Best parameters: ", grid.best_params_)

1 个答案:

答案 0 :(得分:7)

显然,数据帧没有ravel功能。尝试:

target_newrdn.values.ravel()

target_newrdn.values返回一个numpy ndarray,然后对其执行ravel。注意这会返回一个展平的numpy数组。您可能需要转换回数据帧。

但我认为你需要flatten(),因为它返回一个副本,所以如果你修改ravel返回的数组,它就不会修改原始数组中的条目。