Train a Bernoulli Naive Bayes model on binary features and return the unnormalized log posterior for every test sample and class.
θjc=Nc+2Njc+1 logP(c∣x)=logP(c)+j=1∑D[xjlogθjc+(1−xj)log(1−θjc)]Here, Nc is the number of training samples in class c, Njc counts class-c samples whose feature j is one, and D is the feature count. The added one and two implement Laplace smoothing. Order output columns by ascending class label, round values to four decimals, and return a NumPy array of shape (n_test, n_classes).
Input: X_train = [[1, 0], [0, 1]], y_train = [1, 0], X_test = [[1, 0]]
Output: [[-2.8904, -1.5041]]
Explanation: The columns correspond to classes 0 and 1, and the observed feature pattern is more likely under class 1.
Input: X_train = [[1, 0], [1, 1], [0, 0], [0, 1]], y_train = [0, 0, 1, 1], X_test = [[1, 0], [0, 1]]
Output: [[-1.674, -2.7726], [-2.7726, -1.674]]
Use np.unique(y_train, return_counts=True) to obtain sorted classes and priors.
For one class, X_train[y_train == label].sum(axis=0) gives all feature-one counts.
Evaluate the Bernoulli terms with matrix multiplication against np.log(theta) and np.log1p(-theta).
Sign in to take notes on this problem
Accepts: array
Accepts: array
Accepts: array
Train a Bernoulli Naive Bayes model on binary features and return the unnormalized log posterior for every test sample and class.
θjc=Nc+2Njc+1 logP(c∣x)=logP(c)+j=1∑D[xjlogθjc+(1−xj)log(1−θjc)]Here, Nc is the number of training samples in class c, Njc counts class-c samples whose feature j is one, and D is the feature count. The added one and two implement Laplace smoothing. Order output columns by ascending class label, round values to four decimals, and return a NumPy array of shape (n_test, n_classes).
Input: X_train = [[1, 0], [0, 1]], y_train = [1, 0], X_test = [[1, 0]]
Output: [[-2.8904, -1.5041]]
Explanation: The columns correspond to classes 0 and 1, and the observed feature pattern is more likely under class 1.
Input: X_train = [[1, 0], [1, 1], [0, 0], [0, 1]], y_train = [0, 0, 1, 1], X_test = [[1, 0], [0, 1]]
Output: [[-1.674, -2.7726], [-2.7726, -1.674]]
Use np.unique(y_train, return_counts=True) to obtain sorted classes and priors.
For one class, X_train[y_train == label].sum(axis=0) gives all feature-one counts.
Evaluate the Bernoulli terms with matrix multiplication against np.log(theta) and np.log1p(-theta).
Sign in to take notes on this problem
Accepts: array
Accepts: array
Accepts: array