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

TensorFlow LinearClassifier预测时出现KeyError: 'latitude'问题求助

KeyError: 'latitude' when using predict_classes with TensorFlow LinearClassifier

Let's break down why this error is happening and how to fix it quickly:

The Root Cause

Your LinearClassifier was trained expecting features named latitude and longitude (check your training input_fn—it creates a dictionary with these exact keys). But when making predictions, you're passing in a dictionary with a single key "x" instead. The model has no idea what "x" refers to, so it throws a KeyError when looking for the latitude feature it was trained on.

Fix Steps

You need to align the input keys in your prediction function with the feature column names the model expects. Here are two clean ways to do this:

Option 1: Split your new samples into matching feature arrays

new_samples = np.array(([39.8070525,-5.698599],[43.8800776,4.654769]),dtype=np.float64)

# Create an input dictionary with keys matching your feature columns
my_input_fn = tf.estimator.inputs.numpy_input_fn(
    x={
        "latitude": new_samples[:, 0],  # Extract first column as latitude values
        "longitude": new_samples[:, 1]  # Extract second column as longitude values
    },
    y=None,
    num_epochs=1,  # No need for multiple epochs when predicting once
    shuffle=False
)

# Now this will execute without errors
pred = model.predict_classes(input_fn=my_input_fn)

Option 2: Pass separate feature lists directly

If you already have latitude and longitude values as separate lists, you can pass them directly to the input function:

new_lats = [39.8070525, 43.8800776]
new_lons = [-5.698599, 4.654769]

my_input_fn = tf.estimator.inputs.numpy_input_fn(
    x={
        "latitude": np.array(new_lats, dtype=np.float64),
        "longitude": np.array(new_lons, dtype=np.float64)
    },
    y=None,
    num_epochs=1,
    shuffle=False
)

Quick Optimization Note

I adjusted num_epochs=2 to num_epochs=1 in the prediction input function—since you're predicting on these samples once, there's no need to repeat the process multiple times.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:40:06