require 'numo/narray' y = [0.1, 0.05, 0.6, 0.0, 0.05, 0.1, 0.0, 0.1, 0.0, 0.0] t = [0, 0, 1, 0, 0, 0, 0, 0, 0, 0] # 2乗和誤差 def mean_squared_error(y, t) # ニューラルネットワークの出力と教師データの各要素の差の2乗、の総和 return 0.5 * ((y-t)**2).sum end mean_squared_error(Numo::DFloat.asarray(y), Numo::DFloat.asarray(t)) y2 = [0.1, 0.05, 0.1, 0.0, 0.05, 0.1, 0.0, 0.6, 0.0, 0.0]; mean_squared_error(Numo::DFloat.asarray(y2), Numo::DFloat.asarray(t)) # 交差エントロピー誤差 def cross_entropy_error(y, t) delta = 1e-7 # マイナス無限大を発生させないように微小な値を追加する return -(t * Numo::NMath.log(y + delta)).sum end cross_entropy_error(Numo::DFloat.asarray(y), Numo::DFloat.asarray(t)) cross_entropy_error(Numo::DFloat.asarray(y2), Numo::DFloat.asarray(t)) require_relative 'dataset/mnist' x_train, t_train, x_test, t_test = MNIST.load_mnist( normalize: true, one_hot_label: true) x_train.shape t_train.shape x_batch = x_train[0...10] t_batch = t_train[0...10] [x_batch, t_batch] def cross_entropy_error(y, t) if y.ndim == 1 t = t.reshape(1, t.size) y = y.reshape(1, y.size) end delta = 1e-7 batch_size = y.shape[0] return -(t * Numo::NMath.log(y + delta)).sum / batch_size end cross_entropy_error(Numo::DFloat.asarray(y), Numo::DFloat.asarray(t)) def numerical_diff(f, x) h = 1e-4 # return (f(x+h) - f(x-h)) / (2*h) return (f.(x+h) - f.(x-h)) / (2*h) end # def function_1(x) function_1 = -> x do 0.01*x**2 + 0.1*x end numerical_diff(function_1, 5) numerical_diff(function_1, 10) def function_2(x0, x1) return x0**2 + x1**2 end function_tmp1 = -> x0 do function_2(x0, 4.0) end numerical_diff(function_tmp1, 3.0) function_tmp2 = -> x1 do function_2(3.0, x1) end numerical_diff(function_tmp2, 4.0)