我收到了这个错误:

UnimplementedError (see above for traceback): Cast string to float is not supported
 [[node dnn/input_from_feature_columns/input_layer/Gender/ToFloat (defined at neuralnetwork_1.py:39)  = Cast[DstT=DT_FLOAT, SrcT=DT_STRING, Truncate=false, _device="/job:localhost/replica:0/task:0/device:CPU:0"](dnn/input_from_feature_columns/input_layer/Gender/ExpandDims)]]

当我尝试运行我的神经网络时 . 我试图解决它,但找不到任何解决方案 . 真的很感激有人可以弄清楚为什么会出现这种错误 . 我相信这与我的数据集和功能有关,但我不知道 .

neuralnetwork_1.py:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import tensorflow as tf

import livercancer_data


parser = argparse.ArgumentParser()
parser.add_argument('--batch_size', default=100, type=int, help='batch size')
parser.add_argument('--train_steps', default=1000, type=int,
                    help='number of training steps')

def main(argv):
    args = parser.parse_args(argv[1:])

    # Fetch the data
    (train_x, train_y), (test_x, test_y) = livercancer_data.load_data()

    # Feature columns describe how to use the input.
    my_feature_columns = []
    for key in train_x.keys():
        my_feature_columns.append(tf.feature_column.numeric_column(key=key))

    # Build 2 hidden layer DNN with 10, 10 units respectively.
    classifier = tf.estimator.DNNClassifier(
        feature_columns=my_feature_columns,
        # Two hidden layers of 10 nodes each.
        hidden_units=[22, 22],
        # The model must choose between 3 classes.
        n_classes=2)

    # Train the Model.
    classifier.train(
        input_fn=lambda:livercancer_data.train_input_fn(train_x, train_y,
                                                 args.batch_size),
        steps=args.train_steps)

    # Evaluate the model.
    eval_result = classifier.evaluate(
        input_fn=lambda:livercancer_data.eval_input_fn(test_x, test_y,
                                                args.batch_size))

    print('\nTest set accuracy: {accuracy:0.3f}\n'.format(**eval_result))

    # Generate predictions from the model
    expected = ['Yes', 'No', 'Yes']
    predict_x = {
        'Age': [46, 39, 60],
        'Gender': [1, 0, 0],
        'TB': [1.4, 1.6, 19.6],
        'DB': [0.4, 0.8, 9.5],
        'Alkphos': [298, 230, 466],
        'Sgpt': [509, 88, 46],
        'Sgot': [623, 74, 52],
        'TP': [3.6, 8, 6.1],
        'ALB': [1, 4, 2],
        'AGRatio': [0.3, 1, 0.4],
    }



    predictions = classifier.predict(
        input_fn=lambda:livercancer_data.eval_input_fn(predict_x,
                                                labels=None,
                                                batch_size=args.batch_size))

    template = ('\nPrediction is "{}" ({:.1f}%), expected "{}"')

    for pred_dict, expec in zip(predictions, expected):
        class_id = pred_dict['class_ids'][0]
        probability = pred_dict['probabilities'][class_id]

        print(template.format(livercancer_data.SPECIES[class_id],
                              100 * probability, expec))


if __name__ == '__main__':
    tf.logging.set_verbosity(tf.logging.INFO)
    tf.app.run(main)

livercancer_data.py:

import pandas as pd
import tensorflow as tf

TRAIN_URL = "file:///Users/andyjiang/Desktop/Neural%20Network/livercancer_trainset.csv"
TEST_URL = "file:///Users/andyjiang/Desktop/Neural%20Network/livercancer_testset.csv"

CSV_COLUMN_NAMES = ['Age', 'Gender', 'TB', 'DB', 'Alkphos', 'Sgpt', 'Sgot', 'TP', 'ALB', 'AGRatio', 'Diagonsis']
DIAGONSIS = ['Yes', 'No']

def maybe_download():
    train_path = tf.keras.utils.get_file(TRAIN_URL.split('/')[-1], TRAIN_URL)
    test_path = tf.keras.utils.get_file(TEST_URL.split('/')[-1], TEST_URL)

    return train_path, test_path

def load_data(y_name='Diagonsis'):
    """Returns the iris dataset as (train_x, train_y), (test_x, test_y)."""
    train_path, test_path = maybe_download()

    train = pd.read_csv(train_path, names=CSV_COLUMN_NAMES, header=0)
    train_x, train_y = train, train.pop(y_name)


    test = pd.read_csv(test_path, names=CSV_COLUMN_NAMES, header=0)
    test_x, test_y = test, test.pop(y_name)


    return (train_x, train_y), (test_x, test_y)


def train_input_fn(features, labels, batch_size):
    """An input function for training"""
    # Convert the inputs to a Dataset.
    dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels))

    # Shuffle, repeat, and batch the examples.
    dataset = dataset.shuffle(1000).repeat().batch(batch_size)

    # Return the dataset.
    return dataset


def eval_input_fn(features, labels, batch_size):
    """An input function for evaluation or prediction"""
    features=dict(features)
    if labels is None:
        # No labels, use only features.
        inputs = features
    else:
        inputs = (features, labels)

    # Convert the inputs to a Dataset.
    dataset = tf.data.Dataset.from_tensor_slices(inputs)

    # Batch the examples
    assert batch_size is not None, "batch_size must not be None"
    dataset = dataset.batch(batch_size)

    # Return the dataset.
    return dataset


# The remainder of this file contains a simple example of a csv parser,
#     implemented using the `Dataset` class.

# `tf.parse_csv` sets the types of the outputs to match the examples given in
#     the `record_defaults` argument.
CSV_TYPES = [[0], [0], [0.0], [0.0], [0], [0], [0], [0.0], [0.0], [0.0], [0]]

def _parse_line(line):
    # Decode the line into its fields
    fields = tf.decode_csv(line, record_defaults=CSV_TYPES)

    # Pack the result into a dictionary
    features = dict(zip(CSV_COLUMN_NAMES, fields))

    # Separate the label from the features
    label = features.pop('Diagonsis')

    return features, label


def csv_input_fn(csv_path, batch_size):
    # Create a dataset containing the text lines.
    dataset = tf.data.TextLineDataset(csv_path).skip(1)

    # Parse each line.
    dataset = dataset.map(_parse_line)

    # Shuffle, repeat, and batch the examples.
    dataset = dataset.shuffle(1000).repeat().batch(batch_size)

    # Return the dataset.
    return dataset

完全错误:

Caused by op 'dnn/input_from_feature_columns/input_layer/Gender/ToFloat', defined at:
  File "neuralnetwork_1.py", line 82, in <module>
    tf.app.run(main)
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/platform/app.py", line 125, in run
    _sys.exit(main(argv))
  File "neuralnetwork_1.py", line 39, in main
    steps=args.train_steps)
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py", line 354, in train
    loss = self._train_model(input_fn, hooks, saving_listeners)
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py", line 1207, in _train_model
    return self._train_model_default(input_fn, hooks, saving_listeners)
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py", line 1237, in _train_model_default
    features, labels, model_fn_lib.ModeKeys.TRAIN, self.config)
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py", line 1195, in _call_model_fn
    model_fn_results = self._model_fn(features=features, **kwargs)
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/estimator/canned/dnn.py", line 486, in _model_fn
    shared_state_manager=shared_state_manager)
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/estimator/canned/dnn.py", line 300, in _dnn_model_fn
    logits = logit_fn(features=features, mode=mode)
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/estimator/canned/dnn.py", line 109, in dnn_logit_fn
    return dnn_model(features, mode)
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer.py", line 757, in __call__
    outputs = self.call(inputs, *args, **kwargs)
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/estimator/canned/dnn.py", line 204, in call
    net = self._input_layer(features)
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/feature_column/feature_column.py", line 333, in __call__
    from_template=True)
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/ops/template.py", line 368, in __call__
    return self._call_func(args, kwargs)
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/ops/template.py", line 311, in _call_func
    result = self._func(*args, **kwargs)
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/feature_column/feature_column.py", line 222, in _internal_input_layer
    return _get_logits()
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/feature_column/feature_column.py", line 201, in _get_logits
    trainable=trainable)
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/feature_column/feature_column.py", line 2500, in _get_dense_tensor
    return inputs.get(self)
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/feature_column/feature_column.py", line 2289, in get
    transformed = column._transform_feature(self)  # pylint: disable=protected-access
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/feature_column/feature_column.py", line 2475, in _transform_feature
    return math_ops.to_float(input_tensor)
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/ops/math_ops.py", line 732, in to_float
    return cast(x, dtypes.float32, name=name)
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/ops/math_ops.py", line 677, in cast
    x = gen_math_ops.cast(x, base_type, name=name)
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/ops/gen_math_ops.py", line 1659, in cast
    "Cast", x=x, DstT=DstT, Truncate=Truncate, name=name)
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py", line 488, in new_func
    return func(*args, **kwargs)
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 3274, in create_op
    op_def=op_def)
  File "/Users/andyjiang/project/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1770, in __init__
    self._traceback = tf_stack.extract_stack()

UnimplementedError (see above for traceback): Cast string to float is not supported
     [[node dnn/input_from_feature_columns/input_layer/Gender/ToFloat (defined at neuralnetwork_1.py:39)  = Cast[DstT=DT_FLOAT, SrcT=DT_STRING, Truncate=false, _device="/job:localhost/replica:0/task:0/device:CPU:0"](dnn/input_from_feature_columns/input_layer/Gender/ExpandDims)]]

数据集:

https://archive.ics.uci.edu/ml/machine-learning-databases/00225/Indian%20Liver%20Patient%20Dataset%20(ILPD).csv