In [1]:
require 'ruby_brain'
require 'nyaplot'
org_stderr = $stderr
$stderr = File.open(File::NULL, "w")
org_stdout = $stdout
$stdout = File.open(File::NULL, "w")
Out[1]:
In this example, we tray to make a network which imitate a wave form.
Currently RubyBrain has shigmoid as the activation function. Output layer also can has only sigmoid. In the result, the network can only treat 0~1 outpus.
So, we prepare a function which produces values whithin 0~1 for this example.
Define X
is range $0 .. (2*\pi)$ with step $0.1$
In [2]:
X = (0..1).step(0.01).to_a
Out[2]:
Set
$(0.75 * sin(x*2*\pi) + 0.15 * cos(5*\pi – 0.023) + 1) / 2$
to Y_IDEAL
and use Y_IDEAL + (random noise)
for Y
In [3]:
Y_IDEAL = X.map {|x| (0.75 * Math.sin(x*2*Math::PI) - 0.2 * Math.cos(5*x*2*Math::PI - 0.023) + 1) / 2}
Y = [Y_IDEAL, Array.new(X.size) {rand(-0.05..0.05)}].transpose.map {|e| e.inject(:+)}
Out[3]:
Following graph shows X
, Y_IDEAL
and Y
In [4]:
plot1 = Nyaplot::Plot.new
y_ideal_line = plot1.add(:line, X, Y_IDEAL)
y_ideal_line.title('Y_IDEAL')
y_scatter = plot1.add(:scatter, X, Y)
y_scatter.title('Y')
y_scatter.color('rgb(43,140,190)')
plot1.legend(true)
plot1.show
Use this X
for input and Y
for output for the training of the network.
The structure of the network is [1, 13, 6, 1]
.
In [5]:
a_network = RubyBrain::Network.new([1, 13, 6, 1])
a_network.init_network
a_network.learning_rate = 0.5
a_network.learn(X.map{|e| [e]}, Y.map{|e| [e]}, max_tra2ining_count=40000, tolerance=0.0004, monitoring_channels=[:best_params_training])
Out[5]:
You can review the trained network a_network
with following code.
Y_PREDICATED
is the output corresponding to X
In [6]:
Y_PREDICATE = X.map{|e| [e]}.map {|a| a_network.get_forward_outputs(a).first}
Out[6]:
The following graph shows X
, Y_IDEAL
, Y
and Y_PREDICATED
.
Looks good.
In [7]:
plot1 = Nyaplot::Plot.new
ideal_line = plot1.add(:line, X, Y_IDEAL)
ideal_line.title('Y_IDEAL')
training_scatter = plot1.add(:scatter, X, Y)
training_scatter.title('Y')
training_scatter.color('rgb(43,140,190)')
predicated_line = plot1.add(:line, X, Y_PREDICATE)
predicated_line.title("Y_PREDICATED")
predicated_line.color('#f85')
plot1.legend(true)
plot1.show