MATLAB。用平均值替换缺失值

标签 matlab machine-learning

问题

如何用字符串(最常出现的类)和数字列的平均值替换丢失的列值?

数据示例取自:

UCI ML Repo. Iris

例如,将 NaN 替换为'Iris-setosa'

enter image description here

我有代码

它仅替换值,但也如何替换字符串。

function dataWithReplaced = replaceNaNWithAvg(data)

dataWithReplaced = [ ];

averagePerCol = table2array(varfun(@nanmean, data(: , 1:4)));

for i = 1:4

    dataColumn = table2array(data( : , i));
    dataColumn(isnan(dataColumn)) = averagePerCol(1, i);

    dataWithReplaced = [dataWithReplaced dataColumn];

end

end

我是 MATlab 的新手,所以很多事情对我来说并不明显。

最佳答案

以下解决方案解决了该问题:

由于您是 Matlab 新手,我的解决方案对您来说看起来非常复杂(对我来说看起来很复杂)。
可能有一个更简单的解决方案,但我找不到......

请参阅以下代码示例:

%Create data table for the example.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
VarName1 = [4.9; 7.3; 6.7; 7.2; 6.5; 6.4; 6.8; 5.7; 5.8; 6.4; 6.5];
VarName2 = [2.5; 2.9; 2.5; 3.6; 3.2; 2.7; 3.0; 2.5; 2.8; 3.2; 3.0];
VarName3 = [4.5; 6.3; 5.8; 6.1; 5.1; 5.3; 5.5; 5.0; 5.1; 5.3; 5.5];
VarName4 = [1.7; 1.8; 1.8; 2.5; 2.0; 1.9; 2.1; 2.0; 2.4; 2.3; 1.8];
VarName5 = {NaN; 'aa'; 'aa'; 'bbb'; NaN; 'ccc'; 'ccc'; 'ccc'; 'ccc'; 'dddd'; 'dddd'};
data = table(VarName1, VarName2, VarName3, VarName4, VarName5);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%Convert last table column to cell array.
stringColumn = table2cell(data(:, 5));

%Remove all NaN elements from cell array
%Reference: https://www.mathworks.com/matlabcentral/newsreader/view_thread/314852
x = stringColumn(cell2mat(cellfun(@ischar,stringColumn,'UniformOutput',0)));

%Find most repeated string in cell array:
%Reference: https://www.mathworks.com/matlabcentral/answers/7973-how-to-find-out-which-item-is-mode-of-cell-array
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
y = unique(x);
n = zeros(length(y), 1);
for iy = 1:length(y)
    n(iy) = length(find(strcmp(y{iy}, x)));
end
[~, itemp] = max(n);
commonStr = y(itemp);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%Find all indeces of NaN elements in stringColumn.
nanIdx = find(cell2mat(cellfun(@ischar,stringColumn,'UniformOutput',0)) == 0);

%Rplace elements with NaN values with commonStr.
stringColumn(nanIdx) = commonStr;

%Replace last column of original table
data(:, 5) = stringColumn;

关于MATLAB。用平均值替换缺失值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40073655/

相关文章:

matlab - 更改 Matlab 默认的 x 限制行为

matlab - 在 Matlab 中测试 float 是否为整数

matlab - 如何在 MATLAB 中计算环的半径?

python - 语音队列寻找句子中口语单词的重复部分

image-processing - 具有反卷积或其他功能的高档层

python - 我可以将 python 配置为像打印一样使用 matlab 吗?

artificial-intelligence - 决策树剪枝的效果

python - tf.zeros() 是否返回 tf.get_variable()?

machine-learning - 如何通过 LibSVM Weka 实现预处理数据集以获得最大效率

matlab - matlab 中的 svmtrain - 约束不够严格。