[英]ValueError after loading saved keras model
I created a multiple linear regression model in keras.我在 keras 中创建了一个多元线性回归模型。 I have been trying to use the model.save() and model.load_model() methods.我一直在尝试使用 model.save() 和 model.load_model() 方法。 I tried both the 'tf' and the 'h5' format but neither seem to work.我尝试了 'tf' 和 'h5' 格式,但似乎都不起作用。
Calling .summary() on the loaded 'tf' model generates the following:在加载的“tf”模型上调用 .summary() 会生成以下内容:
ValueError: This model has not yet been built. ValueError:此模型尚未构建。 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.首先通过使用一些数据调用build()
或调用fit()
来构建模型,或者在第一层中指定input_shape
参数以进行自动构建。
The 'h5' model throws an error during loading: 'h5' 模型在加载过程中引发错误:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.