import os
import numpy as np
import pandas as pd
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.layers import Input, Dropout
from tensorflow.keras import Model
%%
def data_generator(file_paths, batch_size, train=True, scaler=None):
while True: # Loop forever so the generator never terminates
# Shuffle file paths to ensure random distribution of data across files
np.random.shuffle(file_paths)
for file_path in file_paths:
data = pd.read_csv(file_path)
# Split features and labels
X = data.drop([
'Date', 'Symbol',
'y_High_1d', 'y_Low_1d', 'y_Priority_1d',
'y_High_2d', 'y_Low_2d', 'y_Priority_2d',
'y_High_3d', 'y_Low_3d', 'y_Priority_3d',
'y_High_5d', 'y_Low_5d', 'y_Priority_5d'], axis=1).values
y_high_1d = data['y_High_1d'].values
y_low_1d = data['y_Low_1d'].values
y_priority_1d = data['y_Priority_1d'].values
y_high_2d = data['y_High_2d'].values
y_low_2d = data['y_Low_2d'].values
y_priority_2d = data['y_Priority_2d'].values
y_high_3d = data['y_High_3d'].values
y_low_3d = data['y_Low_3d'].values
y_priority_3d = data['y_Priority_3d'].values
y_high_5d = data['y_High_5d'].values
y_low_5d = data['y_Low_5d'].values
y_priority_5d = data['y_Priority_5d'].values
# Optionally, apply preprocessing here (e.g., Scaler transform)
if scaler is not None and train:
X = scaler.fit_transform(X)
elif scaler is not None:
X = scaler.transform(X)
# Splitting data into batches
for i in range(0, len(data), batch_size):
end = i + batch_size
X_batch = X[i:end]
y_high_batch_1d = y_high_1d[i:end]
y_low_batch_1d = y_low_1d[i:end]
y_priority_batch_1d = y_priority_1d[i:end]
y_high_batch_2d = y_high_2d[i:end]
y_low_batch_2d = y_low_2d[i:end]
y_priority_batch_2d = y_priority_2d[i:end]
y_high_batch_3d = y_high_3d[i:end]
y_low_batch_3d = y_low_3d[i:end]
y_priority_batch_3d = y_priority_3d[i:end]
y_high_batch_5d = y_high_5d[i:end]
y_low_batch_5d = y_low_5d[i:end]
y_priority_batch_5d = y_priority_5d[i:end]
yield X_batch, [y_high_batch_1d, y_low_batch_1d,y_priority_batch_1d,
y_high_batch_2d, y_low_batch_2d,y_priority_batch_2d,
y_high_batch_3d, y_low_batch_3d, y_priority_batch_3d,
y_high_batch_5d, y_low_batch_5d, y_priority_batch_5d]
%%
dataset_dir = r'C:\Users\arisa\Desktop\day_spot'
file_paths = [os.path.join(dataset_dir, file_name) for file_name in os.listdir(dataset_dir)]
train_files, val_files = train_test_split(file_paths, test_size=0.06, random_state=42)
Assistant
User
Assistant
batch_size = 72
%%
Optional: Initialize a scaler for data normalization
inputs = Input(shape=input_shape) # Corrected the input shape specification
x = Dense(6427, activation='relu')(inputs)
x = Dropout(0.25) (x)
x = Dense(3200, activation='relu') (x)
x = Dropout(0.20) (x)
x = Dense(1800, activation='relu') (x)
x = Dropout(0.15) (x)
x = Dense(1024, activation='relu') (x)
x = Dropout(0.10) (x)
x = Dense(512, activation='relu') (x)
x = Dropout(0.05) (x)
x = Dense(256, activation='relu') (x)
x = Dense(128, activation='relu') (x)
x = Dense(64, activation='relu') (x)
x = Dense(32, activation='relu') (x)
Defining three separate outputs
out_high_1d = Dense(1, name='high_output_1d')(x) # No activation, linear output
out_low_1d = Dense(1, name='low_output_1d')(x) # No activation, linear output
out_priority_1d = Dense(1, activation='sigmoid', name='priority_output_1d')(x)
out_high_2d = Dense(1, name='high_output_2d')(x) # No activation, linear output
out_low_2d = Dense(1, name='low_output_2d')(x) # No activation, linear output
out_priority_2d = Dense(1, activation='sigmoid', name='priority_output_2d')(x)
out_high_3d = Dense(1, name='high_output_3d')(x) # No activation, linear output
out_low_3d = Dense(1, name='low_output_3d')(x) # No activation, linear output
out_priority_3d = Dense(1, activation='sigmoid', name='priority_output_3d')(x)
out_high_5d = Dense(1, name='high_output_5d')(x) # No activation, linear output
out_low_5d = Dense(1, name='low_output_5d')(x) # No activation, linear output
out_priority_5d = Dense(1, activation='sigmoid', name='priority_output_5d')(x)
File "c:\Users\arisa\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\data\ops\from_generator_op.py", line 204, in generator_py_func
flattened_values = nest.flatten_up_to(output_types, values)
File "c:\Users\arisa\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\data\util
est.py", line 237, in flatten_up_to
return nest_util.flatten_up_to(
File "c:\Users\arisa\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\util
est_util.py", line 1541, in flatten_up_to
return _tf_data_flatten_up_to(shallow_tree, input_tree)
File "c:\Users\arisa\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\util
est_util.py", line 1570, in _tf_data_flatten_up_to
_tf_data_assert_shallow_structure(shallow_tree, input_tree)
File "c:\Users\arisa\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\util
est_util.py", line 1444, in _tf_data_assert_shallow_structure
_tf_data_assert_shallow_structure(
File "c:\Users\arisa\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\util
est_util.py", line 1414, in _tf_data_assert_shallow_structure
raise TypeError(
TypeError: If shallow structure is a sequence, input must also be a sequence. Input has type: 'list'.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:\Users\arisa\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\ops\script_ops.py", line 270, in call
ret = func(*args)
File "c:\Users\arisa\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\autograph\impl\api.py", line 643, in wrapper
return func(*args, **kwargs)
File "c:\Users\arisa\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\data\ops\from_generator_op.py", line 206, in generator_py_func
raise TypeError(
\t [[{{node PyFunc}}]]
\t [[IteratorGetNext]] [Op:__inference_one_step_on_iterator_7596]",
"stack": "---------------------------------------------------------------------------
InvalidArgumentError Traceback (most recent call last)
Cell In[31], line 12
3 validation_steps = np.ceil(number_of_validation_samples / batch_size).astype(int) # Replace number_of_validation_samples
5 # model.fit(train_gen,
6 # steps_per_epoch=steps_per_epoch,
7 # validation_data=val_gen,
(...)
10
11 # Then use these datasets in your model.fit call
---> 12 model.fit(train_dataset,
13 steps_per_epoch=steps_per_epoch,
14 validation_data=val_dataset,
15 validation_steps=validation_steps,
16 epochs=1000)
File c:\Users\arisa\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\src\utils\traceback_utils.py:122, in filter_traceback..error_handler(*args, **kwargs)
119 filtered_tb = _process_traceback_frames(e.traceback)
120 # To get the full stack trace, call:
121 # keras.config.disable_traceback_filtering()
--> 122 raise e.with_traceback(filtered_tb) from None
123 finally:
124 del filtered_tb
File c:\Users\arisa\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\eager\execute.py:53, in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
51 try:
52 ctx.ensure_initialized()
---> 53 tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
54 inputs, attrs, num_outputs)
55 except core._NotOkStatusException as e:
56 if name is not None:
File "c:\Users\arisa\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\data\ops\from_generator_op.py", line 204, in generator_py_func
flattened_values = nest.flatten_up_to(output_types, values)
File "c:\Users\arisa\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\data\util
est.py", line 237, in flatten_up_to
return nest_util.flatten_up_to(
File "c:\Users\arisa\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\util
est_util.py", line 1541, in flatten_up_to
return _tf_data_flatten_up_to(shallow_tree, input_tree)
File "c:\Users\arisa\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\util
est_util.py", line 1570, in _tf_data_flatten_up_to
_tf_data_assert_shallow_structure(shallow_tree, input_tree)
File "c:\Users\arisa\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\util
est_util.py", line 1444, in _tf_data_assert_shallow_structure
_tf_data_assert_shallow_structure(
File "c:\Users\arisa\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\util
est_util.py", line 1414, in _tf_data_assert_shallow_structure
raise TypeError(
TypeError: If shallow structure is a sequence, input must also be a sequence. Input has type: 'list'.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:\Users\arisa\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\ops\script_ops.py", line 270, in call
ret = func(*args)
File "c:\Users\arisa\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\autograph\impl\api.py", line 643, in wrapper
return func(*args, **kwargs)
File "c:\Users\arisa\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\data\ops\from_generator_op.py", line 206, in generator_py_func
raise TypeError(
The error you're encountering is related to the structure of the data being yielded by your generator and the expected structure defined by your output_signature. Specifically, TensorFlow expects the generator to yield tuples in a specific structure that matches the definition in output_signature, but there's a discrepancy in what's being yielded.
It appears the core issue is how the outputs (targets) are being yielded from the generator and how they're defined in the output_signature. The error message indicates that TensorFlow is expecting a structure of (tf.float32, ([tf.float32, ...])), which means a tuple containing an input and a tuple of outputs, but instead, it's receiving a different structure.
Before diving into specific solutions, it's critical to ensure that each yield statement in your generator matches exactly with the structure defined in output_signature. Here's a simplified example of what TensorFlow is expecting based on your output_signature:
Given the complexity of your generator and the detailed structure expected, please double-check the following:
Matching Structure: Ensure that when the generator yields batches, it yields them in a structure exactly matching the output_signature. From the error message, it seems there's a mismatch – likely around how the labels/targets are being structured.
Nested Tuples for Outputs: Your model has multiple outputs, which means you should be yielding a single input array and then a tuple of arrays for each output in the exact order your model expects. From the error log, it's clear TensorFlow is not recognizing the yielded outputs as a proper sequence (tuple) of arrays.
Considering these points, the immediate solution would involve adjusting the yield part of your generator to match the expected structure precisely. Here's a sketch of how you might adjust the yielding part of your generator:
Make sure the order and structure of these yielded items exactly match what you specified in output_signature, including ensuring each target (y) is correctly structured as individual elements of a tuple and not as a list of arrays. The structure of the yield statement must be a tuple where the first element is your input batch and the second element is a tuple containing all the output batches in order.
Lastly, review your output_signature to confirm it accurately reflects this structure. Each tf.TensorSpec within should correspond to one of the arrays your generator yields, with the shape and dtype correctly specified.
If the problem persists after these adjustments, systematically debug by simplifying the generator to yield batches for a single output case, then gradually add the complexity back while ensuring the structure always aligns with the output_signature expectation.
i updated the code to:
%%
import os
import numpy as np
import pandas as pd
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.layers import Input, Dropout
from tensorflow.keras import Model
%%
def data_generator(file_paths, batch_size, train=True, scaler=None):
while True: # Loop forever so the generator never terminates
# Shuffle file paths to ensure random distribution of data across files
np.random.shuffle(file_paths)
for file_path in file_paths:
data = pd.read_csv(file_path)
# Split features and labels
X = data.drop([
'Date', 'Symbol',
'y_High_1d', 'y_Low_1d', 'y_Priority_1d',
'y_High_2d', 'y_Low_2d', 'y_Priority_2d',
'y_High_3d', 'y_Low_3d', 'y_Priority_3d',
'y_High_5d', 'y_Low_5d', 'y_Priority_5d'], axis=1).values
y_high_1d = data['y_High_1d'].values
y_low_1d = data['y_Low_1d'].values
y_priority_1d = data['y_Priority_1d'].values
y_high_2d = data['y_High_2d'].values
y_low_2d = data['y_Low_2d'].values
y_priority_2d = data['y_Priority_2d'].values
y_high_3d = data['y_High_3d'].values
y_low_3d = data['y_Low_3d'].values
y_priority_3d = data['y_Priority_3d'].values
y_high_5d = data['y_High_5d'].values
y_low_5d = data['y_Low_5d'].values
y_priority_5d = data['y_Priority_5d'].values
# Optionally, apply preprocessing here (e.g., Scaler transform)
if scaler is not None and train:
X = scaler.fit_transform(X)
elif scaler is not None:
X = scaler.transform(X)
# Splitting data into batches
for i in range(0, len(data), batch_size):
end = i + batch_size
X_batch = X[i:end]
y_high_batch_1d = y_high_1d[i:end]
y_low_batch_1d = y_low_1d[i:end]
y_priority_batch_1d = y_priority_1d[i:end]
y_high_batch_2d = y_high_2d[i:end]
y_low_batch_2d = y_low_2d[i:end]
y_priority_batch_2d = y_priority_2d[i:end]
y_high_batch_3d = y_high_3d[i:end]
y_low_batch_3d = y_low_3d[i:end]
y_priority_batch_3d = y_priority_3d[i:end]
y_high_batch_5d = y_high_5d[i:end]
y_low_batch_5d = y_low_5d[i:end]
y_priority_batch_5d = y_priority_5d[i:end]
yield X_batch, (y_high_batch_1d, y_low_batch_1d,y_priority_batch_1d,
y_high_batch_2d, y_low_batch_2d,y_priority_batch_2d,
y_high_batch_3d, y_low_batch_3d, y_priority_batch_3d,
y_high_batch_5d, y_low_batch_5d, y_priority_batch_5d)
%%
dataset_dir = r'C:\Users\arisa\Desktop\day_spot'
file_paths = [os.path.join(dataset_dir, file_name) for file_name in os.listdir(dataset_dir)]
train_files, val_files = train_test_split(file_paths, test_size=0.06, random_state=42)
batch_size = 72
%%
Optional: Initialize a scaler for data normalization
inputs = Input(shape=input_shape) # Corrected the input shape specification
x = Dense(6427, activation='relu')(inputs)
x = Dropout(0.25) (x)
x = Dense(3200, activation='relu') (x)
x = Dropout(0.20) (x)
x = Dense(1800, activation='relu') (x)
x = Dropout(0.15) (x)
x = Dense(1024, activation='relu') (x)
x = Dropout(0.10) (x)
x = Dense(512, activation='relu') (x)
x = Dropout(0.05) (x)
x = Dense(256, activation='relu') (x)
x = Dense(128, activation='relu') (x)
x = Dense(64, activation='relu') (x)
x = Dense(32, activation='relu') (x)
Defining three separate outputs
out_high_1d = Dense(1, name='high_output_1d')(x) # No activation, linear output
out_low_1d = Dense(1, name='low_output_1d')(x) # No activation, linear output
out_priority_1d = Dense(1, activation='sigmoid', name='priority_output_1d')(x)
out_high_2d = Dense(1, name='high_output_2d')(x) # No activation, linear output
out_low_2d = Dense(1, name='low_output_2d')(x) # No activation, linear output
out_priority_2d = Dense(1, activation='sigmoid', name='priority_output_2d')(x)
out_high_3d = Dense(1, name='high_output_3d')(x) # No activation, linear output
out_low_3d = Dense(1, name='low_output_3d')(x) # No activation, linear output
out_priority_3d = Dense(1, activation='sigmoid', name='priority_output_3d')(x)
out_high_5d = Dense(1, name='high_output_5d')(x) # No activation, linear output
out_low_5d = Dense(1, name='low_output_5d')(x) # No activation, linear output
out_priority_5d = Dense(1, activation='sigmoid', name='priority_output_5d')(x)
and the error changed to:
{
"name": "ValueError",
"message": "Creating variables on a non-first call to a function decorated with tf.function.",
"stack": "---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[40], line 12
3 validation_steps = np.ceil(number_of_validation_samples / batch_size).astype(int) # Replace number_of_validation_samples
5 # model.fit(train_gen,
6 # steps_per_epoch=steps_per_epoch,
7 # validation_data=val_gen,
(...)
10
11 # Then use these datasets in your model.fit call
---> 12 model.fit(train_dataset,
13 steps_per_epoch=steps_per_epoch,
14 validation_data=val_dataset,
15 validation_steps=validation_steps,
16 epochs=1000)
File c:\Users\arisa\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\src\utils\traceback_utils.py:122, in filter_traceback..error_handler(*args, **kwargs)
119 filtered_tb = _process_traceback_frames(e.traceback)
120 # To get the full stack trace, call:
121 # keras.config.disable_traceback_filtering()
--> 122 raise e.with_traceback(filtered_tb) from None
123 finally:
124 del filtered_tb
File c:\Users\arisa\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\src\backend\tensorflow\trainer.py:122, in TensorFlowTrainer.make_train_function..one_step_on_iterator(iterator)
120 """Runs a single training step given a Dataset iterator."""
121 data = next(iterator)
--> 122 outputs = self.distribute_strategy.run(
123 one_step_on_data, args=(data,)
124 )
125 outputs = reduce_per_replica(
126 outputs,
127 self.distribute_strategy,
128 reduction=self.distribute_reduction_method,
129 )
130 return outputs
ValueError: Creating variables on a non-first call to a function decorated with tf.function."
}
The new error you're encountering, "Creating variables on a non-first call to a function decorated with tf.function," typically arises in TensorFlow when an operation that creates variables (like model instantiation or the first forward pass through a neural network) occurs inside a function that's being traced for graph execution (such as inside a tf.function or the first call to a dataset mapping operation where the graph mode is being inferred).
However, this is an unusual error to encounter directly in a call to model.fit with a dataset generated by tf.data.Dataset.from_generator. Here are a few things to consider that might help resolve this issue:
Ensure Consistent Output Shapes: Make sure the shapes defined in output_signature accurately reflect the shapes of the data being yielded by the generator. For instance, your output_signature for X_batch seems to expect a 3D tensor with shape (None, 72, X_batch.shape[1]), but your generator appears to produce batches with X_batch in a different shape. Ensure the first dimension None is truly variable (batch size), and 72 matches your data's expected dimension.
Review Generator Shape Consistency: Directly before yielding, you might want to print or assert the shapes of X_batch and the various y_*_batch_* arrays to confirm they're as expected. Sometimes, discrepancies in these shapes or mismatches with the output_signature can cause TensorFlow to attempt variable creation at inappropriate times.
Variable Creation in tf.function: If there's any logic inside model.fit or related processes (like custom callback functions) that inadvertently attempts to create new TensorFlow variables after the graph execution has started, it could trigger this error. Though it's less common for standard usage of keras model.fit, if you're doing anything unconventional with your model or data processing, it's worth double-checking.
Simplification and Debugging: As a diagnostic step, try simplifying your setup. For instance, test your generator with a much simpler model (even a dummy model) to confirm if the issue is with the dataset or the model logic. Sometimes working backward from a simpler case helps isolate the cause.
Review TensorFlow and Keras Versions: Ensure that your TensorFlow and any other relevant packages are up to date. It's possible that there's a bug or incompatibility in your current version, and updating to the latest version could resolve this issue.
Given the depth and the specific nature of the error, it appears to be more involved with TensorFlow's execution model than a simple misalignment in the data. If these steps do not resolve the issue, consider isolating further by creating a minimal reproducible example that triggers the error and testing in a new, clean environment to rule out environment-specific issues.