Repository navigation
Expand file tree
/
Copy pathRL.cs
More file actions
90 lines (80 loc) · 2.27 KB
/
Copy pathRL.cs
File metadata and controls
90 lines (80 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;
using System.IO;
public class RL : MonoBehaviour
{
public struct Transition
{
public float[] state;
public int action;
public float reward;
};
NN neuralNetwork;
public Transform[] targets;
public Image[] images;
public Text epsilonText;
float epsilon = 1;
int trainSteps = 0;
private void Start()
{
neuralNetwork = new NN(14, 10, 66);
}
public int Act(float[] state)
{
List<float> output = neuralNetwork.calcNet(state);
int maxIndex = 0;
float max = output[0], min = output[0];
for(int i = 1; i < output.Count; i++)
{
if(output[i] > max)
{
maxIndex = i;
max = output[i];
}
else if (output[i] < min)
{
min = output[i];
}
}
for (int i = 0; i < output.Count; i++)
{
float ratio = (output[i] - min) / (max - min);
images[i].color = new Color(1 - ratio, ratio, 0, 0.25f);
}
images[maxIndex].color = new Color(0, 1, 0, 0.5f);
return Random.Range(0.0f, 1.0f) >= epsilon ? maxIndex : Random.Range(0, targets.Length);
}
public void Observe(Transition newTransition)
{
neuralNetwork.Train(newTransition);
trainSteps++;
if(trainSteps % 100 == 0 && epsilon > 0.001f)
{
epsilon -= 0.01f;
epsilonText.text = "Epsilon = " + epsilon.ToString("0.00");
}
}
public void Save(StreamWriter writer)
{
writer.WriteLine(epsilon);
writer.WriteLine(trainSteps);
neuralNetwork.Save(writer);
}
public void Load(StreamReader reader)
{
try
{
epsilon = float.Parse(reader.ReadLine());
trainSteps = int.Parse(reader.ReadLine());
neuralNetwork.Load(reader);
}
catch (System.Exception e)
{
Debug.Log(e.Message);
}
if (epsilon < 0.01f)
epsilon = 0;
epsilonText.text = "Epsilon = " + epsilon.ToString("0.00");
}
}