[Python] why my sklearn LinearRegression keep failing?

Discussão em 'Python' iniciado por Stack, Fevereiro 10, 2025.

  1. Stack

    Stack Membro Participativo

    what is wrong with my code why keep failing? I keep getting this error enter image description here

    the AI checker keep returning

    Hidden Tests Redacted
    One or more test cases in this cell did not pass.


    In [15]:
    Grade cell: cell-0d30204dcfba1c7a
    # Print to check results

    print(f"Mean Squared Error (MSE): {mse}")
    print(f"R-squared: {r_squared}")

    Hidden Tests Redacted

    One or more test cases in this cell did not pass.


    Lab Instructions

    1. Load and Explore the Data Step 1.1: Import the required Python library and load dataset.

    import pandas as myPandas
    import numpy as myNumpy
    from sklearn.model_selection import train_test_split
    from sklearn.linear_model import LinearRegression
    from sklearn.metrics import mean_squared_error, r2_score
    from sklearn.preprocessing import StandardScaler


    mydataframe = myPandas.read_csv("house_prices.csv")

    mydataframe.head()
    mydataframe.info()
    mydataframe.describe()
    mydataframe.dtypes

    missing_values = mydataframe.isnull().sum()

    print("Missing values in each column:\\n", missing_values)

    for column in mydataframe.select_dtypes(include=\['float64', 'int64'\]).columns:
    median_value = mydataframe\[column\].median()
    mydataframe\[column\].fillna(median_value, inplace=True)

    missing_values_after = mydataframe.isnull().sum()
    print("Missing values after filling:\\n", missing_values_after)

    XXX = mydataframe.drop('price', axis=1) # Replace 'Price' with your actual target column name
    yyy = mydataframe\['price'\]

    XXX = myPandas.get_dummies(XXX, drop_first=True)

    Xtrain, Xtest, ytrain, ytest = train_test_split(XXX, yyy, test_size=0.2, random_state=42)

    scaler = StandardScaler()
    Xtrain_scaled = scaler.fit_transform(Xtrain)
    Xtest_scaled = scaler.transform(Xtest)

    mydataframe = myPandas.read_csv('house_prices.csv')

    features = \['sqft_living', 'bedrooms', 'bathrooms', 'condition', 'floors'\]
    target = 'price'

    XXX = mydataframe\[features\]
    yyy = mydataframe\[target\]

    print("Features (X):\\n", XXX.head())
    print("\\nTarget (y):\\n", yyy.head())

    X_encoded = myPandas.get_dummies(XXX, columns=\['condition'\], drop_first=True)
    print(X_encoded.head())


    Step 2.4: Split the Data Split the data into training and testing sets (80% train, 20% test) using train_test_split

    Make sure to set the random_state parameter to 42 to ensure reproducibility and obtain the same results as the expected solution.

    Xtrain, Xtest, ytrain, ytest = train_test_split(
    X_encoded,
    yyy,
    test_size=0.2,
    random_state=42
    )

    print(f"The X train shape: {Xtrain.shape}")
    print(f"The y train shape: {ytrain.shape}")
    print(f"The X test shape: {Xtest.shape}")
    print(f"The y test shape: {ytest.shape}")

    print(f'Training the shape: {Xtrain.shape}, Testing the shape: {Xtest.shape}')


    Build and Train a Linear Regression Model Step 3.1: Import LinearRegression

    from sklearn.linear_model import LinearRegression


    Step 3.2: Create an Instance of the Model Create an instance of the LinearRegression model.

    model = LinearRegression()


    Step 3.3: Fit the Model Fit the model to the training data.

    model.fit(Xtrain, ytrain)
    print("Coefficients is as follow:", model.coef\_)
    print("Intercept is as follow:", model.intercept\_)

    1. Make Predictions and Evaluate the Model Step 4.1: Make Predictions Use the trained model to make predictions on the testing data.

    ypred = model.predict(Xtest)
    predictions_mydataframe = myPandas.DataFrame({'Actual': ytest, 'Predicted': ypred})
    print(predictions_mydataframe.head())


    Step 4.2: Evaluate the Model Calculate the Mean Squared Error (MSE) as mse and R-squared value as r_squared to evaluate the model's performance, then check your results by printing them in the following cell.

    from sklearn.metrics import mean_squared_error, r2_score

    mse = mean_squared_error(ytest, ypred)
    r_mse = myNumpy.sqrt(mse)

    r_squared = r2_score(ytest, ypred)


    print(f'Mean Squared Error (MSE): {mse}')
    print(f'R-squared (R²): {r_squared}')

    Continue reading...

Compartilhe esta Página