如何在Python的Keras框架中使用训练好的模型确定输入数据?
Hey there! Let's walk through how to use your trained Keras model to make predictions on new input data. First, let's fix a couple of tiny typos in your training code—they'll cause errors if left unaddressed:
Fixed Training Code
import numpy as np from keras.models import Sequential from keras.layers import Dense np.random.seed(5) # Fixed: "delimeter" → "delimiter" dataset = np.loadtxt('path to dataset', delimiter=',') x_train = dataset[:700, 0:3] y_train = dataset[:700, 3] x_test = dataset[700:, 0:3] y_test = dataset[700:, 3] model = Sequential() # Fixed: "activate" → "activation" model.add(Dense(12, input_dim=3, activation='relu')) model.add(Dense(8, activation='relu')) model.add(Dense(1, activation='sigmoid')) # Completed compile statement with optimizer and metrics model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # Train the model (you were missing this key step!) model.fit(x_train, y_train, epochs=100, batch_size=10)
Using the Trained Model for Predictions
Once your model is trained, you can use it to predict outputs for new input data in three simple steps:
Step 1: Save the Trained Model (Optional but Highly Recommended)
Saving your model lets you reuse it later without retraining. Add this code right after training finishes:
# Save entire model (structure + weights + training config) in one file model.save('my_trained_model.h5') # Alternative: Save structure and weights separately (if you prefer) # model_json = model.to_json() # with open("model_structure.json", "w") as json_file: # json_file.write(model_json) # model.save_weights("model_weights.h5")
Step 2: Load the Saved Model (If You Saved It)
If you closed your Python session and want to reuse the model later, load it like this:
from keras.models import load_model # Load the full saved model loaded_model = load_model('my_trained_model.h5') # If you saved structure/weights separately: # from keras.models import model_from_json # json_file = open('model_structure.json', 'r') # loaded_model_json = json_file.read() # json_file.close() # loaded_model = model_from_json(loaded_model_json) # loaded_model.load_weights("model_weights.h5") # # Re-compile the model (required for separate saves) # loaded_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
Step 3: Make Predictions on New Input Data
Your model expects input data with the same shape as your training data (3 features per sample, formatted as a 2D array). Here's how to use it:
Example 1: Single Input Sample
# Create a 2D array (even for one sample—Keras expects batch inputs) new_sample = np.array([[1.5, 2.3, 4.1]]) # Get prediction probability (from sigmoid activation) pred_prob = loaded_model.predict(new_sample) # Convert probability to binary class (0 or 1) using 0.5 as threshold pred_class = (pred_prob > 0.5).astype(int) print(f"Predicted Probability: {pred_prob[0][0]:.4f}") print(f"Predicted Class: {pred_class[0][0]}")
Example 2: Multiple Input Samples
# Batch of 3 samples, each with 3 features batch_samples = np.array([ [0.2, 0.4, 0.6], [7.2, 8.1, 9.3], [3.5, 1.7, 2.9] ]) pred_probs = loaded_model.predict(batch_samples) pred_classes = (pred_probs > 0.5).astype(int) for idx, (prob, cls) in enumerate(zip(pred_probs, pred_classes)): print(f"Sample {idx+1}: Probability = {prob[0]:.4f}, Class = {cls[0]}")
Key Notes
- Match Preprocessing: If you normalized/standardized your training data (e.g., scaled features to 0-1), apply the exact same transformation to new input data—otherwise predictions will be unreliable.
- Input Shape: Always pass input as a 2D array. A shape like
(3,)will cause errors; use(1, 3)for single samples instead. - No Save? No Problem: If you're using the model immediately after training, you can skip saving/loading and just call
model.predict()directly with your new data.
内容的提问来源于stack exchange,提问作者송준석
相关产品推荐
相关产品推荐

