Python 如何将step_函数作为激活函数写入keras?
已更新 由于,我能够使用tensorflow构建工作步函数。(见下面的代码) 现在我的问题演变成了 如何利用在Python 如何将step_函数作为激活函数写入keras?,python,keras,tensor,Python,Keras,Tensor,已更新 由于,我能够使用tensorflow构建工作步函数。(见下面的代码) 现在我的问题演变成了 如何利用在tensorflow中创建的tf\u步骤激活功能在keras中工作 我尝试使用以下代码在keras中使用tf_stepy,但不起作用: from tensorflow_step_function import tf_stepy def buy_hold_sell(x): return tf_stepy(x) get_custom_objects().update({'cust
tensorflow
中创建的tf\u步骤
激活功能在keras
中工作
我尝试使用以下代码在keras中使用tf_stepy
,但不起作用:
from tensorflow_step_function import tf_stepy
def buy_hold_sell(x):
return tf_stepy(x)
get_custom_objects().update({'custom_activation': Activation(buy_hold_sell)})
下面是使用tensorflow创建的步骤激活函数
# tensorflow_step_function.py
import tensorflow as tf
import keras.backend as K
from keras.backend.tensorflow_backend import _to_tensor
import numpy as np
def stepy(x):
if x < 0.33:
return 0.0
elif x > 0.66:
return 1.0
else:
return 0.5
import numpy as np
np_stepy = np.vectorize(stepy)
def d_stepy(x): # derivative
if x < 0.33:
return 0.0
elif x > 0.66:
return 1.0
else:
return 0.5
np_d_stepy = np.vectorize(d_stepy)
import tensorflow as tf
from tensorflow.python.framework import ops
np_d_stepy_32 = lambda x: np_d_stepy(x).astype(np.float32)
def py_func(func, inp, Tout, stateful=True, name=None, grad=None):
# Need to generate a unique name to avoid duplicates:
rnd_name = 'PyFuncGrad' + str(np.random.randint(0, 1E+8))
tf.RegisterGradient(rnd_name)(grad) # see _MySquareGrad for grad example
g = tf.get_default_graph()
with g.gradient_override_map({"PyFunc": rnd_name}):
return tf.py_func(func, inp, Tout, stateful=stateful, name=name)
def tf_d_stepy(x,name=None):
with ops.op_scope([x], name, "d_stepy") as name:
y = tf.py_func(np_d_stepy_32,
[x],
[tf.float32],
name=name,
stateful=False)
return y[0]
def stepygrad(op, grad):
x = op.inputs[0]
n_gr = tf_d_stepy(x)
return grad * n_gr
np_stepy_32 = lambda x: np_stepy(x).astype(np.float32)
def tf_stepy(x, name=None):
with ops.op_scope([x], name, "stepy") as name:
y = py_func(np_stepy_32,
[x],
[tf.float32],
name=name,
grad=stepygrad) # <-- here's the call to the gradient
return y[0]
with tf.Session() as sess:
x = tf.constant([0.2,0.7,0.4,0.6])
y = tf_stepy(x)
tf.initialize_all_variables().run()
print(x.eval(), y.eval(), tf.gradients(y, [x])[0].eval())
#tensorflow_step_function.py
导入tensorflow作为tf
将keras.backend作为K导入
从keras.backend.tensorflow\u后端导入\u到\u tensor
将numpy作为np导入
def stepy(x):
如果x<0.33:
返回0.0
elif x>0.66:
返回1.0
其他:
返回0.5
将numpy作为np导入
np_stepy=np.矢量化(stepy)
def d_stepy(x):#导数
如果x<0.33:
返回0.0
elif x>0.66:
返回1.0
其他:
返回0.5
np_d_stepy=np.矢量化(d_stepy)
导入tensorflow作为tf
从tensorflow.python.framework导入ops
np_d_stepy_32=lambda x:np_d_stepy(x).astype(np.float32)
def py_func(func、inp、Tout、stateful=True、name=None、grad=None):
#需要生成唯一的名称以避免重复:
rnd_name='PyFuncGrad'+str(np.random.randint(0,1E+8))
tf.RegisterGradient(rnd_名称)(grad)#有关grad示例,请参见_MySquareGrad
g=tf.get_default_graph()
使用g.gradient_覆盖_映射({“PyFunc”:rnd_name}):
返回tf.py_func(func,inp,Tout,stateful=stateful,name=name)
def tf_d_stepy(x,name=None):
使用ops.op_scope([x],名称,“d_stepy”)作为名称:
y=tf.py_func(np_d_stepy_32,
[x] ,,
[tf.32],
name=name,
stateful=False)
返回y[0]
def stepygrad(操作,梯度):
x=运算输入[0]
n_gr=tf_d_stepy(x)
返回梯度*n\u gr
np_stepy_32=lambda x:np_stepy(x).astype(np.float32)
def tf_步骤(x,名称=无):
以ops.op_范围([x],名称,“stepy”)作为名称:
y=py_func(np_stepy_32,
[x] ,,
[tf.32],
name=name,
grad=stepygrad)#这行不通。非线性仍然必须是可微的。阶跃函数是不可微的,因此无法计算梯度
您总是可以尝试构建一个近似步骤的可微函数。这已经是乙状结肠或tanh对于“一步”版本所做的
我希望这有点帮助:)这个步骤函数在tensorflow中工作,因为tensorflow在ops中提供了一个框架,当您调用RegisterGradient时,它使用用户定义的函数作为GridClient函数。然而,当您在keras中使用它时,正如您所描述的,您没有将用户定义的梯度函数添加到(比方说)keras框架中。所以它不起作用。那么如何让它工作。keras使用tensorflow作为后端,所以您可以在调用tensorflow中的函数时始终调用keras.backend中的函数。因此,如果可以的话,可以使用keras.backend实现step函数及其渐变函数 谢谢Nassim,你能看看更新的部分吗?我不知道如何让它在keras中工作,因为tf_stepy
在tensorflow中工作。
def step_func(x, lower_threshold=0.33, higher_threshold=0.66):
# x is an array, and return an array
for index in range(len(x)):
if x[index] < lower_threshold:
x[index] = 0.0
elif x[index] > higher_threshold:
x[index] = 1.0
else:
x[index] = 0.5
import tensorflow as tf
import keras.backend as K
from keras.backend.tensorflow_backend import _to_tensor
import numpy as np
def high_med_low(x, lower_threshold=0.33, higher_threshold=0.66):
"""
x: tensor
return a tensor
"""
# x_shape = K.get_variable_shape(x)
# x_flat = K.flatten(x)
x_array = K.get_value(x)
for index in range(x_array.shape[0]):
if x_array[index,0] < lower_threshold:
x_array[index,0] = 0.0
elif x_array[index,0] > higher_threshold:
x_array[index,0] = 1.0
else:
x_array[index,0] = 0.5
# x_return = x_array.reshape(x_shape)
return _to_tensor(x_array, x.dtype.base_dtype)
x = K.ones((10,1)) * 0.7
print(high_med_low(x))
# the following line of code is used in building a model with keras
get_custom_objects().update({'custom_activation': Activation(high_med_low)})