updating a belief distribution given a measurment - artificial-intelligence

If you are given:
a probability distribution that a robot sensor detects an object , given that it is in a location p(z|x).
prior probabilities that the robot is in any location
An actual observation made by the robots sensor
and asked to update the probability distribution given this observation, what method would one use?
I am not sure if i should be using a bayes filter, kalman filter, or if i am over thinking this problem.
as an example:
if a robot can move along a the number line from 1-7, with a standing poll at x=4. The robot can tell if the poll is to its left, right or in front of it (z=-1,1,0 respectfully).
p(z|x) x=1 x=2 x=3 x=4 x=5 x=6 x=7
z= -1 0 0 0 .25 .5 .5 .5
z = 0 ... (its an example so im leaving this off)
z = 1 ...
𝑝(𝑥 = 1) = 0.1; 𝑝(𝑥 = 2) = 0.2; 𝑝(𝑥 = 3) = 0.2; 𝑝(𝑥 = 4) = 0.2;
𝑝(𝑥 = 5) = 0.2; 𝑝(𝑥 = 6) = 0.1; 𝑝(𝑥 = 7) = 0.0
than the robot sensor outputs z=-1 . What method would i use to update the above table

i am not an expert in this but i have seen a similar kind of topic discussed in this link. i hope this mighthelp you. good luck.
http://bilgin.esme.org/BitsAndBytes/KalmanFilterforDummies

Related

Widen a fibonacci flower using a for cycle

I was wondering in this example that I've used to practice for loops, I needed to change this code in order to change the image that looks like this, some basic golden angle plot:
to this example
phi = (sqrt(5)+1)/2;% Número áureo %Golden Number
golden_angle = 2*pi/phi;
max_angle = 10000;
theta = 1:golden_angle:max_angle;% ángulo %Angle
r = sqrt(theta);% radio %Radius
[x,y] = pol2cart(theta,r);% coordenadas polares a cartesianas %Polar to cartesian
figure
plot(x,y,'.','MarkerSize',10);axis off;
I know that the number next to 'MarkerSize' wides the flower petals, but I tried changing theta values in the array but with no particular result, only I’ve changed color but not the size. I also tried making these a for cycle, that creates circles as the golden flower petals, I think, but don't know how to implement it. But how to make them more and more small at the iteration goes?, and I think total number of petals is 2575.
for i = 1:10
%plot(x,y,'.',x(i),y(i),'.','MarkerSize',10*abs(y(i)),'MarkerFaceColor','g')
You can use scatter in place of plot: scatter allows to set the marker size as a parameter:
phi = (sqrt(5)+1)/2;% Número áureo %Golden Number
golden_angle = 2*pi/phi;
max_angle = 10000;
theta = 1:golden_angle:max_angle;% ángulo %Angle
r = sqrt(theta);% radio %Radius
marker_size = 10 * r / sqrt(max_angle); % new
[x,y] = pol2cart(theta,r);% coordenadas polares a cartesianas %Polar to cartesian
figure
scatter(x,y,marker_size, 'fill'); axis off; % new: scatter
marker_size data look good on table, increasing from 0 to 10 with theta.
However, on my Matlab (R2013b), the rendering is very gross.

How to solve logistic regression using gradient Descent?

I was solving a exercise of a online course form coursera on machine learning. The problem statement is :
Suppose that a high school has a dataset representing 40 students who were admitted to college and 40 students who were not admitted. Each ( x(i), y(i) ) training example contains a student's score on two standardized exams and a label of whether the student was admitted.
Our task is to build a binary classification model that estimates college admission chances based on a student's scores on two exams. In the training data,
a. The first column of your x array represents all Test 1 scores, and the second column represents all Test 2 scores.
b. The y vector uses '1' to label a student who was admitted and '0' to label a student who was not admitted.
I have solved it by using predefined function named fminunc. Now , i am solving it by using gradient descent but my graph of cost vs number of iteration is not conversing i.e cost function value is not decreasing with number of iteration . My theta value is also not matching with the answer that should i get.
theta value that i got :
[-0.085260 0.047703 -0.022851]
theta value that i should get (answer) :
[-16.38 0.1483 0.1589]
My source code :
clear ; close all; clc
x = load('/home/utlesh/Downloads/ex4x.txt');
y = load('/home/utlesh/Downloads/ex4y.txt');
theta = [0,0,0];
alpha = 0.00002;
a = [0,0,0];
m = size(x,1);
x = [ones(m,1) x];
n = size(x,2);
y_hyp = y*ones(1,n);
for kk = 1:100000
hyposis = 1./(1 + exp(-(x*theta')));
x_hyp = hyposis*ones(1,n);
theta = theta - alpha*1/m*sum((x_hyp - y_hyp).*x);
a(kk,:) = theta ;
end
cost = [0];
for kk = 1:100000
h = 1./(1 + exp(-(x*a(kk,:)')));
cost(kk,:) = sum(-y .* log(h) - (1 - y) .* log(1 - h));
end
x_axis = [0];
for kk = 1:100000
x_axis(kk,:) = kk;
end
plot(x_axis,cost);
The graph that i got looks like that of 1/x;
Please tell me where i am doing mistake . If there is anything that i misunderstood please let me know .
What I can see missing is the usage of learning rate and weights. The weights can be adjusted in two modes online and batch.
The weights should be randomly assigned values between [-0.01,0.01]. I did an exercise as a part of my HW during my Master's. Below is the snippet:
assign values to weights between [-0.01,0.01] i.e. no. of weight values will be, no. of features + 1:
weights = -.01 + 0.02 * rand(3,1);
learnRate = 0.001;
Here running the code for set number of iterations: (It converged in 100 iterations also).
while iter < 100
old_output = new_output;
delta = zeros(cols-1,1);
for t = 1:rows
input = 0;
for j = 1:cols-1
input = input + weights(j) * numericdata(t,j);
end
new_output(t) = (1 ./ (1 + exp(-input)));
for j = 1:cols-1
delta(j) = delta(j) + (numericdata(t,4)-new_output(t)) * numericdata(t,j);
end
end
#Adjusting weights (Batch Mode):
for j=1:cols-1
weights(j) = weights(j) + learnRate * (delta(j));
end
error = abs(numericdata(:,4) - new_output);
errorStr(i) = (error(:));
error = 0;
iter = iter + 1;
i = i + 1;
end
Also, I had a talk with my professor, while studying it. He said, if the dataset given has the property to converge then you will see that when you randomly run it for different number of iterations.

Connecting random points in MATLAB without intersecting lines

I need help with solving this problem. I have randomly generated points (example on Picture #1) and I want to connect them with lines (example on Picture #2). Lines can't be intersected and after connection, the connected points should look like an irregular area.
%Generating random points
xn = randi([3 7],1,10);
yn = randi([3 6],1,10);
%Generated points
xn = [6,3,7,7,6,6,6,4,6,3];
yn = [5,3,4,3,3,6,5,4,6,3];
Picture #1:
Result should be like this:
Picture #2:
Any idea how to solve this?
I suppose for the general case it can be very difficult to come up with a solution. But, assuming your points are scattered "nicely" there is quite a simple solution.
If you sort your points according to the angle above the x axis of the vector connecting the point and the center of the point cloud then:
P = [xn;yn]; %// group the points as columns in a matrix
c = mean(P,2); %// center point relative to which you compute the angles
d = bsxfun(#minus, P, c ); %// vectors connecting the central point and the dots
th = atan2(d(2,:),d(1,:)); %// angle above x axis
[st si] = sort(th);
sP = P(:,si); %// sorting the points
And that's about it. To plot the result:
sP = [sP sP(:,1)]; %// add the first point again to close the polygon
figure;plot( sP(1,:), sP(2,:), 'x-');axis([0 10 0 10]);
This algorithm will fail if several points has the same angle w.r.t the center of the point cloud.
An example with 20 random points:
P = rand(2,50);
You could adapt the code from another answer I gave for generating random simple polygons of an arbitrary number of sides. The difference here is you already have your set of points chosen and thus implicitly the number of sides you want (i.e. the same as the number of unique points). Here's what the code would look like:
xn = [6,3,7,7,6,6,6,4,6,3]; % Sample x points
yn = [5,3,4,3,3,6,5,4,6,3]; % Sample y points
[~, index] = unique([xn.' yn.'], 'rows', 'stable'); % Get the unique pairs of points
x = xn(index).';
y = yn(index).';
numSides = numel(index);
dt = DelaunayTri(x, y);
boundaryEdges = freeBoundary(dt);
numEdges = size(boundaryEdges, 1);
while numEdges ~= numSides
if numEdges > numSides
triIndex = vertexAttachments(dt, boundaryEdges(:,1));
triIndex = triIndex(randperm(numel(triIndex)));
keep = (cellfun('size', triIndex, 2) ~= 1);
end
if (numEdges < numSides) || all(keep)
triIndex = edgeAttachments(dt, boundaryEdges);
triIndex = triIndex(randperm(numel(triIndex)));
triPoints = dt([triIndex{:}], :);
keep = all(ismember(triPoints, boundaryEdges(:,1)), 2);
end
if all(keep)
warning('Couldn''t achieve desired number of sides!');
break
end
triPoints = dt.Triangulation;
triPoints(triIndex{find(~keep, 1)}, :) = [];
dt = TriRep(triPoints, x, y);
boundaryEdges = freeBoundary(dt);
numEdges = size(boundaryEdges, 1);
end
boundaryEdges = [boundaryEdges(:,1); boundaryEdges(1,1)];
x = dt.X(boundaryEdges, 1);
y = dt.X(boundaryEdges, 2);
And here's the resulting polygon:
patch(x,y,'w');
hold on;
plot(x,y,'r*');
axis([0 10 0 10]);
Two things to note:
Some sets of points (like the ones you chose here) will not have a unique solution. Notice how my code connected the top 4 points in a slightly different way than you did.
I made use of the TriRep and DelaunayTri classes, both of which may be removed in future MATLAB releases in favor of the delaunayTriangulation class.

3d Accelerometer calculate the orientation

I have accelerometer values for the 3 axes (usually when there is only gravity contains data between -1.0 and 1.0 ):
float Rx;
float Ry;
float Rz;
I make some calculations, then I get the angles for each axis.
float R = sqrt(pow(Rx,2)+pow(Ry,2)+pow(Rz,2));
float Arx = acos(Rx/R)*180/M_PI;
float Ary = acos(Ry/R)*180/M_PI;
float Arz = acos(Rz/R)*180/M_PI;
Then I set the values for the box angles in opengl
rquad = Arx;
yquad = Ary;
Which rotates my box:
glRotatef(yquad,1.0f,0.0f,0.0f);
glRotatef(rquad,0.0f,1.0f,0.0f);
It works on a hemisphere. I would like to use the full sphere and I know that I have to use the Arz value to make it work, but I don't know how can I use that for this rotation. Could you help me?
Update:
The final answer is in my case:
rquad = -atan2(Rx/R, Rz/R)*180/M_PI;
yquad = -atan2(Ry/R, Rz/R)*180/M_PI;
The correct answer is:
Roll = atan2(Y, Z) * 180/M_PI;
Pitch = atan2(-X, sqrt(Y*Y + Z*Z)) * 180/M_PI;
Source: https://www.nxp.com/docs/en/application-note/AN3461.pdf (page 10, Eqn. 25 & 26)
uesp's answer is wrong. It looks like an acceptable approximation until pitch and roll both go above 45 degrees.
I may be assuming a different orientation convention, but even if you swap axes and invert values in any consistent way, uesp's computations will never be equivalent.
While matteo's answer is correct, it does not provide the full, complete solution:
The formulas are correct:
Roll = atan2(Y, Z) * 180/M_PI;
Pitch = atan2(-X, sqrt(Y*Y + Z*Z)) * 180/M_PI;
However, when pitch is +90/-90 degrees and the X axis is vertical pointing up/down, the ideal accelerometer normalized output should be:
accX = -1 / accX = 1
accY = 0
accZ = 0
Which means a roll angle of 0 degrees; correct.
But in practice, the accelerometer output is noisy and you would get something closer to:
accX = -1 / accX = 1
accY = 0.003
accZ = 0.004
This might seem small but it will cause the roll angle to be ~30 dregrees which is not correct.
The obvious instinct would be to filter out the last digits, but this would affect precision, which is not always acceptable.
The compromise, which is very well explained in the reference app note, is to include a very small percentage of the accelerometer X axis reading in the formula for roll:
Roll = atan2( Y, sign* sqrt(Z*Z+ miu*X*X));
sign = 1 if accZ>0, -1 otherwise
miu = 0.001
The error introduced this way is dramatically smaller than the previous case: 2-3 degrees when measuring roll under the same conditions explained above.
I've tried the recommended solution (matteo's), and while it seemed to work great at first, I noticed that when the pitch approaches 90 degrees (starting at around 70 degrees but not necessarily consistent across different phones), the roll suddenly surges. When the pitch is at 90 the roll that should be around 0 is now at over 100 and keeps increasing to 180. I'm trying to think of a way to mathematically prevent this, if I restrict the roll to +90/-90 it behaves normally but I don't get the range I want (+180/-180):
Math.atan2(y, Math.sqrt((xx) + (zz))) * (180/Math.PI))
For roll, I have found you can use arctan(y/sqrt(X*X)+(z*z)) this will give roll -90/90 which is aviation standard without giving the pitch issue
I use the following calculations to convert our accelerometer readings into roll and pitch values:
Roll = atan2( sqrt(Y*Y + X*X), Z) * 180/M_PI;
Pitch = atan2( sqrt(X*X + Z*Z), Y) * 180/M_PI;
You may need to swap the X/Y/Z values or translate the Roll/Pitch depending on how your accelerometers are defined. To use them in the display them it is a simple matter of:
glRotatef (Pitch, 0.0f, 0.0f, 1.0f);
glRotatef (Roll, 1.0f, 0.0f, 0.0f);

Calculate initial velocity to move a set distance with inertia

I want to move something a set distance. However in my system there is inertia/drag/negative accelaration. I'm using a simple calculation like this for it:
v = oldV + ((targetV - oldV) * inertia)
Applying that over a number of frames makes the movement 'ramp up' or decay, eg:
v = 10 + ((0 - 10) * 0.25) = 7.5 // velocity changes from 10 to 7.5 this frame
So I know the distance I want to travel and the acceleration, but not the initial velocity that will get me there. Maybe a better explanation is I want to know how hard to hit a billiard ball so that it stops on a certain point.
I've been looking at Equations of motion (http://en.wikipedia.org/wiki/Equations_of_motion) but can't work out what the correct one for my problem is...
Any ideas? Thanks - I am from a design not science background.
Update: Fiirhok has a solution with a fixed acceleration value; HTML+jQuery demo:
http://pastebin.com/ekDwCYvj
Is there any way to do this with a fractional value or an easing function? The benefit of that in my experience is that fixed acceleration and frame based animation sometimes overshoots the final point and needs to be forced, creating a slight snapping glitch.
This is a simple kinematics problem.
At some time t, the velocity (v) of an object under constant acceleration is described by:
v = v0 + at
Where v0 is the initial velocity and a is the acceleration. In your case, the final velocity is zero (the object is stopped) so we can solve for t:
t = -v0/a
To find the total difference traveled, we take the integral of the velocity (the first equation) over time. I haven't done an integral in years, but I'm pretty sure this one works out to:
d = v0t + 1/2 * at^2
We can substitute in the equation for t we developed ealier:
d = v0^2/a + 1/2 * v0^2 / a
And the solve for v0:
v0 = sqrt(-2ad)
Or, in a more programming-language format:
initialVelocity = sqrt( -2 * acceleration * distance );
The acceleration in this case is negative (the object is slowing down), and I'm assuming that it's constant, otherwise this gets more complicated.
If you want to use this inside a loop with a finite number of steps, you'll need to be a little careful. Each iteration of the loop represents a period of time. The object will move an amount equal to the average velocity times the length of time. A sample loop with the length of time of an iteration equal to 1 would look something like this:
position = 0;
currentVelocity = initialVelocity;
while( currentVelocity > 0 )
{
averageVelocity = currentVelocity + (acceleration / 2);
position = position + averageVelocity;
currentVelocity += acceleration;
}
If you want to move a set distance, use the following:
Distance travelled is just the integral of velocity with respect to time. You need to integrate your expression with respect to time with limits [v, 0] and this will give you an expression for distance in terms of v (initial velocity).

Resources