我是机器学习的初学者,并使用 tf keras 创建了一个顺序模型。我对如何使用 my_model 获得基于一个实例的预测感到困惑。该模型使用 4 个特征列并尝试确定标签“diff”。我已经发布了上下文的模型代码。以下代码来自谷歌机器学习速成课程,我的模型可以编译。我对如何使用生成的模型来预测值感到困惑。我的预测代码会贴在模型代码下。
feature_columns = []
homePAG = tf.feature_column.numeric_column("homePAG")
feature_columns.append(homePAG)
awayPAG = tf.feature_column.numeric_column("awayPAG")
feature_columns.append(awayPAG)
homePPG = tf.feature_column.numeric_column("homePPG")
feature_columns.append(homePPG)
awayPPG = tf.feature_column.numeric_column("awayPPG")
feature_columns.append(awayPPG)
fp_feature_layer = layers.DenseFeatures(feature_columns)
def create_model(my_learning_rate, feature_layer):
"""Create and compile a simple linear regression model."""
# 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)
# Add one linear layer to the model to yield a simple linear regressor.
model.add(tf.keras.layers.Dense(units=1, input_shape=(1,)))
# 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.RootMeanSquaredError()])
return model
def train_model(model, dataset, epochs, batch_size, label_name):
"""Feed a dataset into the model in order to train it."""
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)
# The list of epochs is stored separately from the rest of history.
epochs = history.epoch
# Isolate the mean absolute error for each epoch.
hist = pd.DataFrame(history.history)
rmse = hist["root_mean_squared_error"]
return epochs, rmse
def plot_the_loss_curve(epochs, rmse):
"""Plot a curve of loss vs. epoch."""
plt.figure()
plt.xlabel("Epoch")
plt.ylabel("Root Mean Squared Error")
plt.plot(epochs, rmse, label="Loss")
plt.legend()
plt.ylim([rmse.min()*0.94, rmse.max()* 1.05])
plt.show()
print("Defined the create_model, train_model, and plot_the_loss_curve functions.")
# The following variables are the hyperparameters.
learning_rate = 0.01
epochs = 10
batch_size = 75
label_name = 'diff'
# Create and compile the model's topography.
my_model = create_model(learning_rate, fp_feature_layer)
# Train the model on the training set.
epochs, rmse = train_model(my_model, train_df, epochs, batch_size, label_name)
plot_the_loss_curve(epochs, rmse)
print("\n: Evaluate the new model against the test set:")
test_features = {name:np.array(value) for name, value in test_df.items()}
test_label = np.array(test_features.pop(label_name))
#test_label=tf.convert_to_tensor(test_label)
my_model.evaluate(x=test_features, y=test_label, batch_size=batch_size)
对于此代码,我收到错误:
x={'homePAG':np.int64(7), 'awayPAG':np.int64(7), 'homePPG':np.int64(7), 'awayPPG':np.int64(7)}
my_model.predict(x)
<块引用>
ValueError: Failed to find data adapter that can handle input: (
对于此代码,我收到错误:
z=np.array([[10,10,10,10]])
my_model.predict(z)
<块引用>
ValueError: ('We expected a dictionary here. Instead we got: ', <tf.Tensor 'IteratorGetNext:0' shape=(None, 4) dtype=int64>)