You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于TensorFlow模型实现鸢尾花数据集的预测?

Hey there! Let's break down how to implement prediction with your TensorFlow model for the Iris dataset, using the code snippet you provided as a starting point. First, let's fix a small typo in your existing code (you accidentally used train instead of test for Xtest) and then walk through the full process step by step.

1. Clean Up & Complete the Existing Code

Here's your code with the typo fixed and the model function expanded (since it was cut off mid-definition):

import pandas as pd
import tensorflow as tf

# Load datasets
names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'species']
train = pd.read_csv(dataset, names=names, skiprows=1)
test = pd.read_csv(test_dataset, names=names, skiprows=1)

# Prepare features and one-hot encoded labels
Xtrain = train.drop("species", axis=1)
# Fixed: use test dataframe for Xtest instead of train
Xtest = test.drop("species", axis=1)
ytrain = pd.get_dummies(train.species)
ytest = pd.get_dummies(test.species)

# Get input/output dimensions from training data
input_dim = Xtrain.shape[1]  # 4 features total
output_dim = ytrain.shape[1]  # 3 Iris species

def create_train_model(hidden_nodes, num_iters):
    # Reset the TensorFlow graph to avoid variable reuse conflicts
    tf.reset_default_graph()
    
    # Define placeholders for input features and labels
    X = tf.placeholder(tf.float32, shape=[None, input_dim])
    y = tf.placeholder(tf.float32, shape=[None, output_dim])
    
    # Build hidden layer: fully connected with ReLU activation
    W1 = tf.Variable(tf.random_normal([input_dim, hidden_nodes]))
    b1 = tf.Variable(tf.random_normal([hidden_nodes]))
    hidden_layer = tf.nn.relu(tf.matmul(X, W1) + b1)
    
    # Build output layer: fully connected with softmax (for multi-class classification)
    W2 = tf.Variable(tf.random_normal([hidden_nodes, output_dim]))
    b2 = tf.Variable(tf.random_normal([output_dim]))
    logits = tf.matmul(hidden_layer, W2) + b2
    y_pred = tf.nn.softmax(logits)
    
    # Define loss function and optimizer
    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y, logits=logits))
    optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)
    
    # Calculate accuracy for validation
    correct_pred = tf.equal(tf.argmax(y_pred, 1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
    
    # Train the model within a session
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        
        # Training loop
        for i in range(num_iters):
            _, train_loss, train_acc = sess.run(
                [optimizer, loss, accuracy],
                feed_dict={X: Xtrain.values, y: ytrain.values}
            )
            
            # Print progress every 100 iterations
            if i % 100 == 0:
                print(f"Iteration {i}: Loss = {train_loss:.4f}, Training Accuracy = {train_acc:.4f}")
        
        # Define a helper function to make predictions
        def predict(input_data):
            return sess.run(y_pred, feed_dict={X: input_data})
        
        # Evaluate on test set
        test_acc = sess.run(accuracy, feed_dict={X: Xtest.values, y: ytest.values})
        print(f"\nFinal Test Accuracy: {test_acc:.4f}")
        
        return predict

2. Train the Model

Call the function to create and train your model. Let's use 8 hidden nodes and 1000 iterations as a starting point (you can tweak these hyperparameters later):

# Train the model and get a prediction function
predict_fn = create_train_model(hidden_nodes=8, num_iters=1000)

3. Make Predictions

Now you can use the returned predict_fn to generate predictions on new data. Here's how:

a. Prepare New Input Data

Your input must have the same 4 features (in the same order) as your training data:

# Example new sample: [sepal-length, sepal-width, petal-length, petal-width]
new_iris_sample = [[5.1, 3.5, 1.4, 0.2]]  # This is an Iris-setosa sample

b. Run the Prediction

Use the predict_fn to get the probability distribution for each species:

prediction_probs = predict_fn(new_iris_sample)
print("Predicted Probabilities for Each Species:", prediction_probs)

c. Convert Probabilities to a Species Name

Map the highest-probability class back to the actual species name:

# Get the ordered list of species (matches the one-hot encoding order)
species_list = ytrain.columns.tolist()

# Find the index of the highest probability
predicted_class_index = prediction_probs.argmax(axis=1)[0]
predicted_species = species_list[predicted_class_index]

print(f"Predicted Iris Species: {predicted_species}")

Key Tips

  • Data Consistency: If you applied any preprocessing (like feature scaling) to your training data, make sure to apply the same transformation to new input data before predicting.
  • Model Persistence: For long-term use, save your trained model using TensorFlow's SavedModel format instead of relying on a session-bound prediction function. This lets you load the model later without retraining.

内容的提问来源于stack exchange,提问作者Kyrylo Kalashnikov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:04:42