值错误:在转换后的代码Tenserflow

时间:2020-03-20 13:23:21

标签: python pandas tensorflow

给出值错误。我已经尝试了一切。 这是错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-105-5a2413254bdd> 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/keras/engine/base_layer.py:748 __call__
        self._maybe_build(inputs)
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/engine/base_layer.py:2116 _maybe_build
        self.build(input_shapes)
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/feature_column/feature_column_v2.py:505 build
        trainable=self.trainable)
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/feature_column/feature_column_v2.py:308 create_variable
        getter=variable_scope.get_variable)
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/engine/base_layer.py:446 add_weight
        caching_device=caching_device)
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/tracking/base.py:744 _add_variable_with_custom_getter
        **kwargs_for_getter)
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/variable_scope.py:1572 get_variable
        aggregation=aggregation)
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/variable_scope.py:1315 get_variable
        aggregation=aggregation)
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/variable_scope.py:568 get_variable
        aggregation=aggregation)
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/variable_scope.py:520 _true_getter
        aggregation=aggregation)
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/variable_scope.py:938 _get_single_variable
        aggregation=aggregation)
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/variables.py:258 __call__
        return cls._variable_v1_call(*args, **kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/variables.py:219 _variable_v1_call
        shape=shape)
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/variables.py:197 <lambda>
        previous_getter = lambda **kwargs: default_variable_creator(None, **kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/variable_scope.py:2596 default_variable_creator
        shape=shape)
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/variables.py:262 __call__
        return super(VariableMetaclass, cls).__call__(*args, **kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/resource_variable_ops.py:1411 __init__
        distribute_strategy=distribute_strategy)
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/resource_variable_ops.py:1520 _init_from_args
        if init_from_fn else [initial_value]) as name:
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/ops.py:6249 __enter__
        return self._name_scope.__enter__()
    /usr/lib/python3.6/contextlib.py:81 __enter__
        return next(self.gen)
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/ops.py:4024 name_scope
        raise ValueError("'%s' is not a valid scope name" % name)

    ValueError: 'linear/linear_model/Adult Mortality/weights' is not a valid scope name

为什么会出现错误? 在我的代码中,我基本上制作了一个线性回归模型,该模型使用的是名为data.csv的有关预期寿命的文件。我不了解此错误的原因。任何帮助将是非常可观的。

我的代码:

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('data.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',
                   'BMI', '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_columnss = []
for feature_name in CATEGORICAL_COLUMNS:
  vocabulary = dftrain[feature_name].unique()  # gets a list of all unique values from given feature column
  feature_columnss.append(tf.feature_column.categorical_column_with_vocabulary_list(feature_name, vocabulary))

for feature_name in NUMERIC_COLUMNS:
  feature_columnss.append(tf.feature_column.numeric_column(feature_name, dtype=tf.float32))

print(feature_columnss)

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_columnss)

linear_est.train(train_input_fn)  # train
result = linear_est.evaluate(eval_input_fn)  # get model metrics/stats by testing on tetsing data

0 个答案:

没有答案