2021-02-02 keras 可以改 loss(从 input 或者 tensor)

本文介绍了一种使用深度学习技术进行语音增强的方法。通过加载混响和清晰语音数据,将其转换为频谱并提取特征,然后利用定制损失函数训练模型以提高语音质量。该模型采用多层全连接网络结构,并在训练过程中调整学习率。

from keras.callbacks import LearningRateScheduler

from keras.layers import Multiply 

import keras
from keras.models import Sequential
from keras.models import Model
from keras.layers import Input
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import GRU
from keras.layers import SimpleRNN
from keras.layers import Dropout
from keras.layers import concatenate
from keras import losses
from keras import regularizers
from keras.constraints import min_max_norm
import h5py

from keras.constraints import Constraint
from keras import backend as K
import numpy as np

import os
import sys
import tensorflow as tf 


# def generateDataset():
mix, sr = librosa.load("./mix.wav", sr=16000)
clean,sr = librosa.load("./clean.wav",  sr=16000)

win_length = 256
hop_length = 128
nfft = 512

mix_spectrum = librosa.stft(mix, win_length=win_length, hop_length=hop_length, n_fft=nfft)
clean_spectrum = librosa.stft(clean, win_length=win_length, hop_length=hop_length, n_fft=nfft)

mix_mag = np.abs(mix_spectrum).T
clean_mag = np.abs(clean_spectrum).T
    
mix_phase = np.angle(mix_spectrum).T
clean_phase = np.angle(clean_spectrum).T

frame_num = mix_mag.shape[0] - 4
feature = np.zeros([frame_num, 257*5])
k = 0
for i in range(frame_num - 4):
    frame = mix_mag[k:k+5]
    feature[i] = np.reshape(frame, 257*5)
    k += 1

#PSM    
snr = np.divide(clean_mag, mix_mag) * np.cos(clean_phase - mix_phase)
label = snr[2:-2]

ref = np.cos(clean_phase - mix_phase)
ref = ref[2:-2]

ss = StandardScaler()
feature = ss.fit_transform(feature)


print(feature.shape)
print(label.shape)

window_size = 2000
nb_sequences = feature.shape[0]//window_size

feature = feature[:nb_sequences*window_size, :1285]
feature = np.reshape(feature, (nb_sequences, window_size, 1285))

label = label[:nb_sequences*window_size, :257]
label = np.reshape(label, (nb_sequences, window_size, 257))

ref = ref[:nb_sequences*window_size, :257]
ref = np.reshape(ref, (nb_sequences, window_size, 257))

ref = ref * label

print(feature.shape)
print(label.shape)
 

 

def scheduler(epochs):
    # 每隔1个epoch,学习率减小为原来的1/10
    lr = K.get_value(model.optimizer.lr)
    if epochs < 20:
        K.set_value(model.optimizer.lr, 0.00001)
    if epochs > 20:
        K.set_value(model.optimizer.lr, 0.00001)
    lr = K.get_value(model.optimizer.lr)
    print("lr changed to {}".format(lr ))
    return K.get_value(model.optimizer.lr)    
    
    
reduce_lr = LearningRateScheduler(scheduler)    

def mycost(k_input): 
    def custom_loss(y_true, y_pred):
        k = tf.convert_to_tensor(ref)
        bbb = K.mean( K.square(K.sqrt(y_pred) - K.sqrt( k)), axis=-1 )
        return bbb
    return custom_loss

feature_input = Input(shape=(None, 1285), name = 'feature_input')

dense1 = Dense(2048)(feature_input)
norm1 = BatchNormalization()(dense1)
relu1 = LeakyReLU(alpha=0.1)(norm1)
drop1 = Dropout(0.1)(relu1)

dense2 = Dense(2048)(drop1)
norm2 = BatchNormalization()(dense2)
relu2 = LeakyReLU(alpha=0.1)(norm2)
drop2 = Dropout(0.1)(relu2)

dense3 = Dense(2048)(drop2)
norm3 = BatchNormalization()(dense3)
relu3 = LeakyReLU(alpha=0.1)(norm3)
drop3 = Dropout(0.1)(relu3)


dense4 = Dense(257)(drop3)
norm4 = BatchNormalization()(dense4)
out = Activation('sigmoid')(norm4)

model = Model([feature_input] , out)

# My Cost
model.compile(optimizer='adam',
                  loss= mycost(model.input[1]),
                  metrics=['mse'])    

midWeightPath = './mid_weights.hdf5'
endEpochHookCB = keras.callbacks.ModelCheckpoint( midWeightPath,
                monitor = 'val_loss',
                save_weights_only = True,
                verbose = 1,
                save_best_only = False,
                period = 1 )

if os.path.exists(midWeightPath):
    model.load_weights( midWeightPath )
    print("checkpoint_loaded")
    
model.fit([feature] ,
          label, 
          batch_size=64, epochs=10, 
          callbacks =[endEpochHookCB,reduce_lr])
model.save("./model.hdf5")
    
 

<think>我们正在讨论 TensorFlow GPU 2.6.0 中 tf.keras 的使用方法。根据引用内容,特别是[1][2][3]都强烈建议使用 tf.keras,并且 Keras 2.3.0 之后开始与 tf.keras 同步,并且不再支持其他后端。 用户明确要求的是 tensorflow_gpu-2.6.0 中 tf.keras 函数的使用方法,因此我们需要提供在 TensorFlow 2.6.0 环境下使用 tf.keras 构建和训练模型的基本步骤。 注意:由于我们参考的引用中并没有直接提供2.6.0版本的具体变化,但我们知道2.6.0版本是在2.0之后发布的,因此遵循tf.keras的标准用法。同时,引用[5]提到了一些更新(虽然引用[5]的细节看起来比较底层,可能不直接影响高级API的使用),但我们需要确保我们的代码示例在2.6.0中有效。 下面,我将提供使用 tf.keras 构建模型的典型步骤,包括: 1. 导入 2. 数据准备 3. 模型构建(Sequential 或 Functional API) 4. 模型编译 5. 模型训练 6. 模型评估 另外,由于用户使用的是GPU版本,我们也可以简要提到GPU的使用情况(默认情况下,如果有GPU,TensorFlow会自动使用GPU)。 但是,注意引用[5]中提到的一些变化,比如TensorFloat-32的启用可能会影响精度(默认启用),但用户通常不需要担心,除非有特殊需求。我们可以提醒用户如果需要更高精度,可以禁用TensorFloat-32。 此外,XLA设备的默认注册情况有变,但通常使用tf.keras不需要直接处理XLA设备。 由于用户要求的是“使用方法”,我们将重点放在代码示例上。 下面开始构建回答: </think>### TensorFlow GPU 2.6.0 中 tf.keras 的使用方法 在 TensorFlow GPU 2.6.0 中,`tf.keras` 是官方推荐的高级 API(引用[1][2][3]),以下是核心使用流程: #### 1. **基础模型构建(Sequential API)** ```python import tensorflow as tf # 构建顺序模型 model = tf.keras.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation='softmax') ]) # 编译模型(GPU自动加速) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) ``` #### 2. **自定义模型(Functional API)** ```python inputs = tf.keras.Input(shape=(32,)) x = tf.keras.layers.Dense(64, activation='relu')(inputs) outputs = tf.keras.layers.Dense(10)(x) model = tf.keras.Model(inputs=inputs, outputs=outputs) ``` #### 3. **GPU 加速训练** ```python # 自动检测GPU(无需额外配置) model.fit(train_dataset, epochs=10, validation_data=val_dataset) ``` #### 4. **关键特性说明** - **精度控制**:若需禁用 TensorFloat-32 提升精度(引用[5]): ```python tf.config.experimental.enable_tensor_float_32_execution(False) ``` - **XLA 支持**:默认不启用 XLA 设备(引用[5]),需通过环境变量激活: ```bash export TF_XLA_FLAGS=--tf_xla_enable_xla_devices ``` - **兼容性**:完全兼容 Keras 2.3+ 标准 API(引用[3]) #### 5. **模型保存与加载** ```python model.save('model.h5') # HDF5格式 loaded_model = tf.keras.models.load_model('model.h5') ``` > **注意**:从 TensorFlow 2.0 开始,`tf.keras` 已成为官方首选实现,Keras 独立版本不再推荐用于新项目(引用[1][2][3][4])。所有操作均通过 GPU 自动加速,无需显式 CUDA 调用。 *** ### 相关问题 1. 如何在 TensorFlow 2.6 中混合使用自定义 GPU 操作和 tf.keras? 2. tf.keras 与纯 Keras 在模型迁移时有哪些兼容性陷阱? 3. TensorFlow 2.6 的 tf.keras 相比早期版本有哪些性能优化? 4. 如何利用 tf.keras 实现分布式 GPU 训练?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值