Keras-Flask文档分类API无输出问题排查求助
Hey there! I’ve seen this exact set of issues pop up a lot when folks first put a Keras model behind a Flask endpoint—let’s work through them one by one to get your /predict endpoint running smoothly.
1. Fixing the NameError: name 'texts' is not defined
This error means your code is trying to use a variable texts that hasn’t been created or assigned a value before it’s referenced. The most common culprit here is missing a step where you convert the incoming request text into a format Keras can process.
Here’s a corrected snippet for your endpoint that addresses this:
from flask import Flask, request, jsonify import tensorflow as tf from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences import json app = Flask(__name__) # Load your model and tokenizer ONCE at app startup (critical for performance!) model = tf.keras.models.load_model('your_cnn_model.h5') tokenizer = Tokenizer(num_words=5000) # Load the word index you saved during training (don't skip this!) tokenizer.word_index = json.load(open('word_index.json', 'r')) @app.route('/predict', methods=['POST']) def predict(): try: # Extract text from the incoming JSON request request_data = request.get_json() input_text = request_data.get('text', '') # Create the 'texts' variable by wrapping the input in a list (Keras expects batches!) texts = [input_text] # Preprocess the text exactly as you did during training sequences = tokenizer.texts_to_sequences(texts) padded_sequences = pad_sequences(sequences, maxlen=100) # Use YOUR training maxlen here # Run prediction prediction = model.predict(padded_sequences) predicted_class = tf.argmax(prediction, axis=1).numpy()[0] return jsonify({ 'predicted_class': int(predicted_class), 'confidence': float(prediction[0][predicted_class]) }) except Exception as e: return jsonify({'error': str(e)}), 400
Common mistakes to avoid here:
- Forgetting to wrap the single input text in a list (Keras models are built to handle batches of data, even if it’s just one sample)
- Using the wrong method to extract request data (use
request.get_json()for JSON payloads,request.formfor form data) - Not reloading the tokenizer’s word index from training—this ensures consistent text encoding
2. Fixing the TensorFlow ValueError
Once you resolve the NameError, this error almost always stems from an input shape mismatch between what your model expects and what you’re feeding it.
CNN text models typically expect input in the shape (batch_size, max_sequence_length). To fix this:
- Double-check that the
maxlenvalue inpad_sequencesmatches exactly what you used during training. If you trained withmaxlen=150, don’t usemaxlen=100in your Flask app. - Verify the input shape of your model’s first layer. For example, if your first layer is
Embedding(5000, 128, input_length=100), your padded sequences must be of length 100. - Ensure you’re passing a 2D array to
model.predict(). If your padded sequence is a 1D array (shape(100,)instead of(1,100)), add a batch dimension with:import numpy as np padded_sequences = np.expand_dims(padded_sequences, axis=0)
Quick Windows-Specific Tips
- Stick to
tensorflow.kerasinstead of standalone Keras to avoid version compatibility issues. - Never load your model inside the
/predictendpoint—this will reload it on every request, causing slowdowns and errors. Load it once when the app starts. - Test your preprocessing pipeline independently first: take a sample text, run it through tokenization and padding, then check if the output shape matches what your model expects before integrating with Flask.
Content of the question originates from Stack Exchange, question author StatguyUser

