python - 我收到一个错误 KeyError Feature not in dictionay
问题描述
在我的代码中,我已经导入了所需的库。然后我加载了数据集并创建了我的模型并进行了测试和评估。问题出现在特征字典中。
我的代码是:
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import clear_output
from six.moves import urllib
from sklearn.model_selection import train_test_split
import tensorflow.compat.v2.feature_column as fc
import tensorflow as tf
df = pd.read_csv('life.csv')
dftrain, dfeval = train_test_split(df, test_size = 0.2, random_state = 0)
y_train = dftrain.pop('Status')
y_eval = dfeval.pop('Status')
print(y_eval.shape)
dftrain.head()
dfeval.shape
CATEGORICAL_COLUMNS = ['Country']
NUMERIC_COLUMNS = ['Year', 'Life_expectancy', 'Adult_Mortality', 'infant_deaths',
'Alcohol', 'percentage_expenditure', 'Hepatitis_B', 'Measles',
'Body_mi', 'under-five_deaths', 'Polio', 'Total_expenditure',
'Diphtheria', 'HIV/AIDS', 'GDP', 'Population', 'thinness_1-19_years',
'thinness_5-9_years', 'Income_composition_of_resources', 'Schooling']
feature_columns = []
for feature_name in CATEGORICAL_COLUMNS:
vocabulary = dftrain[feature_name].unique() # gets a list of all unique values from given feature column
feature_columns.append(tf.feature_column.categorical_column_with_vocabulary_list(feature_name, vocabulary))
for feature_name in NUMERIC_COLUMNS:
feature_columns.append(tf.feature_column.numeric_column(feature_name, dtype=tf.float32))
print(feature_columns)
def make_input_fn(data_df, label_df, num_epochs=15, shuffle=True, batch_size=32):
def input_function(): # inner function, this will be returned
ds = tf.data.Dataset.from_tensor_slices((dict(data_df), label_df)) # create tf.data.Dataset object with data and its label
if shuffle:
ds = ds.shuffle(1000) # randomize order of data
ds = ds.batch(batch_size).repeat(num_epochs) # split dataset into batches of 32 and repeat process for number of epochs
return ds # return a batch of the dataset
return input_function # return a function object for use
train_input_fn = make_input_fn(dftrain, y_train) # here we will call the input_function that was returned to us to get a dataset object we can feed to the model
eval_input_fn = make_input_fn(dfeval, y_eval, num_epochs=1, shuffle=False)
linear_est = tf.estimator.LinearClassifier(feature_columns=feature_columns)
linear_est.train(train_input_fn) # train
result = linear_est.evaluate(eval_input_fn) # get model metrics/stats by testing on tetsing data
我解决了以前的一个类似这样的错误,但我无法解决这个问题。我得到的错误是:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-31-d10467b3dec3> in <module>()
----> 1 linear_est.train(train_input_fn) # train
2 result = linear_est.evaluate(eval_input_fn) # get model metrics/stats by testing on tetsing data
8 frames
/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/autograph/impl/api.py in wrapper(*args, **kwargs)
235 except Exception as e: # pylint:disable=broad-except
236 if hasattr(e, 'ag_error_metadata'):
--> 237 raise e.ag_error_metadata.to_exception(e)
238 else:
239 raise
ValueError: in converted code:
/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/feature_column/feature_column_v2.py:706 call
return self.layer(features)
/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/feature_column/feature_column_v2.py:540 call
weight_var=weight_var)
/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/feature_column/feature_column_v2.py:2418 _create_weighted_sum
weight_var=weight_var)
/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/feature_column/feature_column_v2.py:2424 _create_dense_column_weighted_sum
tensor = column.get_dense_tensor(transformation_cache, state_manager)
/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/feature_column/feature_column_v2.py:2852 get_dense_tensor
return transformation_cache.get(self, state_manager)
/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/feature_column/feature_column_v2.py:2615 get
transformed = column.transform_feature(self, state_manager)
/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/feature_column/feature_column_v2.py:2824 transform_feature
input_tensor = transformation_cache.get(self.key, state_manager)
/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/feature_column/feature_column_v2.py:2607 get
raise ValueError('Feature {} is not in features dictionary.'.format(key))
ValueError: Feature Body_mi is not in features dictionary.
任何帮助都会非常显着。我不知道为什么会显示此错误。
解决方案
推荐阅读
- android - 制作 startActivityForResult() 模式
- javascript - 如何根据作为 Socket IO 中 io.to() 的一部分传递的 Shop ID 在 JavaScript 中进行处理
- python - 有没有办法使用 Pillow 将图像转换为 HSL?
- javascript - 当我在我的网站上注册新用户时出现此错误“secretOrPrivateKey 必须有一个值”!节点.js
- linux - TYK 仪表板和网关有效负载
- python - Python OpenCV solvePnP 转换为欧拉角
- excel - 将数据复制到下一个空单元格
- python - 获取 CondaHTTP 错误:尝试更新 anaconda 时 ssl 模块不可用
- arduino - Arduino——失去价值的全局变量
- sql - 如何将 2 个 ComboBoxes 连接到不同的表?