質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Keras

Kerasは、TheanoやTensorFlow/CNTK対応のラッパーライブラリです。DeepLearningの数学的部分を短いコードでネットワークとして表現することが可能。DeepLearningの最新手法を迅速に試すことができます。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

12812閲覧

kerasで自作損失関数を実装したい

guppi-

総合スコア13

Keras

Kerasは、TheanoやTensorFlow/CNTK対応のラッパーライブラリです。DeepLearningの数学的部分を短いコードでネットワークとして表現することが可能。DeepLearningの最新手法を迅速に試すことができます。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

1グッド

2クリップ

投稿2019/04/20 11:35

編集2019/04/20 11:40

前提・実現したいこと

自作の損失関数でkerasによる機械学習を行いたいです。
まず行いたい機械学習について、22次元の数値から、2次元の数値を予測する回帰モデルです。
そして損失関数の内容については、出力の一つ目をA,二つ目をBとしたとき、A+B/nという式を考え、nの範囲243から600までの和
Σ(A+B/n)〔243..600〕
について、正解ラベルと予測結果の平均二乗誤差を出すというものです。

発生している問題・エラーメッセージ

損失関数を作成し、C:\Users(ユーザー名)\Anaconda3\Lib\site-packages\kerasに存在する、losses.pyのファイルに、自作の損失関数originallossを入力し、動くかどうかを確認しようとしたのですが、originallossという損失関数は存在しないというエラーが返ってきました。どのようにすればoriginallossが認識されるようになるのか知りたいです。

--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-62-e841daab48c1> in <module> 64 model.add(Dense(2)) 65 model.compile(loss='oriloss', ---> 66 optimizer='adam') 67 68 hist1 = model.fit(X_data_std, y_data_std, batch_size=69, epochs=8249, verbose=1) ~\Anaconda3\lib\site-packages\keras\engine\training.py in compile(self, optimizer, loss, metrics, loss_weights, sample_weight_mode, weighted_metrics, target_tensors, **kwargs) 137 loss_functions = [losses.get(l) for l in loss] 138 else: --> 139 loss_function = losses.get(loss) 140 loss_functions = [loss_function for _ in range(len(self.outputs))] 141 self.loss_functions = loss_functions ~\Anaconda3\lib\site-packages\keras\losses.py in get(identifier) 131 # Arguments 132 identifier: None or str, name of the function. --> 133 134 # Returns 135 The loss function or None if `identifier` is None. ~\Anaconda3\lib\site-packages\keras\losses.py in deserialize(name, custom_objects) 112 msle = MSLE = mean_squared_logarithmic_error 113 kld = KLD = kullback_leibler_divergence --> 114 cosine = cosine_proximity 115 116 ~\Anaconda3\lib\site-packages\keras\utils\generic_utils.py in deserialize_keras_object(identifier, module_objects, custom_objects, printable_module_name) 163 if fn is None: 164 raise ValueError('Unknown ' + printable_module_name + --> 165 ':' + function_name) 166 return fn 167 else: ValueError: Unknown loss function:oriloss

該当のソースコード

学習用のコード

python

1# -*- coding: utf_8 -*- 2import os 3import time 4import numpy as np 5np.set_printoptions(threshold=np.inf) 6from sklearn.preprocessing import StandardScaler # 標準化の計算 7from keras.models import Sequential 8from keras.layers import Dense, Activation 9 10 11 12 13# ---------標準化準備----------------------- 14x_stdsc = StandardScaler() 15y_stdsc = StandardScaler() 16 17 18# ---------重み保存-------------------------- 19result_dir = 'result' 20if not os.path.exists(result_dir): 21 os.mkdir(result_dir) 22 23 24# ------------CSV読み込み-------------------- 25data = np.loadtxt("train0.csv",delimiter=",") 26# test1 = np.loadtxt("train100.csv",delimiter=",") 27 28 29 30# ---------------xとyを割り当て----------------- 31X_data = data[:,:22] 32# y_data = data[:,[21,22]] 33y_data = data[:,22:] 34# X_test1 = test1[:,:6] 35# y_test1 = test1[:,[10, 11, 16]] 36 37 38# -----------------標準化------------------- 39# print(y_test) 40X_data_std = x_stdsc.fit_transform(X_data) 41# X_test_std1 = x_stdsc.transform(X_test1) 42 43 44y_data_std = y_stdsc.fit_transform(y_data) 45# y_test_std1 = y_stdsc.transform(y_test1) 46 47 48# ---------------モデルkeras------------------- 49 50model = Sequential() 51 52model.add(Dense(32, input_dim=22, init='uniform')) 53model.add(Activation('sigmoid')) 54model.add(Dense(213)) 55model.add(Activation('sigmoid')) 56model.add(Dense(2)) 57model.compile(loss='originalloss', 58 optimizer='adam') 59 60hist1 = model.fit(X_data_std, y_data_std, batch_size=69, epochs=8249, verbose=1) 61 62# -------------------save model------------------- 63json_string = model.to_json() 64open(os.path.join(result_dir, 'model.json'), 'w').write(json_string) 65# -------------------save weights---------------------- 66model.save_weights(os.path.join(result_dir, 'weights.h5'))

実装しようとしている損失関数

python

1def originalloss(y_true,y_pred): 2 def f(n): 3 return y_pred[:,0]+y_pred[:,1]/n 4 def g(n): 5 return y_true[:,0]+y_true[:,1]/n 6 def sigma(func, frm, to): 7 result = 0; #答えの受け皿 8 for i in range(frm, to): 9 result += func(i) 10 return result 11 return K.mean(K.square(sigma(f, 273,601 )-sigma(g, 273,601), axis=-1) #22 12

現在のlosses.pyの中身

python

1"""Built-in loss functions. 2""" 3from __future__ import absolute_import 4from __future__ import division 5from __future__ import print_function 6 7import six 8from . import backend as K 9from .utils.generic_utils import deserialize_keras_object 10from .utils.generic_utils import serialize_keras_object 11 12def originalloss(y_true,y_pred): 13 def f(n): 14 return y_pred[:,0]+y_pred[:,1]/n 15 def g(n): 16 return y_true[:,0]+y_true[:,1]/n 17 def sigma(func, frm, to): 18 result = 0; #答えの受け皿 19 for i in range(frm, to): 20 result += func(i) 21 return result 22 return K.mean(K.square(sigma(f, 273,601 )-sigma(g, 273,601), axis=-1) #22 23 24def mean_squared_error(y_true, y_pred): 25 return K.mean(K.square(y_pred - y_true), axis=-1) 26 27 28def mean_absolute_error(y_true, y_pred): 29 return K.mean(K.abs(y_pred - y_true), axis=-1) 30 31 32def mean_absolute_percentage_error(y_true, y_pred): 33 diff = K.abs((y_true - y_pred) / K.clip(K.abs(y_true), 34 K.epsilon(), 35 None)) 36 return 100. * K.mean(diff, axis=-1) 37 38 39def mean_squared_logarithmic_error(y_true, y_pred): 40 first_log = K.log(K.clip(y_pred, K.epsilon(), None) + 1.) 41 second_log = K.log(K.clip(y_true, K.epsilon(), None) + 1.) 42 return K.mean(K.square(first_log - second_log), axis=-1) 43 44 45def squared_hinge(y_true, y_pred): 46 return K.mean(K.square(K.maximum(1. - y_true * y_pred, 0.)), axis=-1) 47 48 49def hinge(y_true, y_pred): 50 return K.mean(K.maximum(1. - y_true * y_pred, 0.), axis=-1) 51 52 53def categorical_hinge(y_true, y_pred): 54 pos = K.sum(y_true * y_pred, axis=-1) 55 neg = K.max((1. - y_true) * y_pred, axis=-1) 56 return K.maximum(0., neg - pos + 1.) 57 58 59def logcosh(y_true, y_pred): 60 """Logarithm of the hyperbolic cosine of the prediction error. 61 62 `log(cosh(x))` is approximately equal to `(x ** 2) / 2` for small `x` and 63 to `abs(x) - log(2)` for large `x`. This means that 'logcosh' works mostly 64 like the mean squared error, but will not be so strongly affected by the 65 occasional wildly incorrect prediction. 66 67 # Arguments 68 y_true: tensor of true targets. 69 y_pred: tensor of predicted targets. 70 71 # Returns 72 Tensor with one scalar loss entry per sample. 73 """ 74 def _logcosh(x): 75 return x + K.softplus(-2. * x) - K.log(2.) 76 return K.mean(_logcosh(y_pred - y_true), axis=-1) 77 78 79def categorical_crossentropy(y_true, y_pred): 80 return K.categorical_crossentropy(y_true, y_pred) 81 82 83def sparse_categorical_crossentropy(y_true, y_pred): 84 return K.sparse_categorical_crossentropy(y_true, y_pred) 85 86 87def binary_crossentropy(y_true, y_pred): 88 return K.mean(K.binary_crossentropy(y_true, y_pred), axis=-1) 89 90 91def kullback_leibler_divergence(y_true, y_pred): 92 y_true = K.clip(y_true, K.epsilon(), 1) 93 y_pred = K.clip(y_pred, K.epsilon(), 1) 94 return K.sum(y_true * K.log(y_true / y_pred), axis=-1) 95 96 97def poisson(y_true, y_pred): 98 return K.mean(y_pred - y_true * K.log(y_pred + K.epsilon()), axis=-1) 99 100 101def cosine_proximity(y_true, y_pred): 102 y_true = K.l2_normalize(y_true, axis=-1) 103 y_pred = K.l2_normalize(y_pred, axis=-1) 104 return -K.sum(y_true * y_pred, axis=-1) 105 106 107# Aliases. 108oriloss = originalloss 109mse = MSE = mean_squared_error 110mae = MAE = mean_absolute_error 111mape = MAPE = mean_absolute_percentage_error 112msle = MSLE = mean_squared_logarithmic_error 113kld = KLD = kullback_leibler_divergence 114cosine = cosine_proximity 115 116 117def serialize(loss): 118 return serialize_keras_object(loss) 119 120 121def deserialize(name, custom_objects=None): 122 return deserialize_keras_object(name, 123 module_objects=globals(), 124 custom_objects=custom_objects, 125 printable_module_name='loss function') 126 127 128def get(identifier): 129 """Get the `identifier` loss function. 130 131 # Arguments 132 identifier: None or str, name of the function. 133 134 # Returns 135 The loss function or None if `identifier` is None. 136 137 # Raises 138 ValueError if unknown identifier. 139 """ 140 if identifier is None: 141 return None 142 if isinstance(identifier, six.string_types): 143 identifier = str(identifier) 144 return deserialize(identifier) 145 if isinstance(identifier, dict): 146 return deserialize(identifier) 147 elif callable(identifier): 148 return identifier 149 else: 150 raise ValueError('Could not interpret ' 151 'loss function identifier:', identifier) 152

試したこと

mse = MSE = mean_squared_errorみたいな名前の定義が必要なのかと思いoriloss = originallossとも書いてloss=orilossともしたのですが、うまくいきませんでした。

menimani👍を押しています

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

まず、losses.pyを含め、Kerasのソースコードを勝手に書き換えるのはよくありません
今回はlosses.pyをいじる必要は全くありませんし、これが原因でバグが起こったりしたら大変です。
自分でつくったコードに追記するか、新しくpyファイルを作成してください。

Python

1model.compile(loss='originalloss', 2 optimizer='adam')

上記ですが、'originalloss'はただの文字列なので、その文字列に対応している関数が無ければエラーになります。

よって、以下のいずれかの方法を取る必要があります。

  • model.compileのlossに関数そのものを指定する

Python

1model.compile(loss=originalloss, 2 optimizer='adam')
  • CustomObjectScopeを使う

Python

1from keras.utils import CustomObjectScope 2 3# …(中略) 4 5with CustomObjectScope({'originalloss': originalloss}): 6 model = Sequential() 7 8 model.add(Dense(32, input_dim=22, init='uniform')) 9 model.add(Activation('sigmoid')) 10 model.add(Dense(213)) 11 model.add(Activation('sigmoid')) 12 model.add(Dense(2)) 13 model.compile(loss='originalloss', 14 optimizer='adam')

投稿2019/04/20 11:51

編集2019/04/20 11:52
fiveHundred

総合スコア9805

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guppi-

2019/04/21 11:13

ありがとうございます。 無事に動きました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問