sklearn:关闭警告
sklearn: Turning off warnings
当我使用 1 列 python pandas
DataFrame
拟合 sklearn
的 LogisticRegression
(不是 Series
对象),我收到此警告:
/Library/Python/2.7/site-packages/sklearn/preprocessing/label.py:125:
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)
我知道我可以很容易地在我的代码中添加这个警告,但是我怎样才能关闭这些警告?
已发布 here、
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# Do stuff here
感谢上面的 Andreas 发布 link。
实际上警告告诉你到底是什么问题:
您传递的二维数组恰好是 (X, 1)
的形式,但该方法需要一个一维数组并且必须采用 (X, )
.
的形式
此外,警告会告诉您如何转换为您需要的形式:y.ravel()
。因此,与其抑制警告,不如摆脱它。
你可以使用这个:
import warnings
from sklearn.exceptions import DataConversionWarning
warnings.filterwarnings(action='ignore', category=DataConversionWarning)
注意: 如果您想忽略或摆脱这样的警告
import warnings
warnings.filterwarnings("ignore")
否则,如果您正在调查问题的原因,这可能会有所帮助。
当您尝试拟合模型时,请确保 X_test
和 y_test
与训练数据中使用的相似。换句话说,X_train
和 X_test
应该具有相同的特征,并且 X_test
和 y_test
应该相同
例如:np.array(X_test)
与 X_test
不同,因为 X_train
只是一个 numpy 的 DataFrame
而 X_test
是从数据集中分离出来的:
# imports
...
clf = RandomForestClassifier(n_estimators=100)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2)
# the following produce warning since X_test's shape is different than X_train
y_predicts = clf.predict(np.array(X_test))
# no warning (both are same)
y_predicts = clf.predict(X_test)
当我使用 1 列 python pandas
DataFrame
拟合 sklearn
的 LogisticRegression
(不是 Series
对象),我收到此警告:
/Library/Python/2.7/site-packages/sklearn/preprocessing/label.py:125:
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)
我知道我可以很容易地在我的代码中添加这个警告,但是我怎样才能关闭这些警告?
已发布 here、
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# Do stuff here
感谢上面的 Andreas 发布 link。
实际上警告告诉你到底是什么问题:
您传递的二维数组恰好是 (X, 1)
的形式,但该方法需要一个一维数组并且必须采用 (X, )
.
此外,警告会告诉您如何转换为您需要的形式:y.ravel()
。因此,与其抑制警告,不如摆脱它。
你可以使用这个:
import warnings
from sklearn.exceptions import DataConversionWarning
warnings.filterwarnings(action='ignore', category=DataConversionWarning)
注意: 如果您想忽略或摆脱这样的警告
import warnings
warnings.filterwarnings("ignore")
否则,如果您正在调查问题的原因,这可能会有所帮助。
当您尝试拟合模型时,请确保 X_test
和 y_test
与训练数据中使用的相似。换句话说,X_train
和 X_test
应该具有相同的特征,并且 X_test
和 y_test
例如:np.array(X_test)
与 X_test
不同,因为 X_train
只是一个 numpy 的 DataFrame
而 X_test
是从数据集中分离出来的:
# imports
...
clf = RandomForestClassifier(n_estimators=100)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2)
# the following produce warning since X_test's shape is different than X_train
y_predicts = clf.predict(np.array(X_test))
# no warning (both are same)
y_predicts = clf.predict(X_test)