Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0125-preview· OpenAIAi2 WildChat-4.8M (AI2)

code: %% from sklearn.preprocessing import StandardScaler import numpy as np from…

  1. User

    code:

    %%

    from sklearn.preprocessing import StandardScaler import numpy as np from sklearn.preprocessing import StandardScaler

    %%

    import pandas as pd

    chunk_size = 10000 # This depends on your available memory batch_size = 72

    %%

    def data_generator(): reader = pd.read_csv(r"C:\Users\arisa\Desktop\combined_day.csv", chunksize=chunk_size) for chunk in reader:

        X = chunk.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 = chunk[['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']].values
        xScaler = StandardScaler()
        yScaler = StandardScaler()
        X_scaled = xScaler.fit_transform(X)
        Y_scaled = yScaler.fit_transform(Y)
        # Yield batches
        for i in range(0, len(X_scaled), batch_size):
            X_batch = X_scaled.iloc[i:i+batch_size]
            y_batch = Y_scaled[i:i+batch_size]
            yield np.array(X_batch), np.array(y_batch)
    

    %%

    from tensorflow.keras.layers import Dense, Dropout from tensorflow.keras import Model from tensorflow.keras.layers import Input, Dropout

    def build_model(): input_shape = (6427,)

    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)
    
    # Constructing the model
    model = Model(inputs=inputs, outputs=[
        out_high_1d, out_low_1d, out_priority_1d,out_high_2d, out_low_2d, out_priority_2d,
        out_high_3d, out_low_3d, out_priority_3d,out_high_5d, out_low_5d, out_priority_5d])
    
    model.compile(optimizer='adam',
                  loss={
                    'high_output_1d': 'mse', 'low_output_1d': 'mse', 'priority_output_1d': 'binary_crossentropy',
                    'high_output_2d': 'mse', 'low_output_2d': 'mse', 'priority_output_2d': 'binary_crossentropy',
                    'high_output_3d': 'mse', 'low_output_3d': 'mse', 'priority_output_3d': 'binary_crossentropy',
                    'high_output_5d': 'mse', 'low_output_5d': 'mse', 'priority_output_5d': 'binary_crossentropy'
                  },
                  metrics={
                    'high_output_1d': ['mae'], 'low_output_1d': ['mae'], 'priority_output_1d': ['accuracy'],
                    'high_output_2d': ['mae'], 'low_output_2d': ['mae'], 'priority_output_2d': ['accuracy'],
                    'high_output_3d': ['mae'], 'low_output_3d': ['mae'], 'priority_output_3d': ['accuracy'],
                    'high_output_5d': ['mae'], 'low_output_5d': ['mae'], 'priority_output_5d': ['accuracy']
                  },
                  loss_weights={
                    'high_output_1d': 1.0, 'low_output_1d': 1.0, 'priority_output_1d': 1.0,
                    'high_output_2d': 1.0, 'low_output_2d': 1.0, 'priority_output_2d': 1.0,
                    'high_output_3d': 1.0, 'low_output_3d': 1.0, 'priority_output_3d': 1.0,
                    'high_output_5d': 1.0, 'low_output_5d': 1.0, 'priority_output_5d': 1.0
                  }
                  )
    return model
    

    %%

    model = build_model()

    history = model.fit(data_generator(), steps_per_epoch=100, epochs=10)

    error: { "name": "AttributeError", "message": "'numpy.ndarray' object has no attribute 'iloc'", "stack": "--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[35], line 3 1 model = build_model() ----> 3 history = model.fit(data_generator(), steps_per_epoch=100, epochs=10)

    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

    Cell In[34], line 21, in data_generator() 19 # Yield batches 20 for i in range(0, len(X_scaled), batch_size): ---> 21 X_batch = X_scaled.iloc[i:i+batch_size] 22 y_batch = Y_scaled[i:i+batch_size] 23 yield np.array(X_batch), np.array(y_batch)

    AttributeError: 'numpy.ndarray' object has no attribute 'iloc'" }

  2. Assistant

    The error you're encountering:

    AttributeError: 'numpy.ndarray' object has no attribute 'iloc'
    

    is due to trying to use the .iloc method on a NumPy array (X_scaled), which is not a valid operation. The .iloc method is specific to Pandas DataFrames, not NumPy arrays.

    To fix this error, you can simply use slicing without .iloc since X_scaled is already a NumPy array due to the call to fit_transform() which returns a NumPy array and not a Pandas DataFrame.

    Replace:

    X_batch = X_scaled.iloc[i:i+batch_size]
    

    with

    X_batch = X_scaled[i:i+batch_size]
    

    So, the revised part of your data_generator function should look like this:

    def data_generator():
        reader = pd.read_csv(r"C:\Users\arisa\Desktop\combined_day.csv", chunksize=chunk_size)
        for chunk in reader:
            
            X = chunk.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 = chunk[['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']].values
            xScaler = StandardScaler()
            yScaler = StandardScaler()
            X_scaled = xScaler.fit_transform(X)
            Y_scaled = yScaler.fit_transform(Y)
            # Yield batches
            for i in range(0, len(X_scaled), batch_size):
                X_batch = X_scaled[i:i+batch_size]
                y_batch = Y_scaled[i:i+batch_size]
                yield np.array(X_batch), np.array(y_batch)
    

    This fix will solve the AttributeError you're facing by correctly slicing the NumPy array without attempting to use DataFrame-specific methods.

  3. User

    new error: { "name": "OperatorNotAllowedInGraphError", "message": "Iterating over a symbolic tf.Tensor is not allowed. You can attempt the following resolutions to the problem: If you are running in Graph mode, use Eager execution mode or decorate this function with @tf.function. If you are using AutoGraph, you can try decorating this function with @tf.function. If that does not work, then you may be using an unsupported feature or your source code may not be visible to AutoGraph. See https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/autograph/g3doc/reference/limitations.md#access-to-source-code for more information.", "stack": "--------------------------------------------------------------------------- OperatorNotAllowedInGraphError Traceback (most recent call last) Cell In[41], line 3 1 model = build_model() ----> 3 history = model.fit(data_generator(), steps_per_epoch=100, epochs=10)

    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\trainers\compile_utils.py:561, in CompileLoss.build(self, y_true, y_pred) 553 if not is_function_like(loss[name]): 554 raise ValueError( 555 "For a model with multiple outputs, " 556 "when providing the loss argument as a dict, " (...) 559 f"At key '{name}', received invalid type:
    {loss[name]}" 560 ) --> 561 for name, yt, yp in zip(output_names, y_true, y_pred): 562 if name in loss: 563 if loss[name]:

    OperatorNotAllowedInGraphError: Iterating over a symbolic tf.Tensor is not allowed. You can attempt the following resolutions to the problem: If you are running in Graph mode, use Eager execution mode or decorate this function with @tf.function. If you are using AutoGraph, you can try decorating this function with @tf.function. If that does not work, then you may be using an unsupported feature or your source code may not be visible to AutoGraph. See https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/autograph/g3doc/reference/limitations.md#access-to-source-code for more information." }

  4. Assistant

    The error message you encountered:

    OperatorNotAllowedInGraphError: Iterating over a symbolic `tf.Tensor` is not allowed...
    

    suggests an issue related to TensorFlow's execution mode and how the tensors are being handled. The error is indicative of TensorFlow's graph execution mode encountering an operation that requires eager execution or behavior that mimics Pythonic control flow, which is not directly transferable to the static computation graph.

    Potential Causes and Solutions:

    1. Mismatch in Output Format: When using a custom data generator with a model that has multiple outputs (as in your case), ensure that the generator yields data in a format that matches what the model expects. Specifically, for models with multiple outputs, the generator should yield a tuple (input_data, output_data_dict) where input_data is the input feature array and output_data_dict is a dictionary mapping output names to their respective arrays.

      Ensure data_generator yields outputs in a way that matches the named outputs of your model. Each batch should return X_batch and a dictionary for y_batch where keys are the names of the output layers. There wasn't a conversion of your y_batch into a dictionary for multiple outputs, which might have contributed to the issue.

    2. Compatibility with TensorFlow's Execution Model: The error suggests there's iteration over a symbolic tensor in a way that's not compatible with TensorFlow's static graph execution. Ensure your TensorFlow execution is eager (which is default in recent TensorFlow versions). If you're using an older version of TensorFlow where eager execution is not the default, you could explicitly enable it:

      import tensorflow as tf
      tf.compat.v1.enable_eager_execution()
      

      However, for TensorFlow 2.x, eager execution is enabled by default. So, if you're using TensorFlow 2.x, this would typically not be the issue.

    Modifying the Generator for Multiple Outputs:

    Without seeing the exact way you're formatting the output of your generator, the general approach for a model with multiple outputs is to yield inputs and a dictionary for outputs where the keys match your output layer names. Here's how you might modify the yield statement to work with your model's multiple outputs (assuming Y_scaled can be partitioned appropriately):

    def data_generator():
        ...
        for i in range(0, len(X_scaled), batch_size):
            X_batch = X_scaled[i:i + batch_size]
            y_batch = { 
                'high_output_1d': Y_scaled[i:i + batch_size, 0],
                'low_output_1d': Y_scaled[i:i + batch_size, 1],
                'priority_output_1d': Y_scaled[i:i + batch_size, 2],
                'high_output_2d': Y_scaled[i:i + batch_size, 3],
                'low_output_2d': Y_scaled[i:i + batch_size, 4],
                # Continue for all needed outputs...
            }
            yield np.array(X_batch), y_batch
    

    Review the Generator and Model Structure:

    • Ensure the generator yields data in the correct format expected by the model.
    • Review the model.fit() call to ensure it's properly set up to handle the data format provided by the generator.

    If these suggestions do not resolve the issue, it could be useful to share more details about the TensorFlow version you're using, as some behaviors and best practices might vary between versions.

  5. User

    gimme full code of y_batch = { ‘high_output_1d’: Y_scaled[i:i + batch_size, 0], ‘low_output_1d’: Y_scaled[i:i + batch_size, 1], ‘priority_output_1d’: Y_scaled[i:i + batch_size, 2], ‘high_output_2d’: Y_scaled[i:i + batch_size, 3], ‘low_output_2d’: Y_scaled[i:i + batch_size, 4], # Continue for all needed outputs… }

  6. Assistant

    Certainly, based on the structure of your data_generator and the output layer names provided in your model definition, here's how you can reform the y_batch as a dictionary to correctly match the expected output format for a model trained with multiple outputs.

    This adjustment ensures that each generated batch of data yields a structured output that aligns with the named outputs of your model. Given your model's configuration, here's the full adjustment within the data_generator function:

    def data_generator():
        reader = pd.read_csv(r"C:\Users\arisa\Desktop\combined_day.csv", chunksize=chunk_size)
        for chunk in reader:
            
            X = chunk.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 = chunk[['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']].values
            xScaler = StandardScaler()
            yScaler = StandardScaler()
            X_scaled = xScaler.fit_transform(X)
            Y_scaled = yScaler.fit_transform(Y)
            # Yield batches
            for i in range(0, len(X_scaled), batch_size):
                X_batch = X_scaled[i:i+batch_size]
                y_batch = {
                    'high_output_1d': Y_scaled[i:i + batch_size, 0],
                    'low_output_1d': Y_scaled[i:i + batch_size, 1],
                    'priority_output_1d': Y_scaled[i:i + batch_size, 2],
                    'high_output_2d': Y_scaled[i:i + batch_size, 3],
                    'low_output_2d': Y_scaled[i:i + batch_size, 4],
                    'priority_output_2d': Y_scaled[i:i + batch_size, 5],
                    'high_output_3d': Y_scaled[i:i + batch_size, 6],
                    'low_output_3d': Y_scaled[i:i + batch_size, 7],
                    'priority_output_3d': Y_scaled[i:i + batch_size, 8],
                    'high_output_5d': Y_scaled[i:i + batch_size, 9],
                    'low_output_5d': Y_scaled[i:i + batch_size, 10],
                    'priority_output_5d': Y_scaled[i:i + batch_size, 11],
                }
                yield np.array(X_batch), y_batch
    

    This code block takes into account the 12 outputs you've defined in your model architecture. Make sure the indices and names used in y_batch match exactly with those you've specified for your model outputs. For clarity and to prevent any mistakes, ensure the column selection in the Y extraction (chunk[['y_High_1d', 'y_Low_1d', ...]]) aligns perfectly with the expected order and number of outputs in your model.

    The goal is to have each element in y_batch map directly to the corresponding output layers of your model, with the dictionary keys exactly matching the names of the output layers. This approach facilitates TensorFlow's handling of multiple-output models, enabling it to correctly pair each portion of the generated target data with its corresponding model output for training.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.