Main Content

MapReduce を使用した最大値の検索

次の例では、mapreduce を使用してデータ セット内の単独の変数の最大値を検索する方法を示します。キーは 1 つのみで最低限の計算を行うため、これは mapreduce の最も簡単な使用法を示しています。

データの準備

airlinesmall.csv データ セットを使用してデータストアを作成します。この 12 MB のデータ セットには、到着時間と出発時間を含む、いくつかの航空会社のフライト情報が 29 列に含まれます。この例では、ArrDelay (フライト到着遅延時間) を目的の変数として選択します。

ds = tabularTextDatastore('airlinesmall.csv', 'TreatAsMissing', 'NA');
ds.SelectedVariableNames = 'ArrDelay';

データストアは、既定では 'NA' 値を欠損として扱い、欠損値を NaN 値に置換します。さらに、SelectedVariableNames プロパティにより、選択した目的の変数のみを処理することができ、preview を使用して検査できます。

preview(ds)
ans=8×1 table
    ArrDelay
    ________

        8   
        8   
       21   
       13   
        4   
       59   
        3   
       11   

mapreduce の実行

関数 mapreduce は、入力として map 関数と reduce 関数を必要とします。マッパーはデータのブロックを受け取って中間結果を出力します。リデューサーは中間結果を読み取って最終結果を生成します。

この例では、マッパーはデータの各ブロック内の最大到着遅延時間を求めます。次にマッパーは、これらの最大値をキー 'PartialMaxArrivalDelay' に関連付けられた中間値として保存します。

map 関数のファイルを表示します。

function maxArrivalDelayMapper (data, info, intermKVStore)
  partMax = max(data.ArrDelay);
  add(intermKVStore, 'PartialMaxArrivalDelay',partMax);
end

リデューサーは、各ブロックの最大到着遅延時間のリストを受け取り、値のリストから全体の最大到着遅延を求めます。マッパーは単一の一意なキーのみを追加するため、mapreduce はこのリデューサーを一度だけ呼び出します。リデューサーは、add を使用して最終的なキーと値のペアを出力に追加します。

reduce 関数のファイルを表示します。

function maxArrivalDelayReducer(intermKey, intermValIter, outKVStore)
  % intermKey is 'PartialMaxArrivalDelay'. intermValIter is an iterator of
  % all values that has the key 'PartialMaxArrivalDelay'.
  maxVal = -Inf;
  while hasnext(intermValIter)
    maxVal = max(getnext(intermValIter), maxVal);
  end
  % The key-value pair added to outKVStore will become the output of mapreduce 
  add(outKVStore,'MaxArrivalDelay',maxVal);
end

mapreduce を使用して、map 関数および reduce 関数をデータストア ds に適用します。

maxDelay = mapreduce(ds, @maxArrivalDelayMapper, @maxArrivalDelayReducer);
********************************
*      MAPREDUCE PROGRESS      *
********************************
Map   0% Reduce   0%
Map  16% Reduce   0%
Map  32% Reduce   0%
Map  48% Reduce   0%
Map  65% Reduce   0%
Map  81% Reduce   0%
Map  97% Reduce   0%
Map 100% Reduce   0%
Map 100% Reduce 100%

mapreduce は、現在のフォルダー内のファイルでデータストア maxDelay を返します。

出力データストア maxDelay から最終結果を読み取ります。

readall(maxDelay)
ans=1×2 table
            Key             Value  
    ___________________    ________

    {'MaxArrivalDelay'}    {[1014]}

参考

|

関連するトピック