简体   繁体   中英

ValueError after loading saved keras model

I created a multiple linear regression model in keras. I have been trying to use the model.save() and model.load_model() methods. I tried both the 'tf' and the 'h5' format but neither seem to work.

Calling .summary() on the loaded 'tf' model generates the following:
ValueError: This model has not yet been built. Build the model first by calling build() or calling fit() with some data, or specify an input_shape argument in the first layer(s) for automatic build.

The 'h5' model throws an error during loading:

ValueError: You are trying to load a weight file containing 2 layers into a model with 0 layers.

I found postings of similar issues but the solutions don't seem to work in my case.

Here's the code I used to build the model.

# Create an empty list that will eventually hold all created feature columns.
feature_columns = []
feature_names = data.drop(['price', 'lat', 'long'], axis=1).columns

# Loop through features to represent data
for feature in feature_names:
    if data[feature].dtype == bool:
        train_df_norm[feature] = data[feature].astype('str') # bool raises value error
        test_df_norm[feature] = data[feature].astype('str') # bool raises value error
        categorical_feature = tf.feature_column.categorical_column_with_vocabulary_list(
            feature, ['True', 'False']
        )
        new_feature = tf.feature_column.indicator_column(categorical_feature)
    else:
        new_feature = tf.feature_column.numeric_column(feature, shape=(1,))
    feature_columns.append(new_feature)

# Convert list of feature columns into a layer that will be fed into the model. 
my_feature_layer = tf.keras.layers.DenseFeatures(feature_columns)
def create_model(my_learning_rate, feature_layer, l2=0):
    """Create and compile a linear regression model with l2 regularization."""
    # Most simple tf.keras models are sequential.
    model = tf.keras.models.Sequential()

    # Add the layer containing the feature columns to the model.
    model.add(feature_layer)

    # model.add(keras.engine.InputLayer(batch_input_shape=(36, 1)))

    # Add one linear layer to the model to yield a simple linear regressor.
    model.add(tf.keras.layers.Dense(units=1, input_shape=(1,),
                                    kernel_regularizer=tf.keras.regularizers.l2(l2)))

    # Construct the layers into a model that TensorFlow can execute.
    model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=my_learning_rate),
                loss="mean_squared_error",
                metrics=[tf.keras.metrics.MeanSquaredError()])

    return model           


def train_model(model, dataset, epochs, batch_size, label_name):
    """Feed a dataset into the model in order to train it."""

    # Split the dataset into features and label.
    features = {name:np.array(value) for name, value in dataset.items()}
    label = np.array(features.pop(label_name))
    history = model.fit(x=features, y=label, batch_size=batch_size,
                        epochs=epochs, shuffle=True)

    # Get details that will be useful for plotting the loss curve.
    epochs = history.epoch
    hist = pd.DataFrame(history.history)
    rmse = hist["mean_squared_error"]

    return epochs, rmse   

print("Defined the create_model and train_model functions.")
# Hyperparameters.
learning_rate = 0.002
epochs = 150
batch_size = 1000
l2 = 0.1
label_name = "price"

# Establish the model's topography.
my_linear_model = create_model(learning_rate, my_feature_layer, l2)

# Train the model on the normalized training set.
epochs, mse = train_model(my_linear_model, train_df_norm, epochs, batch_size, label_name)

# Validation
test_features = {name:np.array(value) for name, value in test_df_norm.items()}
test_label = np.array(test_features.pop(label_name)) # isolate the label
print("\n Evaluate the linear regression model against the test set:")
my_linear_model.evaluate(x = test_features, y = test_label, batch_size=batch_size)

You can try

model_2 = load.model('model_1.h5')

To evaluate the model :

model_2.evaluate(test_set)

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