this is my solution to Exercise 5 of http://work.caltech.edu/homework/hw2.pdf Please help me make this more elegant.
The exercise is about classifying random Points by a (randomly generated) target function to 2 classes (-1 and +1), build a new target function by linear Regression and compare where they don't classify to the same value.
first I generate two Random Points to build the target function
funktionsPunkte = RandomReal[{-1, 1}, {2, 2}]
then generate the target function from it (to classify the data points)
targetFct[{x1_, x2_}] :=
With[{targetFunction = LinearModelFit[funktionsPunkte, {1, t}, t]},
x2 - targetFunction[x1]];
then I generate 100 data Points and classify them to either +1 or -1 ,depending if they are above or below the target function
data = With[{points = RandomReal[{-1, 1}, {100, 2}]},
Map[{Prepend[#, 1], If[targetFct[#] < 0, -1, 1]} &, points]];
one data Point is of the form {{1,x1,x2},y} where y is either +1 or -1.
now Comes the ugly part. I Need the weight vector w = PseudoInverse[{1,x1,x2}].y
w = (PseudoInverse[#[[1]] & /@ data]).(#[[2]] & /@ data)
only {1,x1,x2} :
xlist = (#[[1]] &) /@ data;
the sign of each element w.x (-1 or 1 depending on which class we classify it)
sig = Sign /@ (w.# &) /@ xlist ;
only the y of our data Points
datasig = #[[2]] & /@ data;
now we Count the "misclassified" elements
Length[Select[
Table[sig[[i]] != datasig[[i]], {i, 100}], # == True &]]
now I Need to repeat this Experiment a 1000 times and take the mean. But how do I do that. I'm coming from an imperative Point of view and this would be trivial there.
I'm also welcoming more elegant Solutions that more use functional and mathematica specific elements.
edit:
thanks to the comments, I made this
f := Module[{}, funktionsPunkte = RandomReal[{-1, 1}, {2, 2}];
targetFct[{x1_, x2_}] :=
With[{targetFunction = LinearModelFit[funktionsPunkte, {1, t}, t]},
x2 - targetFunction[x1]];
data = With[{points = RandomReal[{-1, 1}, {100, 2}]},
Map[{Prepend[#, 1], If[targetFct[#] < 0, -1, 1]} &, points]];
w = (PseudoInverse[#[[1]] & /@ data]).(#[[2]] & /@ data);
xlist = (#[[1]] &) /@ data;
sig = Sign /@ (w.# &) /@ xlist;
datasig = #[[2]] & /@ data;
Length[Select[
Table[sig[[i]] != datasig[[i]], {i, 100}], # == True &]]]
and then
f & /@ Range[1000]
it's awfully slow but it works (have not implemented the other suggestions yet)
Module
or similar are useful for that. You can merge separate cells, but make sure you use the right amount of;
. $\endgroup$funktionsPunkte
, some Denglish there :D $\endgroup$