blob: a6585554007b440388c30cdb7176f58e19a32290 [file] [log] [blame]
#-------------------------------------------------------------
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
#-------------------------------------------------------------
D = read($1)
C = read($2)
# reading input args
numClasses = $3
laplace_correction = 1
numRows = nrow(D)
numFeatures = ncol(D)
# Compute conditionals
# Compute the feature counts for each class
classFeatureCounts = matrix(0, rows=numClasses, cols=numFeatures)
parfor (i in 1:numFeatures, opt=CONSTRAINED, mode=REMOTE_MR) {
Col = D[,i]
classFeatureCounts[,i] = aggregate(target=Col, groups=C, fn="sum")
}
# Compute the total feature count for each class
# and add the number of features to this sum
# for subsequent regularization (Laplace's rule)
classSums = rowSums(classFeatureCounts) + numFeatures*laplace_correction
# Compute class conditional probabilities
repClassSums = classSums %*% matrix(1,rows=1,cols=numFeatures);
class_conditionals = (classFeatureCounts + laplace_correction) / repClassSums;
# Compute class priors
class_counts = aggregate(target=C, groups=C, fn="count")
class_prior = class_counts / numRows;
# write out the model
write(class_prior, $4, format="text");
write(class_conditionals, $5, format="text");