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 tableArrDelay ________ 8 8 21 13 4 59 3 11
mapreduce の実行
関数mapreduce
は、入力として map 関数と reduce 関数を必要とします。マッパーはデータのブロックを受け取って中間結果を出力します。リデューサーは中間結果を読み取って最終結果を生成します。
この例では、マッパーはデータの各ブロック内の最大到着遅延時間を求めます。次にマッパーは、これらの最大値をキー'PartialMaxArrivalDelay'
に関連付けられた中間値として保存します。
map 関数のファイルを表示します。
functionmaxArrivalDelayMapper (data, info, intermKVStore) partMax = max(data.ArrDelay); add(intermKVStore,'PartialMaxArrivalDelay',partMax);end
リデューサーは、各ブロックの最大到着遅延時間のリストを受け取り、値のリストから全体の最大到着遅延を求めます。マッパーは単一の一意なキーのみを追加するため、mapreduce
はこのリデューサーを一度だけ呼び出します。リデューサーは、add
を使用して最終的なキーと値のペアを出力に追加します。
reduce 関数のファイルを表示します。
functionmaxArrivalDelayReducer(intermKey, intermValIter, outKVStore)% intermKey is 'PartialMaxArrivalDelay'. intermValIter is an iterator of% all values that has the key 'PartialMaxArrivalDelay'.maxVal = -Inf;whilehasnext(intermValIter) maxVal = max(getnext(intermValIter), maxVal);end% The key-value pair added to outKVStore will become the output of mapreduce添加(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 tableKey Value ___________________ ________ {'MaxArrivalDelay'} {[1014]}
ローカル関数
ここに挙げるのは、mapreduce
がデータに適用する map 関数と reduce 関数です。
functionmaxArrivalDelayMapper (data, info, intermKVStore) partMax = max(data.ArrDelay); add(intermKVStore,'PartialMaxArrivalDelay',partMax);end%--------------------------------------------------------------------functionmaxArrivalDelayReducer(intermKey, intermValIter, outKVStore)% intermKey is 'PartialMaxArrivalDelay'. intermValIter is an iterator of% all values that has the key 'PartialMaxArrivalDelay'.maxVal = -Inf;whilehasnext(intermValIter) maxVal = max(getnext(intermValIter), maxVal);end% The key-value pair added to outKVStore will become the output of mapreduce添加(outKVStore'MaxArrivalDelay',maxVal);end%--------------------------------------------------------------------
参考
mapreduce
|tabularTextDatastore