我正在尝试将我的(float32)模型的精度更改为float16,以查看它需要多少性能 . 加载模型(base_model)后我尝试了这个:

from keras import backend as K
K.set_floatx('float16')
weights_list = base_model.layers[1].get_weights()
print('Original:')
print(weights_list[0].dtype)
new_weights = [K.cast_to_floatx(weights_list[0])]
print('New Weights:')
print(new_weights[0].dtype)
print('Setting New Weights')
base_model.layers[1].set_weights(new_weights)
new_weights_list = base_model.layers[1].get_weights()
print(new_weights_list[0].dtype)

输出:

Original:
float32
New Weights:
float16
Setting New Weights
float32

使用此代码,一层中的权重将转换为float16,并且模型中的权重将设置为新权重,但在使用get_weights后,数据类型将返回到float32 . 有没有办法设置图层的dtype?据我所知,K.cast_to_floatx用于numpy数组,K.cast用于张量 . 我是否需要使用新的dtype来构建全新的空模型并将重铸权重放入新模型中?

或者是否有一些更简单的方法来加载模型,所有图层都具有dtype'float32',并将所有图层转换为dtype'float16'?这是一个融入mlmodel的功能,所以我认为在Keras中并不是特别困难 .