python - TensorFlow:“UnimplementedError:不支持将字符串转换为浮点数”
问题描述
我有一个正在尝试创建的多输入网络。每个输入都有其各自的 dtype。我有 4 个字符串张量和 2 个浮点张量。输出也是一个字符串张量。我似乎无法找到导致错误的确切原因。当我尝试训练我的模型时也会发生错误。
Training model....
Epoch 1/200
---------------------------------------------------------------------------
UnimplementedError Traceback (most recent call last)
<ipython-input-128-38584befa568> in <module>
1 # Train Model
2 print('Training model....')
----> 3 model.fit(x=[Date_Train_Input, Team_One_Train_Input, Team_Two_Train_Input, Team_One_Stats_Train_Input, Team_Two_Stats_Train_Input],
4 y=Train_Output,
5 validation_data=([Date_Input_Validate, Team_One_Input_Validate, Team_Two_Input_Validate, Team_One_Stats_Input_Validate, Team_Two_Stats_Input_Validate], Output_Validate),
~/Documents/Python Projects/.venv/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)
1098 _r=1):
1099 callbacks.on_train_batch_begin(step)
-> 1100 tmp_logs = self.train_function(iterator)
1101 if data_handler.should_sync:
1102 context.async_wait()
~/Documents/Python Projects/.venv/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)
826 tracing_count = self.experimental_get_tracing_count()
827 with trace.Trace(self._name) as tm:
--> 828 result = self._call(*args, **kwds)
829 compiler = "xla" if self._experimental_compile else "nonXla"
830 new_tracing_count = self.experimental_get_tracing_count()
~/Documents/Python Projects/.venv/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)
853 # In this case we have created variables on the first call, so we run the
854 # defunned version which is guaranteed to never create variables.
--> 855 return self._stateless_fn(*args, **kwds) # pylint: disable=not-callable
856 elif self._stateful_fn is not None:
857 # Release the lock early so that multiple threads can perform the call
~/Documents/Python Projects/.venv/lib/python3.8/site-packages/tensorflow/python/eager/function.py in __call__(self, *args, **kwargs)
2940 (graph_function,
2941 filtered_flat_args) = self._maybe_define_function(args, kwargs)
-> 2942 return graph_function._call_flat(
2943 filtered_flat_args, captured_inputs=graph_function.captured_inputs) # pylint: disable=protected-access
2944
~/Documents/Python Projects/.venv/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _call_flat(self, args, captured_inputs, cancellation_manager)
1916 and executing_eagerly):
1917 # No tape is watching; skip to running the function.
-> 1918 return self._build_call_outputs(self._inference_function.call(
1919 ctx, args, cancellation_manager=cancellation_manager))
1920 forward_backward = self._select_forward_and_backward_functions(
~/Documents/Python Projects/.venv/lib/python3.8/site-packages/tensorflow/python/eager/function.py in call(self, ctx, args, cancellation_manager)
553 with _InterpolateFunctionError(self):
554 if cancellation_manager is None:
--> 555 outputs = execute.execute(
556 str(self.signature.name),
557 num_outputs=self._num_outputs,
~/Documents/Python Projects/.venv/lib/python3.8/site-packages/tensorflow/python/eager/execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
57 try:
58 ctx.ensure_initialized()
---> 59 tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
60 inputs, attrs, num_outputs)
61 except core._NotOkStatusException as e:
UnimplementedError: Cast string to float is not supported
[[node model_30/Cast (defined at <ipython-input-124-38584befa568>:3) ]] [Op:__inference_train_function_5842]
Function call stack:
train_function
我已按要求附上了下面的代码。
# Import Necessary Modules
import tensorflow as tf
from openpyxl import load_workbook
import numpy as np
# Import Dataset
workbook = load_workbook('/Users/BOBJOE/Documents/Python Projects/Tensor Flow/ML NBA Predictor/Traning_Data_Redo1.xlsx', read_only=True)
Input_book = workbook['Input Data']
Output_book = workbook['Output Data']
tf_Input = {'Date': [], 'Team One': [], 'Team Two': [], 'Team One Stats': [], 'Team Two Stats': []}
# Organize Input Data
for col in Input_book:
Date = []
Team_One = []
Team_Two = []
Team_One_Stats = []
Team_Two_Stats = []
First_Team = True
for cell in col:
if cell.value is None:
pass
elif isinstance(cell.value, str) and 'T00' in cell.value:
Date.append(cell.value)
elif isinstance(cell.value, str) and len(cell.value) == 3 and 0 == len(Team_One):
Team_One.append(cell.value)
elif isinstance(cell.value, str) and len(cell.value) == 3 and 3 == len(Team_One[0]):
First_Team = False
elif First_Team and isinstance(cell.value, str):
Team_One.append(cell.value)
elif First_Team and isinstance(cell.value, float):
Team_One_Stats.append(cell.value)
elif isinstance(cell.value, str):
Team_Two.append(cell.value)
elif isinstance(cell.value, float):
Team_Two_Stats.append(cell.value)
tf_Input['Date'].append(Date)
tf_Input['Team One'].append(Team_One)
tf_Input['Team Two'].append(Team_Two)
tf_Input['Team One Stats'].append(Team_One_Stats)
tf_Input['Team Two Stats'].append(Team_Two_Stats)
# Make all List Even Sizes
for i in tf_Input['Team One']:
while len(i) < 11:
i.append('No Name')
for i in tf_Input['Team Two']:
while len(i) < 11:
i.append('No Name')
for i in tf_Input['Team One Stats']:
while len(i) < 250:
i.append(0)
for i in tf_Input['Team Two Stats']:
while len(i) < 250:
i.append(0)
for i in tf_Input['Date']:
while len(i) < 1:
i.append('No Date')
# Get Rid of all Nones in List
for i in tf_Input['Team One']:
i = ['No Name' if v is None else v for v in i]
for i in tf_Input['Team Two']:
i = ['No Name' if v is None else v for v in i]
for i in tf_Input['Team One Stats']:
i = [0 if v is None else v for v in i]
for i in tf_Input['Team Two Stats']:
i = [0 if v is None else v for v in i]
for i in tf_Input['Date']:
i = ['No Date' if v is None else v for v in i]
# Clean Output Data
Output_Data_Set = []
for col in Output_book:
Output_List = []
for cell in col:
Output_List.append(str(cell.value))
if len(Output_List) < 4:
Output_List.extend('0')
Output_List = ['0' if v is None else v for v in Output_List]
Output_Data_Set.append(Output_List)
# Split Training Data
Date_Train_Input, Date_Input_Validate, Date_Input_Test = np.split(tf_Input['Date'], [int(len(tf_Input['Date'])*0.6), int(len(tf_Input['Date'])*0.8)])
Team_One_Train_Input, Team_One_Input_Validate, Team_One_Input_Test = np.split(tf_Input['Team One'], [int(len(tf_Input['Team One'])*0.6), int(len(tf_Input['Team One'])*0.8)])
Team_Two_Train_Input, Team_Two_Input_Validate, Team_Two_Input_Test = np.split(tf_Input['Team Two'], [int(len(tf_Input['Team Two'])*0.6), int(len(tf_Input['Team Two'])*0.8)])
Team_One_Stats_Train_Input, Team_One_Stats_Input_Validate, Team_One_Stats_Input_Test = np.split(tf_Input['Team One Stats'], [int(len(tf_Input['Team One Stats'])*0.6), int(len(tf_Input['Team One Stats'])*0.8)])
Team_Two_Stats_Train_Input, Team_Two_Stats_Input_Validate, Team_Two_Stats_Input_Test = np.split(tf_Input['Team Two Stats'], [int(len(tf_Input['Team Two Stats'])*0.6), int(len(tf_Input['Team Two Stats'])*0.8)])
# Split Output Data
Train_Output, Output_Validate, Output_Test = np.split(Output_Data_Set, [int(len(Output_Data_Set)*0.6), int(len(Output_Data_Set)*0.8)])
Train_Output = Train_Output.astype('str')
Date_Train_Input = Date_Train_Input.astype('str')
Team_One_Train_Input = Team_One_Train_Input.astype('str')
Team_Two_Train_Input = Team_Two_Train_Input.astype('str')
Team_One_Stats_Train_Input = Team_One_Stats_Train_Input.astype('float64')
Team_Two_Stats_Train_Input = Team_Two_Stats_Train_Input.astype('float64')
Output_Validate = Output_Validate.astype('str')
Date_Input_Validate = Date_Input_Validate.astype('str')
Team_One_Input_Validate = Team_One_Input_Validate.astype('str')
Team_Two_Input_Validate = Team_Two_Input_Validate.astype('str')
Team_One_Stats_Input_Validate = Team_One_Stats_Input_Validate.astype('float64')
Team_Two_Stats_Input_Validate = Team_Two_Stats_Input_Validate.astype('float64')
# Define Inputs
Date_Input = tf.keras.Input(shape=(1,))
Team_One_Input = tf.keras.Input(shape=(11,))
Team_Two_Input = tf.keras.Input(shape=(11,))
Team_One_Stats_Input = tf.keras.Input(shape=(250,))
Team_Two_Stats_Input = tf.keras.Input(shape=(250,))
# Define Branches for Each Input (Date)
Date = tf.keras.layers.Dense(4, activation='relu')(Date_Input)
Date = tf.keras.Model(inputs=Date_Input, outputs=Date)
# Team One
Team_One = tf.keras.layers.Dense(8, activation='relu')(Team_One_Input)
Team_One = tf.keras.layers.Dense(4, activation='relu')(Team_One)
Team_One = tf.keras.Model(inputs=Team_One_Input, outputs=Team_One)
# Team Two
Team_Two = tf.keras.layers.Dense(8, activation='relu')(Team_Two_Input)
Team_Two = tf.keras.layers.Dense(4, activation='relu')(Team_Two)
Team_Two = tf.keras.Model(inputs=Team_Two_Input, outputs=Team_Two)
# Team One Stats
Team_One_Stats = tf.keras.layers.Dense(125, activation='relu')(Team_One_Stats_Input)
Team_One_Stats = tf.keras.layers.Dense(25, activation='relu')(Team_One_Stats)
Team_One_Stats = tf.keras.layers.Dense(5, activation='relu')(Team_One_Stats)
Team_One_Stats = tf.keras.Model(inputs=Team_One_Stats_Input, outputs=Team_One_Stats)
# Team Two Stats
Team_Two_Stats = tf.keras.layers.Dense(125, activation='relu')(Team_Two_Stats_Input)
Team_Two_Stats = tf.keras.layers.Dense(25, activation='relu')(Team_Two_Stats)
Team_Two_Stats = tf.keras.layers.Dense(5, activation='relu')(Team_Two_Stats)
Team_Two_Stats = tf.keras.Model(inputs=Team_Two_Stats_Input, outputs=Team_Two_Stats)
# Combine the outputs of all branches
combined = tf.keras.layers.concatenate([Date.output, Team_One.output, Team_Two.output, Team_One_Stats.output, Team_Two_Stats.output])
# FC Layer
z = tf.keras.layers.Dense(12, activation='relu')(combined)
z = tf.keras.layers.Dense(4, activation='linear')(z)
# Setup Model
model = tf.keras.Model(inputs=[Date.input, Team_One.input, Team_Two.input, Team_One_Stats.input, Team_Two_Stats.input], outputs=z)
# Optimize
opt = tf.keras.optimizers.Adam(lr=1e-3, decay=1e-3 / 200)
model.compile(loss="mean_absolute_percentage_error", optimizer=opt)
# Convert to Tensor Train Data
Date_Train_Input = tf.convert_to_tensor(Date_Train_Input)
Team_One_Train_Input = tf.convert_to_tensor(Team_One_Train_Input)
Team_Two_Train_Input = tf.convert_to_tensor(Team_Two_Train_Input)
Team_One_Stats_Train_Input = tf.convert_to_tensor(Team_One_Stats_Train_Input)
Team_Two_Stats_Train_Input = tf.convert_to_tensor(Team_Two_Stats_Train_Input)
Train_Output = tf.convert_to_tensor(Train_Output)
# Convert to Tensor Validate
Date_Input_Validate = tf.convert_to_tensor(Date_Input_Validate)
Team_One_Input_Validate = tf.convert_to_tensor(Team_One_Input_Validate)
Team_Two_Input_Validate = tf.convert_to_tensor(Team_Two_Input_Validate)
Team_One_Stats_Input_Validate = tf.convert_to_tensor(Team_One_Stats_Input_Validate)
Team_Two_Stats_Input_Validate = tf.convert_to_tensor(Team_Two_Stats_Input_Validate)
Output_Validate = tf.convert_to_tensor(Output_Validate)
# Train Model
print('Training model....')
model.fit(x=[Date_Train_Input, Team_One_Train_Input, Team_Two_Train_Input, Team_One_Stats_Train_Input, Team_Two_Stats_Train_Input],
y=Train_Output,
validation_data=([Date_Input_Validate, Team_One_Input_Validate, Team_Two_Input_Validate, Team_One_Stats_Input_Validate, Team_Two_Stats_Input_Validate], Output_Validate),
epochs=200)