java simple neural network setup - java

I have decided to play around with some simple concepts involving neural networks in Java, and in adapting somewhat useless code I found on a forum, I have been able to create a very simple model for the typical beginner's XOR simulation:
public class MainApp {
public static void main (String [] args) {
Neuron xor = new Neuron(0.5f);
Neuron left = new Neuron(1.5f);
Neuron right = new Neuron(0.5f);
left.setWeight(-1.0f);
right.setWeight(1.0f);
xor.connect(left, right);
for (String val : args) {
Neuron op = new Neuron(0.0f);
op.setWeight(Boolean.parseBoolean(val));
left.connect(op);
right.connect(op);
}
xor.fire();
System.out.println("Result: " + xor.isFired());
}
}
public class Neuron {
private ArrayList inputs;
private float weight;
private float threshhold;
private boolean fired;
public Neuron (float t) {
threshhold = t;
fired = false;
inputs = new ArrayList();
}
public void connect (Neuron ... ns) {
for (Neuron n : ns) inputs.add(n);
}
public void setWeight (float newWeight) {
weight = newWeight;
}
public void setWeight (boolean newWeight) {
weight = newWeight ? 1.0f : 0.0f;
}
public float getWeight () {
return weight;
}
public float fire () {
if (inputs.size() > 0) {
float totalWeight = 0.0f;
for (Neuron n : inputs) {
n.fire();
totalWeight += (n.isFired()) ? n.getWeight() : 0.0f;
}
fired = totalWeight > threshhold;
return totalWeight;
}
else if (weight != 0.0f) {
fired = weight > threshhold;
return weight;
}
else {
return 0.0f;
}
}
public boolean isFired () {
return fired;
}
}
In my main class, I've created the simple simulation in modeling Jeff Heaton's diagram:
However, I wanted to ensure my implementation for the Neuron class is correct..I've already tested all possible inputs ( [true true], [true false], [false true], [false false]), and they all passed my manual verification. Additionally, since this program accepts the inputs as arguments, it also seems to pass manual verification for inputs such as [true false false], [true true false], etc..
But conceptually speaking, would this implementation be correct? Or how can I improve upon it before I start further development and research into this topic?
Thank you!

It looks like a good starting point. I do have a few suggestions:
For scalability, fire() should be restructured so that a neuron that's already fired with the current input set doesn't have to recalculate each time. This would be the case if you had another hidden layer, or more than one output node.
Consider splitting your threshold calc into its own method. Then you can subclass Neuron and use different types of activation functions (bipolar sigmoid, RBF, linear, etc).
To learn more complex functions, add a bias input to each neuron. It's basically like another input with it's own weight value, but the input is always fixed at 1 (or -1).
Don't forget to allow for training methods. Backpropagation will need something like the inverse of fire(), to take a target output and ripple the weight changes through each layer.

From the (limited) work I've done with neural nets, that implementation and model looks correct to me - the output is what I'd expect and the source looks solid.

Related

How to convert two ints (swings, hits) to accuracy

How would I convert swings and hits to accuracy? I know how to calculate the swing/hit ratio but I don't know how to convert it to accuracy.
This is what I've tried:
public double convertToMeleeAccuracy(int swings, int hits) {
try {
double classicHitAccuracy = Double.valueOf(swings - hits); //I know the math for getting the ratio is swings / hits but i don't know how to calculate accuracy.
if (classicwlr < 0) {
return 0.0;
}
return classicwlr;
} catch (ArithmeticException e) {
return 0.0;
}
}
I'm going to try to explain this to you in a way that helped me calculate percentages easily throughout my life.
Let's look at this like so:
Say swings is always 10, so in this scenario, each swing is worth 10% of the accuracy. (because the max accuracy will always be 100%) In that case the function will look something like this:
public class Main {
public static void main(String[] args) {
System.out.println(convertToMeleeAccuracy(3)); // Can be any number you'd like under 10.
}
public static double convertToMeleeAccuracy(int hits) {
int swings = 10;
double percentage = 100.0 / swings;
return hits * percentage;
}
}
In this scenario, the program will output 30.0 which means 30% of the hits have hit.
In the scenario above I only used the number 10 because it's an easy number to work with, here's an example of how this would work with any number of swings:
public class Main {
public static void main(String[] args) {
System.out.println(convertToMeleeAccuracy(22, 21)); // Can be any numbers you'd like.
}
public static double convertToMeleeAccuracy(int swings, int hits) {
double percentage = 100.0 / swings;
return hits * percentage;
}
}
In this scenario, the function will output 95.45454545454547 which is the correct accuracy and you can use any numbers you'd like.
You can also add some checks in the function to make sure hits isn't higher than swings etc..
I hope I helped you understand!

Creating a Vehicle Program

Right now I'm doing some tasks from a java e-book that I've acquired, and unfortunately, I'm stuck. The main thought of this program is to create a Vehicle class, which along with a test program can increase, decrease and break the current speed.
The starting speed should be 0. I want the user to specify what speed the car should drive to (for an example 90 km/h). After hitting the speed(90 in this case) I want the program to ask the user if he wants to decrease the speed to a given value, stay at the same speed, or break to 0. Should all of this be done in the testprogram, or should it be implemented into the Vehicle class?
I'm supposed to create a program from the following UML: https://i.stack.imgur.com/01fgM.png
This is my code so far:
public class Vehicle {
int speed;
//Constructor
public Vehicle () {
this.speed = 0;
}
public void increaseSpeed (int differenceInc) {
this.speed += differenceInc;
}
public void decreaseSpeed (int differenceDec) {
this.speed -= differenceDec;
}
public void brake() {
}
public int getSpeed () {
return this.speed;
}
}
And this is my empty test class.
public class VehicleTest {
public static void main(String[] args) {
Vehicle golf = new Vehicle();
//Speed which should be accelerated to:
Vehicle myHybrid = new Vehicle();
System.out.println("You've hit the given speed. Do you want to stay at this speed, break, or decrease to another given speed?");
}
}
Well , first of all, welcome to Stack Overflow.
If you want a method to accept arguments (parameters) then you must declare said arguments and the arguments' types in the mehtod declaration:
public void increaseSpeed (int augmentValue) {
this.speed += augmentValue;
}
You're also asking about software design: "should the component (Vehicle) user or client be able to set the augment value of the increaseSpeed mehtod?" . The answer relies on the design of said component. If your method will accept an argument then perhaps the method should also validate the input value and establish pre and post conditions.
Hope this helps.
Probably the idea is to take an int for increaseSpeed(), so that you can increase the speed by that given integer. Also add the logic for hitting the speed limit in your increaseSpeed method.
So...
public void increaseSpeed (int amount) {
if (speed + amount < MAX_SPEED) { // Where MAX_SPEED is a static final int of value 90
this.speed += amount;
} else {
System.out.println("Max speed reached. Want to exceed (y/n)?");
Scanner scanner = new Scanner(System.in);
char c = scanner.next().charAt(0);
if (c == 'y') {
this.speed += amount;
}
}
}
You can do the same for decreaseSpeed(), of course. Don't forget to check if decreasing the speed doesn't result in a negative speed (unless, you consider a negative value of speed to be driving in reverse.
By the way, here I have hard-coded MAX_SPEED for simplicity. This is, of course, dependent on the road you are driving, so it is probably better to do this differently (e.g., a Road class that includes the particular attributes of a given road, or by passing both an integer for the amount you want to speedup with and an integer for the maximum speed).

Java - How shorten if statements using lambda expressions?

First of all, I'm aware that there is a similar questions like this. The answer to that question, however, did not help me.
I have the following code:
boolean result = fields[x][y + 1].getRing().getPlayer() == player || fields[x][y - 1].getRing().getPlayer() == player || fields[x + 1][y].getRing().getPlayer() == player || fields[x - 1][y].getRing().getPlayer() == player
The code is supposed to check if there are any rings of the current player above, under or next to the current field.
I'm trying to make this code more readable by using a lambda expression, but I can't get it right. I'm not sure whether this is even possible, though.
I tried to replace fields[x][y] by a variable field and then have field become fields[x][y+1], fields[x][y-1], fields[x+1][y], fields[x-1][y]
boolean result = field.getRing().getPlayer() == player -> field = {fields[x][y+1], fields[x][y-1], fields[x+1][y], fields[x-1][y]};
But this gives me a syntax error, which I expected, since field = {fields[x][y+1], fields[x][y-1], fields[x+1][y], fields[x-1][y]}; sets field to an array, and does not iterate over that array.
Is there any way I can make this code shorter using lambda expression?
You keep repeating the same condition, on 4 different values. So what you want in fact is to avoid this repetition, and write the condition once. And you want to test if any of the 4 values match the condition. So start by storing the 4 values in a collection:
List<Field> neighbors = Arrays.asList(fields[x + 1][y],
fields[x - 1][y],
fields[x][y + 1],
fields[x][y - 1]);
Then test if any of those values match the condition:
boolean result = neighbors.stream().anyMatch(field -> field.getRing().getPlayer() == player);
This doesn't necessarily make the code faster or shorter, but it makes it more readable, and DRY.
I don't think lambdas will help here. What I think is better is just to introduce some methods so that the code is more readable.
For example, you could make four methods ringAbove, ringBelow, ringRight and ringLeft and that would make the code a little more readable.
boolean result = ringAbove(x,y) || ringBelow(x,y) || ringRight(x,y) || ringLeft(x,y);
Now just implement each method, with a bit of refactoring:
private boolean ringAbove( int x, int y ) {
return ringAt( x+1, y);
}
The other three methods can be implemented similarly.
I don't really understand this code, but lets just assume it works. player will need to be available as a global variable, or you'll need to also pass it as a parameter.
private boolean ringAt( int x, int y ) {
if( x < 0 || y < 0 || x >= fields.length || y >= fields[x].length )
return false;
return fields[x][y].getRing().getPlayer() == player;
}
Here is another "tiny embedded domain specific language" for
dealing with positions and fields. It makes use of Java8 Streams and lambdas.
The method neighborhood
abstracts the idea of the shape of a discrete geometric neighborhood, so
that is becomes very easy to deal with all kind of neighborhoods on the
grid, for example with something like this:
# ### # #
#x# #x# # #
# ### x
# #
# #
You wanted the first case, but in the code below, it would be very easy to
replace the concept of "neighborhood" by the 8-cell neighborhood (second case), or by something even weirder, like for example the allowed moves of a knight in chess (third case).
The method neighboringFields makes use of the stream of the purely geometric positions, performs some additional checks on it (to ensure that you don't leave the game universe), and then enumerates all the fields with their content.
You can then use these streams of fields to quickly check various predicates on them, for example using the allMatch and anyMatch methods, as is shown in the very last method checkRingsInNeighborhood,
so that the unwieldy if-expression collapses to just this:
return neighboringFields(pos).anyMatch(
field -> field.getRing().getPlayer() == player
);
Here is the full code snippet:
import java.util.function.*;
import java.util.stream.*;
class NeighborPositions {
// Mock up implementations of `Ring`, `Player`, and `Position`,
// whatever those things are
public static class Ring {
private Player player;
public Ring(Player player) {
this.player = player;
}
public Player getPlayer() {
return this.player;
}
}
public static class Player {
private final String name;
public Player(String name) {
this.name = name;
}
}
public static class Field {
private final Ring ring;
public Field(Ring ring) {
this.ring = ring;
}
public Ring getRing() {
return this.ring;
}
}
// you probably want to fill it somehow...
public static int DIM_X = 100;
public static int DIM_Y = 42;
public static Field[][] fields = null;
/** Position on a rectangular grid */
public static class Position {
final int x;
final int y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
}
/** Shortcut for accessing fields at a given position */
public static Field field(Position p) {
return fields[p.x][p.y];
}
/** Generates stream of neighboring positions */
public static Stream<Position> neighborhood(Position pos) {
return Stream.of(
new Position(pos.x + 1, pos.y),
new Position(pos.x - 1, pos.y),
new Position(pos.x, pos.y + 1),
new Position(pos.x, pos.y - 1)
);
}
/** Generates stream of neighboring fields */
public static Stream<Field> neighboringFields(Position pos) {
return neighborhood(pos).
filter(p -> p.x >= 0 && p.x < DIM_X && p.y >= 0 && p.y < DIM_Y).
map(p -> field(p));
}
/** This is the piece of code that you've tried to implement */
public static boolean checkRingsInNeighborhood(Position pos, Player player) {
return neighboringFields(pos).anyMatch(
field -> field.getRing().getPlayer() == player
);
}
}
You obviously shouldn't try to cram everything into a single file and declare it public static, it's just an example.
You could create a BiFunction<Integer, Integer, Player> that, given x and y coordinates, returns a Player:
BiFunction<Integer, Integer, Player> fun = (coordX, coordY) ->
fields[coordX][coordY].getRing().getPlayer();
Now, to check whether a given player's ring is above, under or next to a given pair of coordinates, you could use:
boolean result = List.of(
fun.apply(x, y - 1),
fun.apply(x, y + 1),
fun.apply(x - 1, y),
fun.apply(x + 1, y))
.contains(player);
This uses Java 9's List.of. If you are not in Java 9 yet, just use Arrays.asList.
Besides, it also uses the List.contains method, which checks if a given object belongs to the list by means of the Objects.equals method, which in turn uses the equals method (taking care of nulls). If Player doesn't override equals, then identity equality == will be used as a fallback.

Finding all complex roots of cubic function by using Newton's Method in Java

I've looked everywhere for code I can understand which could help me on my way. I've found one but I'm struggling, so I hope someone could help me.
This is what I want to achieve:
Solve a cubic function (ax^3+bx^2+cx+d) where a,b,c and d are filled
in by the command line when you run it.
I need the roots and complex roots to be found using the Newton's Method. The code I'm struggling with is this, but I don't know if this works and I don't know how I can calculate all 3 roots (even knowing if it has multiplicity 1, 2 or 3).
Any help is appreciated.
import java.util.function.Function;
public class Newton {
static double a = Polynom.geta(); // these are to get the input from the class you run from calling this class to solve the roots
static double b = Polynom.getb();
static double c = Polynom.getc();
static double d = Polynom.getd();
public static void main(String args[]) {
}
private Complex[] sqrt(double x, double y) {
Complex com = new Complex(x,y); // Complex is my class that deals with Complexnumbers, com is supposed to get the value of the root in the end
double tolerance = 1e-11; // tolerance for the error
int iterations = 1, max = 512;
Complex aa = com.pow(3).multiply(a); // These put in the values from input to complex values and fill in the cubic function of ax^3+bx^2+cx+d
Complex bb = com.pow(2).multiply(b);
Complex cc = com.multiply(c);
Complex dd = com.pow(2).multiply(a).multiply(3.0);
Complex ee = com.multiply(2.0).add(com);
Complex function = aa.add(bb).add(cc).add(d,0);
Complex derivative = dd.add(ee);
for(int k = 0; k<3; k++) {
while(iterations<max) {
Complex difference = function.divide(derivative); //difference=fx/dx
com = com.subtract(difference);
if (Math.abs(difference.getReal()) < tolerance && Math.abs(difference.getImaginary()) < tolerance)
return com; // this is where i get an error atm "Cannot convert from Complex to Complex
iterations++;
}
}
}

Simulating archers hitting a target monte carlo method

3 archers are shooting at a target with probabilities p1, p2, p3. With a Monte Carlo simulation I am supposed to find an approximation of the probabilities of the following events:
randomly chosen archer hits the target // already solved
the target will be hit if all three shoot at it with a single bullet. // no idea how to approach
This is the first problem of this type that I am approaching. I can solve it easily using probabilities formulas, but I have no idea how to approach the problem using a simulation.
I would do something like this:
public class Archer {
private Random random = new Random();
public final double chance;
public Archer(double chance) {
this.chance = chance;
}
public boolean shoot() {
return random.nextDouble() < chance;
}
}
// ...
public boolean sample_problem2() {
for (Archer archer : archers) {
if (archer.shoot()) return true;
}
return false;
}
public double estimate_sample2(long count) {
long positive = 0;
for (long i = 0; i < count; i++) {
if (sample_problem2()) positive++;
}
return (double)positive / (double)count;
}
Here, the archer objects shoot method will return true or false with their respective probabilities. sample_problem2 will simulate an event you need. The latter method will take count samples, and will estimate the probability of the simulated event.
If you have some example code, we can help you develop a solution which fits better to what you already have.

Categories

Resources