尝试使用未初始化的值density_1 / bias Tensorflow

时间:2019-02-06 04:34:22

标签: python tensorflow machine-learning keras

我正在使用keras模型开发声音识别系统,然后使用tensorflow将其转换为可在Android上使用的模型。代码如下。代码中的X_data和Y_data是numpy二进制文件,具有2个功能:40个表示声音的MFCC及其值的值。

import numpy as np
import pandas as pd
import os
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.optimizers import Adam
from keras.utils import np_utils
from sklearn import model_selection as ms
from sklearn import preprocessing
import librosa
import h5py
import tensorflow as tf

X_data = np.load('C:\\Users\colew\oneDrive\Desktop\X.npy')
Y_data = np.load('C:\\Users\colew\oneDrive\Desktop\Y.npy')

X=np.array(X_data.tolist())
Y=np.array(Y_data.tolist())
lb=preprocessing.LabelEncoder()
yy=np_utils.to_categorical(lb.fit_transform(Y_data))

aTrain,aTest,bTrain,bTest=ms.train_test_split(X_data,yy,test_size=0.2)

num_labels = yy.shape[1]
filter_size = 2

# build model
model = Sequential()

model.add(Dense(256, input_shape=(40, )))
model.add(Activation('relu'))
model.add(Dropout(0.5))
'''
model.add(Dense(256, input_shape=(40, )))
model.add(Activation('relu'))
model.add(Dropout(0.5))

model.add(Dense(256, input_shape=(40, )))
model.add(Activation('relu'))
model.add(Dropout(0.5))
'''
model.add(Dense(num_labels, input_shape = (10, )))
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam')
model.fit(aTrain, bTrain, epochs=100, validation_data=(aTest, bTest))

model.save("SDmodel.h5")

# Save tf.keras model in HDF5 format.
keras_file = "keras_model.h5"
tf.keras.models.save_model(model, keras_file)

# Convert to TensorFlow Lite model.
converter = tf.lite.TFLiteConverter.from_keras_model_file(keras_file)
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)

这是由tensorflow提供的一组示例代码,该代码可以正常工作并执行类似的操作

import numpy as np
import tensorflow as tf

# Generate tf.keras model.
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(2, input_shape=(3,)))
model.add(tf.keras.layers.RepeatVector(3))
model.add(tf.keras.layers.TimeDistributed(tf.keras.layers.Dense(3)))
model.compile(loss=tf.keras.losses.MSE,
              optimizer=tf.keras.optimizers.RMSprop(lr=0.0001),
              metrics=[tf.keras.metrics.categorical_accuracy],
              sample_weight_mode='temporal')

x = np.random.random((1, 3))
y = np.random.random((1, 3, 3))
model.train_on_batch(x, y)
model.predict(x)

# Save tf.keras model in HDF5 format.
keras_file = "keras_model.h5"
tf.keras.models.save_model(model, keras_file)

# Convert to TensorFlow Lite model.
converter = tf.lite.TFLiteConverter.from_keras_model_file(keras_file)
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)

该代码运行完美。但是,在成功保存模型并进入转换部分后,我的遇到了一些问题。具体来说,我在代码中碰到了一个问题

tf.keras.models.save_model(model, keras_file)

我在哪里得到错误

Traceback (most recent call last):
  File "C:/Users/colew/PycharmProjects/SDModel/SDSoundRecognitionSystem.py", line 77, in <module>
    tf.keras.models.save_model(model, keras_file)
  File "C:\Users\colew\PycharmProjects\SDModel\venv\python35\lib\site-packages\tensorflow\python\keras\saving\hdf5_format.py", line 108, in save_model
    save_weights_to_hdf5_group(model_weights_group, model_layers)
  File "C:\Users\colew\PycharmProjects\SDModel\venv\python35\lib\site-packages\tensorflow\python\keras\saving\hdf5_format.py", line 699, in save_weights_to_hdf5_group
    weight_values = K.batch_get_value(symbolic_weights)
  File "C:\Users\colew\PycharmProjects\SDModel\venv\python35\lib\site-packages\tensorflow\python\keras\backend.py", line 2777, in batch_get_value
    return get_session().run(tensors)
  File "C:\Users\colew\PycharmProjects\SDModel\venv\python35\lib\site-packages\tensorflow\python\client\session.py", line 930, in run
    run_metadata_ptr)
  File "C:\Users\colew\PycharmProjects\SDModel\venv\python35\lib\site-packages\tensorflow\python\client\session.py", line 1153, in _run
    feed_dict_tensor, options, run_metadata)
  File "C:\Users\colew\PycharmProjects\SDModel\venv\python35\lib\site-packages\tensorflow\python\client\session.py", line 1329, in _do_run
    run_metadata)
  File "C:\Users\colew\PycharmProjects\SDModel\venv\python35\lib\site-packages\tensorflow\python\client\session.py", line 1349, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value dense_1/bias
     [[node dense_1/bias/read (defined at \Users\colew\PycharmProjects\SDModel\venv\python35\lib\site-packages\keras\backend\tensorflow_backend.py:402) ]]

我不太确定问题出在哪里,但是我假设由于错误中包含density_1,所以它与第一次引用density有关。任何信息都会有所帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

您正在使用来自keras的顺序模型,而示例代码使用tf.keras。那可能是问题所在。我以前也遇到过麻烦。