[Python] How to make my model actually predict something? [closed]

Discussão em 'Python' iniciado por Stack, Março 4, 2025.

  1. Stack

    Stack Membro Participativo

    I wanted to create a model that predicts age based on height, weight and sex of a person. For some reason it predicts always the same thing in test_model() function. In .csv file is everything fine I guess. I create random numbers and then in this code divide them by 1000 to make suitable for sigmoid function. I'm also not sure if I should use sigmoid. I was programming under the instructions of ChatGPT. Here is the code:

    import os
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
    from time import sleep

    import matplotlib.pyplot as plt #pip install matplotlib
    import numpy as np
    import pandas as pd #pip install pandas

    import tensorflow as tf #pip install tensorflow
    from tensorflow.keras import layers
    from tensorflow.keras.saving import register_keras_serializable
    from tensorflow.keras.models import Model, load_model
    from tensorflow.keras.callbacks import EarlyStopping

    @register_keras_serializable()
    class CustomModel(Model):
    def __init__(self, **kwargs):
    super(CustomModel, self).__init__(**kwargs)

    self.dense1 = layers.Dense(64, activation='elu', kernel_regularizer=tf.keras.regularizers.l2(0.01))
    self.dense2 = layers.Dense(32, activation='elu', kernel_regularizer=tf.keras.regularizers.l2(0.01))

    self.output_layer = layers.Dense(1, activation='sigmoid')

    def call(self, inputs):
    x = self.dense1(inputs)
    x = self.dense2(x)
    return self.output_layer(x)

    def get_config(self):
    config = super(CustomModel, self).get_config()
    return config


    def train_model(self, x_train, y_train, batch_size, epochs):
    self.compile(optimizer='adam',
    loss='mse',
    metrics=['mae'])

    history = self.fit(x_train, y_train, batch_size=batch_size, epochs=epochs)
    return history

    def evaluate_model(self, x_test, y_test):
    return self.evaluate(x_test, y_test)

    def predict_data(self, x_test):
    return self.predict(x_test)

    def test_model(self):
    print("Starting test", end="")
    sleep(2)
    print(".", end="")
    sleep(1.5)
    print(".", end="")
    sleep(1.5)
    print(".", end="\n\n")

    while True:
    prediction = 0
    print("Write your age: ", end="")
    age = int(input())
    print("\nWrite your sex (0=Man, 1=Woman): ", end="")
    sex = int(input())
    print("\nWrite your height: ", end="")
    height = int(input())
    print("\nWrite your weight: ")
    weight = int(input())

    prediction = self.predict_data(np.array([[sex, weight, height]]))
    print(f"Model thinks that your age is: {prediction[0][0]}")
    print("Continue? y/n")
    cont = input()
    if cont.lower() == "y":
    continue
    else:
    break


    def main():
    print("Train/Test?")
    todo = input()
    if todo.lower() == "train":
    df_train = pd.read_csv("data/data_train.csv")
    df_train["Weight"] = df_train["Weight"] / 1000
    df_train["Height"] = df_train["Height"] / 1000
    df_train["Age"] = df_train["Age"] / 1000
    X_train = df_train[["Sex", "Weight", "Height"]].values
    y_train = df_train["Age"].values
    model = CustomModel()
    history = model.train_model(X_train, y_train, epochs=2, batch_size=32)
    print("=======================")
    print("=======================")
    df_test = pd.read_csv("data/data_test.csv")
    df_test["Weight"] = df_test["Weight"] / 1000
    df_test["Height"] = df_test["Height"] / 1000
    df_test["Age"] = df_test["Age"] / 1000
    X_test = df_test[["Sex", "Weight", "Height"]].values
    y_test = df_test["Age"].values
    predictions = model.predict_data(X_test)
    test_loss, test_acc = model.evaluate_model(X_test, y_test)

    print(f"Test Loss: {test_loss}")
    print(f"Test Accuracy: {test_acc}")
    model.save("model.keras")
    model.test_model()


    else:
    model = load_model("model.keras")
    model.test_model()




    if __name__ == "__main__":
    main()

    print("Program finished")
    input()

    Continue reading...

Compartilhe esta Página