下記のコードで OptimizerV2
を Optimizer
に変えたところOptimizerの初期化時にエラーが出るようになってしまいました。
コードは自分が書いたものではなく、自分の知識も不足しているためよく理解できていないです。
エラーメッセージ:
ValueError: Argument learning_rate should be float, or an instance of LearningRateSchedule, or a callable (that takes in the current iteration value and returns the corresponding learning rate value). Received instead: learning_rate=MultiOptimizerV3
目的
他の部分ではtensorflow.kerasを使用しており、ここでtensorflow.python.kerasを使うと以下のようなエラーが出るためライブラリのインポート元をそろえようとしている
ValueError: Could not interpret optimizer identifier: <__main__.MultiOptimizerV3 object at 0x00000163F5AFB860>
インスタンス作成側のコード
multiOpt = MultiOptimizerV3(belief=True, learning_rate=0.001,momentum=0.9,rho=0.999)
実行したコード(https://qiita.com/T-STAR/items/08ff024512ce56958ddc)
from tensorflow.python.keras.optimizer_v2.optimizer_v2 import OptimizerV2
from tensorflow.keras.optimizers import Optimizer #追加部分
from tensorflow.python.keras import backend_config
class MultiOptimizerV3(Optimizer): #ここをOptimizerV2からOptimizerへ変更しました
def __init__(self, learning_rate=0.01, momentum=0.0, centered=True, rho=0.0, centered_v=True, epsilon=1e-7, belief=False, name='MultiOptimizerV3', **kwargs):
super().__init__(name, **kwargs)
self._set_hyper('learning_rate', kwargs.get('lr', learning_rate))
self._set_hyper('decay', self._initial_decay)
self.momentum = momentum
self.centered = centered if momentum!=0.0 else False
self.rho = rho
self.centered_v = centered_v if rho!=0.0 else False
self.epsilon = epsilon or backend_config.epsilon()
self.belief = belief if rho!=0.0 and momentum!=0.0 else False
def get_config(self):
config = super(MultiOptimizerV3, self).get_config()
config.update({
'learning_rate': self._serialize_hyperparameter('learning_rate'),
'decay': self._serialize_hyperparameter('decay'),
'momentum': self.momentum,
'centered': self.centered,
'rho': self.rho,
'centered_v': self.centered_v,
'epsilon': self.epsilon,
'belief': self.belief,
})
return config
def _create_slots(self, var_list):
for var in var_list:
if self.momentum!=0.0:
self.add_slot(var, 'm')
if self.rho!=0.0:
self.add_slot(var, 'v')
def _resource_apply_dense(self, grad, var, apply_state=None):
var_device, var_dtype = var.device, var.dtype.base_dtype
lr_t = self._decayed_lr(var_dtype)
local_step = tf.cast(self.iterations+1, var_dtype)
updates = []
if self.momentum!=0.0:
# MomentumSGD
m = self.get_slot(var, 'm')
m_t = m.assign( self.momentum*m + (1.0-self.momentum)*grad )
if self.centered:
denominator = 1.0-(self.momentum**local_step)
m_t_hat = m_t / denominator
else:
m_t_hat = m_t
updates.append(m_t)
else:
m_t_hat = grad
if self.rho!=0.0:
#RMSprop
if self.belief: # AdaBelief
g2 = (grad-m_t)**2
epsilon_b = self.epsilon
else:
g2 = grad**2
epsilon_b = 0.0
v = self.get_slot(var, 'v')
v_t = v.assign( self.rho*v + (1.0-self.rho)*g2 )
if self.centered_v:
denominator = 1.0-(self.rho**local_step)
lr_t = lr_t / ((((v_t+epsilon_b)/denominator)**0.5)+self.epsilon)
else:
lr_t = lr_t / ((v_t**0.5)+self.epsilon)
updates.append(v_t)
# Update var
var_update = var.assign(var - lr_t*m_t_hat)
updates.append(var_update)
return tf.group(*updates)
def _resource_apply_sparse(self, grad, var, indices):
raise NotImplementedError("not implemented")
追記:
エラーメッセージ全文はこれです。
ValueError Traceback (most recent call last)
Cell In[59], line 83
81 def _resource_apply_sparse(self, grad, var, indices):
82 raise NotImplementedError("not implemented")
---> 83 multiOpt = MultiOptimizerV3(belief=True, learning_rate=0.001,momentum=0.9,rho=0.999)
Cell In[59], line 6, in MultiOptimizerV3.__init__(self, learning_rate, momentum, centered, rho, centered_v, epsilon, belief, name, **kwargs)
5 def __init__(self, learning_rate=0.01, momentum=0.0, centered=True, rho=0.0, centered_v=True, epsilon=1e-7, belief=False, name='MultiOptimizerV3', **kwargs):
----> 6 super().__init__(name, **kwargs)
7 self._set_hyper('learning_rate', kwargs.get('lr', learning_rate))
8 self._set_hyper('decay', self._initial_decay)
File ~\anaconda3\Lib\site-packages\keras\src\backend\tensorflow\optimizer.py:22, in TFOptimizer.__init__(self, *args, **kwargs)
21 def __init__(self, *args, **kwargs):
---> 22 super().__init__(*args, **kwargs)
23 self._distribution_strategy = tf.distribute.get_strategy()
File ~\anaconda3\Lib\site-packages\keras\src\optimizers\base_optimizer.py:124, in BaseOptimizer.__init__(self, learning_rate, weight_decay, clipnorm, clipvalue, global_clipnorm, use_ema, ema_momentum, ema_overwrite_frequency, loss_scale_factor, gradient_accumulation_steps, name, **kwargs)
122 else:
123 if not isinstance(learning_rate, float):
--> 124 raise ValueError(
125 "Argument `learning_rate` should be float, or an instance "
126 "of LearningRateSchedule, or a callable "
127 "(that takes in the current iteration value "
128 "and returns the corresponding learning rate value). "
129 f"Received instead: learning_rate={learning_rate}"
130 )
131 with backend.name_scope(self.name, caller=self):
132 learning_rate = backend.Variable(
133 learning_rate,
134 name="learning_rate",
(...)
137 aggregation="only_first_replica",
138 )