This is an implementation of Naive Bayes Classifier Algorithm.
I couldn't understand the line score.Add(results[i].Name, finalScore * 0.5);.
Where does this value 0.5 come from?
Why 0.5? Why not any other value?
public string Classify(double[] obj)
{
Dictionary<string,> score = new Dictionary<string,>();
var results = (from myRow in dataSet.Tables[0].AsEnumerable()
group myRow by myRow.Field<string>(
dataSet.Tables[0].Columns[0].ColumnName) into g
select new { Name = g.Key, Count = g.Count() }).ToList();
for (int i = 0; i < results.Count; i++)
{
List<double> subScoreList = new List<double>();
int a = 1, b = 1;
for (int k = 1; k < dataSet.Tables["Gaussian"].Columns.Count; k = k + 2)
{
double mean = Convert.ToDouble(dataSet.Tables["Gaussian"].Rows[i][a]);
double variance = Convert.ToDouble(dataSet.Tables["Gaussian"].Rows[i][++a]);
double result = Helper.NormalDist(obj[b - 1], mean, Helper.SquareRoot(variance));
subScoreList.Add(result);
a++; b++;
}
double finalScore = 0;
for (int z = 0; z < subScoreList.Count; z++)
{
if (finalScore == 0)
{
finalScore = subScoreList[z];
continue;
}
finalScore = finalScore * subScoreList[z];
}
score.Add(results[i].Name, finalScore * 0.5);
}
double maxOne = score.Max(c => c.Value);
var name = (from c in score
where c.Value == maxOne
select c.Key).First();
return name;
}
I figured it out.
0.5 is the apriori probability.
Related
void blur(int height, int width, RGBTRIPLE image[height][width])
{
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
int red_total = 0;
int blue_total = 0;
int green_total = 0;
int number_counted = 0;
for (int k = -1; k <= 1; k++)
{
for (int l = -1; l <= 1; l++)
{
if (i + k <= height && i + k >= 0 && j + l <= width && j + l >= 0)
{
blue_total += image[i+k][j+l].rgbtBlue;
red_total += image[i+k][j+l].rgbtRed;
green_total += image[i+k][j+l].rgbtGreen;
number_counted ++;
}
}
}
image[i][j].rgbtBlue = blue_total / number_counted;
image[i][j].rgbtRed = red_total / number_counted;
image[i][j].rgbtGreen = green_total / number_counted;
}
}
return;
}
Why is that section && operators?
if (i + k <= height && i + k >= 0 && j + l <= width && j + l >= 0)
I ran it with || operators because my understanding is that under the guise of the problem IF any of those conditions are satisfied there is no block to add. Yet why is it that when I run it under || it returns segmentation fault whereas if I run it with && the problem works out?
Thank you for answering!
All of those conditions have to be true or else the array operations will be invalid.
e.g. if i+k > height then image[i+k] is invalid.
Also I think you have some "off by one problems. image is [height][width] so valid values are [0..height-1] and [0..width-1] so the checks should be more like if (i + k < height && i + k >= 0 && j + l < width && j + l >= 0)
So this is the code I have for Pset4 for the Sepia filter...it's heading in the right direction but I've been trying to figure out why it isn't passing the tests. Cannot filter a simple 3 x 3 image or complex 3 x 3 image or the 4 x 4 image. Trying to figure out where the bug is, any tips would be wonderful!
void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
// get values of each colour in the image
int red = image[i][j].rgbtRed;
int blue = image[i][j].rgbtBlue;
int green = image[i][j].rgbtGreen;
// find average of the pixel RBG colors
float average = (round(red) + round(blue) + round(green)) / 3;
average = round(average);
//puts the value average into the pixel colors
image[i][j].rgbtRed = average;
image[i][j].rgbtBlue = average;
image[i][j].rgbtGreen = average;
}
}
return;
}
void sepia(int height, int width, RGBTRIPLE image[height][width])
{
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
//gets the values of each color in the image
int red = image[i][j].rgbtRed;
int blue = image[i][j].rgbtBlue;
int green = image[i][j].rgbtGreen;
// gets the sepia value of the pixels
int sepiaRed = round(0.393 * red + 0.769 * green + 0.189 * blue);
int sepiaGreen = round(0.349 * red + 0.686 * green + 0.168 * blue);
int sepiaBlue = round(0.272 * red + 0.534 * green + 0.131 * blue);
if (sepiaRed >= 256)
{
sepiaRed = 255;
}
if (sepiaGreen >= 256)
{
sepiaGreen = 255;
}
if (sepiaBlue >= 256)
{
sepiaBlue= 255;
}
image[i][j].rgbtRed = sepiaRed;
image[i][j].rgbtBlue = sepiaBlue;
image[i][j].rgbtGreen = sepiaGreen;
}
return;
}
}
I'm not sure, without seeing more of the code. But shouldn't these three ifs at the end be placed before you save their values to the image? Like this:
...
if (sepiaRed >= 256)
{
sepiaRed = 255;
}
if (sepiaGreen >= 256)
{
sepiaGreen = 255;
}
if (sepiaBlue >= 256)
{
sepiaBlue = 255;
}
image[i][j].rgbtRed = sepiaRed;
image[i][j].rgbtBlue = sepiaBlue;
image[i][j].rgbtGreen = sepiaGreen;
...
First You check if calculated values are not higher than 255. Then save these values to the image.
Also you should replace 'else if' with 'if' to check all 3 values not up to one. And then edit value of sepiaRed, sepiaBlue, sepiaGreen not red, blue, green.
I'm not sure if I get right what that function suppose to do.
you have to use the math function round(), mine just working fine.
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
//gets the values of each color in the image
int red = image[i][j].rgbtRed;
int blue = image[i][j].rgbtBlue;
int green = image[i][j].rgbtGreen;
// gets the sepia value of the pixels
int sepiaRed = round(0.393 * red + 0.769 * green + 0.189 * blue) ;
int sepiaGreen = round(0.349 * red + 0.686 * green + 0.168 * blue) ;
int sepiaBlue = round(0.272 * red + 0.534 * green + 0.131 * blue) ;
if (sepiaRed >= 256)
{
sepiaRed = 255;
}
if (sepiaGreen >= 256)
{
sepiaGreen = 255;
}
if (sepiaBlue >= 256)
{
sepiaBlue= 255;
}
image[i][j].rgbtRed = sepiaRed;
image[i][j].rgbtBlue = sepiaBlue;
image[i][j].rgbtGreen = sepiaGreen;
}
}
I am trying to find the values x and y may take so the following inequalities hold:
1/24 < 1/15*y < 1/10*x < 2/24 < 2/15*y < 3/24
Is there a way to formulate such a problem in Java?
Constraint Programming would probably solve such a problem but is there an alternative way?
If Constraint Programming is the only way, how does this look like?
The following is what I tried with constraint programming using or-tools. How to formulate strict inequalities?
MPSolver solver = new MPSolver(
"SimpleMipProgram", MPSolver.OptimizationProblemType.CBC_MIXED_INTEGER_PROGRAMMING);
// [END solver]
// [START variables]
double infinity = java.lang.Double.POSITIVE_INFINITY;
// x and y are float/double variables.
MPVariable x = solver.makeNumVar(0,1,"x"); //makeIntVar(0.0, infinity, "x");
MPVariable y = solver.makeNumVar(0,1,"y"); //makeIntVar(0.0, infinity, "y");
System.out.println("Number of variables = " + solver.numVariables());
// [END variables]
// [START constraints]
// x + 7 * y <= 17.5.
/*MPConstraint c0 = solver.makeConstraint(-1, 17.5, "c0");
c0.setCoefficient(x, 1);
c0.setCoefficient(y, 7);
// x <= 3.5.
MPConstraint c1 = solver.makeConstraint(-infinity, 3.5, "c1");
c1.setCoefficient(x, 1);
c1.setCoefficient(y, 0);*/
// 1/24 < 1/15*y ---> -1/15 * y < -1/24
MPConstraint c0 = solver.makeConstraint(-1000,-1/24.0,"c0");
c0.setCoefficient(y,-1/15.0);
// 1/15*y < 1/10*x ---> 1/15*y - 1/10*x < 0
MPConstraint c1 = solver.makeConstraint(-1000,0,"c1");
c1.setCoefficient(y,1/15.0);
c1.setCoefficient(x,-1/10.0);
// 1/10*x < 2/24 ---> 1/10*x < 2/24
MPConstraint c2 = solver.makeConstraint(-1000,2/24.0,"c2");
c2.setCoefficient(x,1/10.0);
// 2/24 < 2/15*y ---> -2/15*y < -2/24
MPConstraint c3 = solver.makeConstraint(-1000, -2/24.0);
c3.setCoefficient(y,-2/15.0);
// 2/15*y < 3/24 ---> 2/15*y < 3/24
MPConstraint c4 = solver.makeConstraint(-1000,3/24.0);
c4.setCoefficient(y,2/15.0);
Here is a working code using the integer solver
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model
model = cp_model.CpModel()
scale = 1000
x = model.NewIntVar(0, scale, 'x')
y = model.NewIntVar(0, scale, 'y')
# 1/24 < 1/15*y < 1/10*x < 2/24 < 2/15*y < 3/24
model.Add(5 * scale < 8 * y)
model.Add(8 * y < 12 * x)
model.Add(12 * x < 10 * scale)
model.Add(10 * scale < 16 * y)
model.Add(16 * y < 15 * scale)
solver = cp_model.CpSolver()
solver.parameters.log_search_progress = True
status = solver.Solve(model)
if status == cp_model.FEASIBLE:
print('x =', solver.Value(x) * 1.0 / scale)
print('y =', solver.Value(y) * 1.0 / scale)
With scale = 1000, it outputs:
x = 0.418
y = 0.626
With scale = 100, it outputs:
x = 0.43
y = 0.63
With scale = 10, it outputs
x = 0.5
y = 0.7
I found the solution by writing down a loop that produces random values until all the statements are fulfilled.
Now I am interested in how wolfram alpha solves such problems so quickly.
public class inequalities {
private static double x;
private static double y;
private static double Ratio3 = 1/24.0;
private static double Ratio2 = 1/15.0;
private static double Ratio1 = 1/10.0;
public static void main(String[] args) {
x = Math.random();
y = Math.random();
boolean loop = true;
while (loop) {
loop = calculatingTheInequalities();
if (loop) {
x = Math.random();
y = Math.random();
}
}
System.out.println("x value: " + x);
System.out.println("y value: " + y);
}
public static boolean calculatingTheInequalities() {
if (Ratio3<Ratio2*y && Ratio2*y<Ratio1*x &&
Ratio1*x<2*Ratio3 && 2*Ratio3<2*Ratio2*y &&
2*Ratio2*y<3*Ratio3) {
return false;
} else {
return true;
}
/*if (Ratio3 < Ratio2 *y) {
if (Ratio2 *y < Ratio1 *x) {
if (Ratio1 *x<2* Ratio3) {
if (2* Ratio3 < 2* Ratio2 *y) {
if (2* Ratio2 *y < 3* Ratio3) {
return false;
} else {
return true;
}
} else {
return true;
}
} else {
return true;
}
} else {
return true;
}
} else {
return true;
}*/
}
}
import numpy as np n=int(input())
R = n C = n p,s=0,0
print("Enter the entries in a single line (separated by space): ")
entries = list(map(int, input().split())) matrix = np.array(entries).reshape(R, C) print(matrix) for i in range(R): for j in range(C): if i==j: p=p+matrix[i][j] if i+j==n-1: s=s+matrix[i][j] s1=p-s print(s1)
r_sum=0
l_sum=0
for i in range(len(arr)):
l_sum=l_sum+arr[i][i]
r_sum=r_sum+arr[i][(len(arr)-1)-i]
return abs(l_sum - r_sum)
#pyhton3 using array concept
Maybe this helps:
c = np.array([[1,2,3],[4,5,6],[7,8,9]])
i,j = np.indices(c.shape)
sum1 = c[i==j].sum()
sum2 = c[i+j == len(c)-1].sum()
print(abs(sum1-sum2))
function absoluteDifference(arr){
var sumDiagnoalOne=0
var sumDiagnoalTwo=0
for(var i=0; i<arr.length; i++){
for(var j=i; j<arr.length; j++){
sumDiagnoalOne+=arr[i][j]
break
}
}
var checkArray=[]
arr.map(array=>checkArray.push(array.reverse()))
for(var i=0; i<checkArray.length; i++){
for(var j=i; j<checkArray.length; j++){
sumDiagnoalTwo+=checkArray[i][j]
break
}
}
return Math.abs(sumDiagnoalOne- sumDiagnoalTwo)
}
#include
using namespace std;
int main() {
int n;
cin >> n;
int arr[n][n];
long long int d1=0; //First Diagonal
long long int d2=0; //Second Diagonal
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> arr[i][j];
if (i == j) d1 += arr[i][j];
if (i == n - j - 1) d2 += arr[i][j];
}
}
cout << abs(d1 - d2) << endl; //Absolute difference of the sums across the
diagonals
return 0;
}
#!/bin/ruby
n = gets.strip.to_i
a = Array.new(n)
(0..n-1).each do |i|
a[i] = gets.strip.split(' ').map(&:to_i)
end
d1 = 0
d2 = 0
(0..n-1).each do |i|
d1 = d1 + a[i][i]
d2 = d2 + a[-i-1][i]
end
print (d1-d2).abs
Javascript in O(n)
function diagonalDifference(arr) {
const size = arr.length;
let lsum = 0;
let rsum = 0;
for(let i = 0; i < size; i ++){
lsum += arr[i][i];
rsum += arr[i][Math.abs(size - 1 - i)];
}
return Math.abs(lsum - rsum);
}
//sample array matrix 4x4
const arr=[ [ 11, 2, 4 ,5], [ 4, 5, 6,4 ], [ 10, 8, -12,6 ],[ 10, 8, -12,6 ] ];
function findMedian(arr) {
const matrixType=arr.length
const flat=arr.flat()
let sumDiag1=0
let sumDiag2=0
for(let i=0;i<matrixType;i++)
{
sumDiag1+=flat[i*(matrixType+1)]
sumDiag2+=flat[(i+1)*(matrixType-1)]
}
const diff=Math.abs(sumDiag1-sumDiag2)
return diff
}
console.log(findMedian(arr))
I am trying to transform my C# implementation of Levenstein algorithm into Visual C++ and I am facing this error message
An unhandled exception of type 'System.IndexOutOfRangeException' occurred
The original fully working C# code is
public static int Compute(string s, string t)
{
int n = s.Length;
int m = t.Length;
int[,] d = new int[n + 1, m + 1];
// Step 1
if (n == 0)
{
return m;
}
if (m == 0)
{
return n;
}
// Step 2
for (int i = 0; i <= n; d[i, 0] = i++)
{
}
for (int j = 0; j <= m; d[0, j] = j++)
{
}
// Step 3
for (int i = 1; i <= n; i++)
{
//Step 4
for (int j = 1; j <= m; j++)
{
// Step 5
int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
// Step 6
d[i, j] = Math.Min(
Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
d[i - 1, j - 1] + cost);
}
}
// Step 7
return d[n, m];
}
Visual C++ code that produces IndexOutOfRangeException is this
int Compute(String^ s, String^ t)
{
int n = s->Length;
int m = t->Length;
array<int,2>^ d = gcnew array<int,2>(n+1 , m+1); //int[,] d = new int[n + 1, m + 1];
// Step 1
if (n == 0)
{
return m;
}
if (m == 0)
{
return n;
}
// Step 2
for (int i = 0; i <= n; d[i, 0] = i++)
{
}
for (int j = 0; j <= m; d[0, j] = j++)
{
}
// Step 3
for (int i = 1; i <= n; i++)
{
//Step 4
for (int j = 1; j <= m; j++)
{
// Step 5
int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
// Step 6
d[i, j] = Math::Min(
Math::Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
d[i - 1, j - 1] + cost);
}
}
// Step 7
return d[n, m];
}
Is there anything wrong with my array declaration in Visual C++?
This exception occurs because of accessing the index more than its limit.
e.g. limit is n and you are using n+1 th element of an array.
check the value of i and j does it exceeds or and m+1 print the values of i and j so that you can find in which iteration the value exceeds limit.
I soved it , I used vectors instead or array
my 2D array implementation was not corrected , here is the correct implementation in visual C++
int Lev(String^ s, String^ t)
{
int n = s->Length;
int m = t->Length;
vector<vector<int> > d(n+1,vector<int>(m+1));
// Step 1
if (n == 0)
{
return m;
}
if (m == 0)
{
return n;
}
// Step 2
for (int i = 0; i <= n; d[i][0] = i++)
{
}
for (int j = 0; j <= m; d[0][j] = j++)
{
}
// Step 3
for (int i = 1; i <= n; i++)
{
//Step 4
for (int j = 1; j <= m; j++)
{
// Step 5
int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
// Step 6
d[i][j] = Math::Min(
Math::Min(d[i - 1][j] + 1, d[i][j - 1] + 1),
d[i - 1][j - 1] + cost);
}
}
// Step 7
return d[n][m];
}