[Python] Problem with fitting a neural network model on binary classification data

Discussão em 'Python' iniciado por Stack, Outubro 5, 2024.

  1. Stack

    Stack Membro Participativo

    I have a dataset of 280 samples with 20 features and 0,1 results. I scaled them.

    Also, having three neural network models to train data on them.

    But while looping on models I receive an error with fitting.

    How to resolve it?

    import numpy as np
    import math

    import tensorflow as tf

    from sklearn.linear_model import LinearRegression
    from sklearn.preprocessing import StandardScaler,PolynomialFeatures
    from sklearn.model_selection import train_test_split
    from sklearn.metrics import mean_squared_error
    from tensorflow.keras.losses import binary_crossentropy
    from tensorflow.keras.optimizers import Adam


    from tensorflow.keras.models import Sequential
    from tensorflow.keras.layers import Dense


    model1 = Sequential([
    Dense(units=25, activation='relu'),
    Dense(units=15, activation='relu'),
    Dense(units=1, activation='linear')
    ])
    model2 = Sequential([
    Dense(units=20, activation='relu'),
    Dense(units=12, activation='relu'),
    Dense(units=12, activation='relu'),
    Dense(units=20, activation='relu'),
    Dense(units=1, activation='linear')
    ])
    model3 = Sequential([
    Dense(units=32, activation='relu'),
    Dense(units=16, activation='relu'),
    Dense(units=8, activation='relu'),
    Dense(units=4, activation='relu'),
    Dense(units=12, activation='relu'),
    Dense(units=1, activation='linear')
    ])


    nn_train_error = []
    nn_cv_error = []

    models_bc = [model1, model2, model3]
    for model in models_bc:

    # setup the loss and optimizer
    model.compile(
    loss = tf.keras.losses.BinaryCrossentropy(from_logits=True),
    optimizer = tf.keras.optimizers.Adam(learning_rate=0.01)
    )

    print(f"Training {model.name}...")
    # train the model
    model.fit(x_bc_train_scaled, y_bc_train, epochs=100, verbose=0)
    print("Done!\n")

    # Set the threshold for classification
    threshold = 0.5

    # Record the fraction of misclassified examples for the training set
    yhat = model.predict(x_bc_train_scaled)
    yhat = tf.math.sigmoid(yhat)
    yhat = np.where(yhat >= threshold, 1, 0) # where in np : condition function
    train_error = np.mean(yhat != y_bc_train) # mean in np : show the percent of misclassified

    nn_train_error.append(train_error)

    # Record the fraction of misclassified examples for the cross validation set
    yhat = model.predict(x_bc_cv_scaled)
    yhat = tf.math.sigmoid(yhat)
    yhat = np.where(yhat >= threshold, 1, 0)
    cv_error = np.mean(yhat != y_bc_cv)

    nn_cv_error.append(cv_error)

    print(nn_train_error)
    print(nn_cv_error)


    output:

    ValueError Traceback (most recent call
    last) Cell In\[109\], line 15 13 print(f"Training
    {model.name}...") 14 # train the model ---\> 15
    model.fit(x_bc_train_scaled, y_bc_train, epochs=100, verbose=0)
    16 print("Done!\\n")


    Arguments received by Sequential.call():

    • inputs=tf.Tensor(shape=(None, 20), dtype=float32)
    • training=True
    • mask=None

    Continue reading...

Compartilhe esta Página