我正在尝试阅读完整的泰坦尼克号数据集,可在此处找到:
biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic3.xls
import pandas as pd
# Importing the dataset
dataset = pd.read_excel('titanic3.xls')
y = dataset.iloc[:, 1].values
x = dataset.iloc[:, 2:14].values
# Create Dataset for Men
men_on_board = dataset[dataset['sex'] == 'male']
male_fatalities = men_on_board[men_on_board['survived'] ==0]
X_male = male_fatalities.iloc[:, [4,8]].values
# Taking care of missing data
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0)
imputer = imputer.fit(X_male[:,0])
X_male[:,0] = imputer.transform(X_male[:,0])
当我运行除最后一行以外的所有行时,我收到以下警告:
/Users/<username>/anaconda/lib/python3.6/site-packages/sklearn/utils/validation.py:395: DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.
DeprecationWarning)
当我运行最后一行时,它会抛出以下错误:
File "<ipython-input-2-07afef05ee1c>", line 1, in <module>
X_male[:,0] = imputer.transform(X_male[:,0])
ValueError: could not broadcast input array from shape (523) into shape (682)
我已经将上面的代码片段用于其他项目的插补,不知道为什么它不起作用。
答案 0 :(得分:2)
快速解决方案是将axis = 0
更改为axis = 1
。这将使它工作,但我不确定这是否是你想要的。所以我想对这里发生的事情做一些解释如下:
警告基本上告诉你sklearn estimator now requires 2D data arrays rather than 1D data arrays将数据解释为样本(行)与特征(列)的关系。在此弃用过程中,此要求由np.atleast_2d强制执行,假设您的数据具有单个样本(行)。同时,您将axis = 0
传递给strategy = 'mean'
X_male[:,0][~np.isnan(X_male[:,0])].reshape(1, -1)
的{{1}}。但是,您现在只有一行。当遇到缺失值时,没有意义来替换该缺失值。因此,将丢弃整个列(仅包含此缺失值)。如您所见,这等于
X_male[:,0] = imputer.transform(X_male[:,0])
这就是作业X_male[:,0]
失败的原因:imputer.transform(X_male[:,0])
是形状(682),而imputer.transform(X_male[:,0])
是形状(523)。我之前的解决方案基本上将其更改为“沿着行进行插补”,其中您有意义替换缺失值。这次你不会丢弃任何内容,X_male[:,0]
是形状(682),可以分配给X.reshape(-1, 1)
。
现在我不知道为什么你的插补代码片段适用于其他项目。对于您的具体情况,有关弃用警告的(逻辑上)更好的方法可能是使用X_male[:,0]
,因为您的数据具有单个功能和682个样本。但是,您需要重新整形转换后的数据,然后才能将其分配到imputer = imputer.fit(X_male[:,0].reshape(-1, 1))
X_male[:,0] = imputer.transform(X_male[:,0].reshape(-1, 1)).reshape(-1)
:
date_add