首页 > 编程语言 > 解决TensorFlow调用Keras库函数存在的问题
2020
10-08

解决TensorFlow调用Keras库函数存在的问题

tensorflow在1.4版本引入了keras,封装成库。现想将keras版本的GRU代码移植到TensorFlow中,看到TensorFlow中有Keras库,大喜,故将神经网络定义部分使用Keras的Function API方式进行定义,训练部分则使用TensorFlow来进行编写。一顿操作之后,运行,没有报错,不由得一喜。但是输出结果,发现,和预期的不一样。难道是欠拟合?故采用正弦波预测余弦来验证算法模型。

部分调用keras库代码如上图所示,用正弦波预测余弦波,出现如下现象:

def interface(_input):
  tmp = tf.keras.layers.Dense(10)(_input)
  vad_gru = tf.keras.layers.GRU(24, return_sequences=True)(tmp)
  denoise_output = tf.keras.layers.Dense(1)(vad_gru)
  return denoise_output

波形是断断续续的。而且最后不收敛。

运行N久。。。之后

基本断定是程序本身的问题,于是通过排查,发现应该是GRU的initial_state没有进行更新导致的。导致波形是断断续续的,没有学习到前一次网络的输出。于是,决定不使用Keras库实现一遍:

部分代码如下:

def interface(_input):
  tmp = tf.keras.layers.Dense(10)(_input)
  gru_cell = tf.nn.rnn_cell.GRUCell(vad_cell_size)
  with tf.name_scope('initial_state'):
    cell_init_state = gru_cell.zero_state(batch_size, dtype=tf.float32)
  cell_outputs, cell_final_state = tf.nn.dynamic_rnn(
    gru_cell, tmp, initial_state=cell_init_state, time_major=False)
  denoise_output = tf.keras.layers.Dense(1)(cell_outputs)
  return denoise_output, cell_init_state, cell_final_state

波形图如下(这才是GRU的正确打开方式啊~):

再回头看之前写的调用keras,既然知道了是initial_state没有更新,那么如何进行更新呢?

网上查找了大量的资料,说要加上

update_ops = []
for old_value, new_value in layers.updates:
  update_ops.append(tf.assign(old_value, new_value))

但是加上去没有效果,是我加错了还是其他的,大家欢迎指出来

以下是我做的一些尝试,就不一一详细说明了,大家看一下,具体不再展开,有问题大家交流一下,有解决方法的,能够分享出来,感激不尽~

def interface(_input):
  # input_layer = tf.keras.layers.Input([None, 1])
  # input_layer = tf.keras.layers.Input(batch_shape=(50, 20, 1))
  tmp = tf.keras.layers.Dense(10)(_input)
  # tmp = tf.keras.layers.Dense(24)(tmp)
 
  # with tf.variable_scope('vad_gru', reuse=tf.AUTO_REUSE):
  # vad_gru, final_state = tf.keras.layers.GRU(24, return_sequences=True, return_state=True, stateful=True)(tmp)
  # print(vad_gru)
  # _initial_state = vad_gru.zero_state(50, tf.float32)
  # tf.get_variable_scope().reuse_variables()
 
  # vad_gru = tf.contrib.
 
  # tmp = tf.reshape(tmp, [-1, TIME_STEPS, vad_cell_size])
  gru_cell = tf.nn.rnn_cell.GRUCell(vad_cell_size)
  # gru_cell = tf.keras.layers.GRUCell(self.vad_cell_size)
  with tf.name_scope('initial_state'):
    cell_init_state = gru_cell.zero_state(batch_size, dtype=tf.float32)
  cell_outputs, cell_final_state = tf.nn.dynamic_rnn(
    gru_cell, tmp, initial_state=cell_init_state, time_major=False)
  # print(cell_outputs.get_shape().as_list())
 
  # cell_outputs = tf.reshape(cell_outputs, [-1, vad_cell_size])
 
  denoise_output = tf.keras.layers.Dense(1)(cell_outputs)
  print(denoise_output.get_shape().as_list())
 
  # model = tf.keras.models.Model(input_layer, denoise_output)
  # update_ops = []
  # for old_value, new_value in model.layers[1].updates:
  #   update_ops.append(tf.assign(old_value, new_value))
 
  return denoise_output, cell_init_state, cell_final_state

补充知识:TensorFlow和Keras常用方法(避坑)

TensorFlow

在TensorFlow中,除法运算:

1.tensor除法会使结果的精度高一级,可能会导致后面计算类型不匹配,如float32 / float32 = float64。

2.除法需要分子分母同类型,否则报错。

产生类似错误提示如下:

-1.TypeError: x and y must have the same dtype, got tf.float32 != tf.int32

-2.TypeError: Input ‘y' of ‘Mul' Op has type float32 that does not match type float64 of argument ‘x'.

-3.ValueError: Tensor conversion requested dtype float64 for Tensor with dtype float32: ‘Tensor(“Sum:0”, shape=(), dtype=float32)'

-4.ValueError: Incompatible type conversion requested to type ‘int32' for variable of type ‘float32_ref'

解决办法:

tf.cast(a, tf.float32) # 转换成同类型即可

tf.boolean_mask

K.gather

K.argmax

K.max

以上这篇解决TensorFlow调用Keras库函数存在的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持自学编程网。

编程技巧