简体   繁体   中英

Error in TensorFlow/Keras: ValueError: No gradients provided for any variable

I am new to the implementation of deep learning and I am trying to implement a method of music genre classification with Keras / Tensorflow based on the following Git .

With some modifications to the model.

The code I am implementing is as follows:

def preprocess(fin):
    y, sr = librosa.load(fin, duration=30.0)
    
    ##PREPROCESSING
    buffer = 3 * sr     #3seg
    samples_total = len(y)
    samples_wrote = 0
    mel = []
    win_length = int(np.ceil(0.020*sr))
    hop_length = int(np.ceil(0.010*sr))
    n_mels = 128
    window = 'hann'
    
    while samples_wrote < samples_total:
    
        #check if the buffer is not exceeding total samples 
        if buffer > (samples_total - samples_wrote):
            buffer = samples_total - samples_wrote
    
        block = y[samples_wrote : (samples_wrote + buffer)]
        samples_wrote += buffer
    
        #mel.append(librosa.feature.melspectrogram(y=block, sr=sr, n_mels=n_mels,hop_length=hop_length, win_length=win_length, window=window))
        test = librosa.feature.melspectrogram(y=block, sr=sr, n_mels=n_mels, hop_length=hop_length, win_length=win_length, window=window)
        
        #mel.append((test,4))
        #print("fin",str(fin))
        name = str(fin)
        if(name[0:2] == "cl"): #classical
            mel.append((test,1))
        elif(name[0:2] == "re"): #reggae
            mel.append((test,2))
        elif(name[0:2] == "co"): #country
            mel.append((test,3))
        elif(name[0:2] == "bl"): #blues
            mel.append((test,4))
        else:
            if(name[0:2] == "hi"): #hiphop
                mel.append((test,5))
        
        #mel.append(test)
            # mel.append(test.flatten())
        # df = np.asarray(mel)
        return(mel)
## CREATE A DATASET
M = []
df = []
for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.wav'):
        print("Loading...",file)
        M = preprocess(file)
        df += M
del M
del file

## CREATE AND PREPAR DATA
dataset = df
random.shuffle(dataset)

train = dataset[:25]
dev = dataset[25:35]
test = dataset[35:]

X_train, Y_train = zip(*train)
X_dev, Y_dev = zip(*dev)
X_test, Y_test = zip(*test)

## Reshape for CNN input
X_train = np.array([x.reshape( (128, 300, 1) ) for x in X_train])
X_dev = np.array([x.reshape( (128, 300, 1) ) for x in X_dev])
X_test = np.array([x.reshape( (128, 300, 1) ) for x in X_test])

## One-Hot encoding for classes
Y_train = np.array(keras.utils.to_categorical(Y_train, num_classes=6)) ## n_CLASS + 1
Y_dev = np.array(keras.utils.to_categorical(Y_dev, num_classes=6))
Y_test = np.array(keras.utils.to_categorical(Y_test, num_classes=6))

## OU USAR ESSE ABAIXO
# Y_train = np.array(Y_train)
# Y_dev = np.array(Y_dev)
# Y_test = np.array(Y_test)


######################################
# MODELO DE TESTE 1
# ERRO  ValueError: No gradients provided for any variable
######################################
# ## MODEL
# input_shape=(128, 300, 1)

# model_input = Input(input_shape, name='input')
# num_classes = 5
# layer = model_input

# conv_1 = tf.keras.layers.Conv2D(filters = 256, kernel_size = 7,
#                                 input_shape=input_shape, activation='relu',
#                                 name='conv_1')(layer)
# pool_1 = tf.keras.layers.MaxPooling2D(pool_size = 2)(conv_1)
# conv_2 = tf.keras.layers.Conv2D(filters = 256, kernel_size = 7,
#                                 input_shape=input_shape, activation='relu',
#                                 name='conv_2')(pool_1)
# pool_2 = tf.keras.layers.MaxPooling2D(pool_size = 2)(conv_2)
# drop_1 = Dropout(0.5)(pool_2)
# # flatten1 = Flatten()(drop_1)
# reshp_1 = tf.keras.layers.Reshape((161280,3))(drop_1)
# gru_1 = tf.keras.layers.GRU(units = 1024)(reshp_1)
# output = Dense(num_classes, activation = 'softmax')(gru_1)
# model_output = output

# model = Model(model_input, model_output)

# opt = RMSprop(lr=0.001)

# model.compile(optimizer="rmsprop")

# model.summary()

# EPOCH_COUNT = 3
# BATCH_SIZE = 16


# history = model.fit(X_train, Y_train, batch_size=BATCH_SIZE, epochs=EPOCH_COUNT, validation_data=(X_dev, Y_dev))

#############


#####################################
# MODELO DE TESTE 2
# ERRO  ValueError: No gradients provided for any variable
#####################################

# esse valor aqui em baixo é só teste
# train_data = tf.data.Dataset.from_tensor_slices((X_train, Y_train)).batch(30)

model = models.Sequential()
input_shape=(128, 300, 1)
model.add(tf.keras.layers.Conv2D(filters = 256, kernel_size = 7, input_shape=input_shape, activation='relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size = 2))
model.add(tf.keras.layers.Conv2D(filters = 256, kernel_size = 7, input_shape=input_shape, activation='relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size = 2))
model.add(Dropout(0.5))
model.add(tf.keras.layers.Reshape((161280,3)))
model.add(tf.keras.layers.GRU(units = 1024))
model.add(Dropout(0.5))
#model.add(tf.keras.activations.softmax)
model.add(tf.keras.layers.Activation('softmax'))

model.compile(optimizer="rmsprop")
model.summary()

epochs = 3
batch_size = 16
model.fit(x=X_train, y=Y_train, batch_size=batch_size, epochs = epochs, validation_data=(X_dev, Y_dev))
# model.fit(train_data, batch_size=batch_size, epochs = epochs)
#print(model.summary())

I tried to rewrite the model in two ways and both ways return the following error:

ValueError: No gradients provided for any variable: ['conv2d_5/kernel:0', 'conv2d_5/bias:0', 'conv2d_6/kernel:0', 'conv2d_6/bias:0', 'gru_2/gru_cell_2/kernel:0', 'gru_2/gru_cell_2/recurrent_kernel:0', 'gru_2/gru_cell_2/bias:0'].

Reading some solutions here at Stack Overflow and Git I was unable to solve the problem, since the code structure is analogous to Git above.

I'm running on Windows with Spyder 4.0.1

The database I am using to test at the moment (a small sample of the actual database) is available here .

增加损失:

model.compile(optimizer="rmsprop", loss='mse')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM