KAGGLE FIRST COMPETITION HOUSE IOWA PRICE

Here I will describe my attempts to improve machine learning prediction for the basic house price problem on Kaggle.

ML kaggle competition for house price task with artificial intelligence and Development|lower


IOWA HOUSE PRICE COMPETITION WALKTROUGH

0. First thing to do is to understand your data. Visualize each feature. Count NaNs.

1. I made a basic Random Forest model trained on 37 columns and I get a MAE 17162 starting point.

2. Some columns has NaN values. Thats why I exclude them from training with >>>pandas_dataset.dropna(axis=0) but how could I ignore NaN in training process without dropping the whole column? i would like to chenge NaN with 0.

2.0. To check Nan display(your_dataset_name.info())

2.1. To get list of columns with Nan values use >>> miss = [clm for clm in pandas_dataset.columns if pandas_dataset[clim].isnull().any()]

2.2. Following columns of train dataset contain missing values [LotFrontage, Alley, MasVnrType, MasVnrArea, BsmtQual, BsmtCond, BsmtExposure, BsmtFinType1, BsmtFinType2, Electrical, FireplaceQu, GarageType, GarageYrBlt, GarageFinish, GarageQual, GarageCond, PoolQC, Fence, MiscFeature]

In test dataset [MSZoning, LotFrontage, Alley, Utilities, Exterior1st, Exterior2st, MasVnrType, MasVnrArea, BsmtQual, BsmtCond, BsmtExposure, BsmtFinType1, BsmtFinSF1, BsmtFinType2, BsmtFinSF2, BsmtUnfSF, TotalBsmtSF, BsmtFullBath, BsmthalfBath, KitchenQual, Functional, FireplaceQu, GarageType, GarageYrBlt, GarageFinish, GarageCars, GarageArea,  GarageQual, GarageCond, PoolQC, Fence, MiscFeature, SaleType]

2.3. To replace values I can use // It is good idea to fill NaNs with frequent or mean values on concatenated dataset (train+test). But it is cheating actually.

from sklearn.impute import SimpleImputer 

imputer = SimpleImputer(startegy='most_frequent')

imputed_dataset = pd.DataFrame(imputer.fit_transform(panda_dataset)

imputed_dataset.columns = panda_dataset.columns

2.3.1 Try other strategies.

2.3.2. startegy='mean' or median do not show a significant change but imputer = SimpleImputer(startegy='constant', fill_value=0) shows -0.5% MAE.

2.4.1. KNN imputer create clusters and use nearest value from the cluster to impute feature. // Good only for numeric missing values.

2.3.3. criterion="fridman_mse" // Insignificant improvement close to inside static error

2.3.4. min_samples_split // increasing just impaire performance

2.3.5. min_samples_leaf // increasing just impaire performance

2.3.6. min_weight_fraction_leaf // This is like quantization or L2 increasing it above 0.0001 just impaire performance

2.3.7. max_features=0.55 impoved performance by 2% 

2.3.8. max_leaf_nodes // nothing

2.3.9. min_impurity_decrease // nothing changes

2.3.10. bootstrap=False // -1%

2.3.11. oob_score=True and bootstrap=true // Nothing

2.3.12. warm_start = True // Nothing

2.4. From my experience it is not a good idea to add columns ["LotFrontage, LowQualFinSF, GarageQual, YrSold, PoolQC, GarageFinish, ScreenPorch"]

3. Try to experiment with RandomForestRegressor parameters.

3.1. Increasing of n_estimators from 200 to 600 helped to improve MAE from 16000 to 15800. Increasing above 3000 doesn't have a sence.

4. Currently I implement one-hot encodind for columns with categorical datatype with >>> pd.get_dummies(pandas_dataset). What if try ordinal encoding instead? Or use >>> from sklearn.preprocessing import OneHotEncoder // Worse

4.1. Ordinal encoding doesn't show any significant MAE changing.

4.2. Try to implement ordinal encoding only for categorical variables with less then 4 values >>> nunique = list(map(lambda col: X[col].nunique(), columns_with_objects)) // 4 doesn't really help but for < 3 not that bad 0.5% improvement. Actually it is recommended to encode ordinally columns with high amount of unique values bcs they increase dataset.

4.3. Try to >9 for ordinal encoding. // Nothing

4.4. What if position Imputer before Dummy one-hot encoder. // Nothing

5. Try pipeline with OneHot and Impuser. // I get 1% worse result and I had some magical problems with usage of this "pipeline". I can't even explain, I made just a small change in example and standart function stops to work. For example Train_pandas_dataset["Some_column_name"].dtype generates an error. If I copy the same code from initial kaggle example it works. If I make any small change strategy="mean" I get dtype error again. Mistery.

6. Try to change model RandomForestRegressor itself for something else lke Histogram Gradient Boosting. 

6.1. from xgboost import XGBRegressor // Better then RandomForestRegressor

6.1.1 While training XGBRegressor I get ValueError: feature_names must be unique. Duplicates found: ['TotRmsAbvGrd']

6.1.2. I have two same columns TotRmsAbvGrd. I have to remove one of them.

6.1.3. Which moment I get this duplicate? // It was my mistake. I mentioned this column twice while creating dataset.

6.2. XGBRegressor parameter engineering.

6.2.1. booster="dart" // impaire

6.2.2. max_depth=5 gives best result

6.2.3. subsample=0.74 gives the best results for me.

6.2.4. colsample_bytree=0.74 is best for validation of my dataset

7. HistGradientBoostingRegressor worse then XGBRegressor

7.1. AdaBoostRegressor worse then HGBR.

7.2. BaggingRegressor, ExtraTreesRegressor better then Ada but worse then HistGradientBoostingRegressor.

7.3. GradientBoostingRegressor shows best result 13800.

gbr = GradientBoostingRegressor(

    n_estimators=13000,

    learning_rate=0.001,

    max_leaf_nodes=30,

    max_depth=19,

    min_samples_leaf=3,

    alpha=0.8,

    max_features=10,

    min_impurity_decrease=0.8,

    subsample=0.9,

    random_state=1,

)

7.4. Try to use StackingRegressor it is intresting method which ensable other ensambling methods. // Looks like it shows just an average result.

7.4.1. But VotingRegressor gives better results then average and StackingRegressor. // It is actually pretty good.

estimators = [

    ('hgb', HistGradientBoostingRegressor(max_iter=1186, learning_rate=0.005, max_leaf_nodes=30, max_depth=19, min_samples_leaf=4, l2_regularization=0.4 )),

    ('gbr', GradientBoostingRegressor(n_estimators=13000, learning_rate=0.01, max_leaf_nodes=30, max_depth=19, min_samples_leaf=3, alpha=0.8,

                                        max_features=10, min_impurity_decrease=0.8, subsample=0.9, random_state=1)),

    ('etr', ExtraTreesRegressor(n_estimators=300, min_samples_leaf=2, random_state=1) ),

    ('xgbr', XGBRegressor(n_estimators=92, learning_rate=0.1, max_depth = 5,  subsample=0.74, colsample_bytree=0.74, tree_method="hist", refresh_leaf=1, reg_lambda=1,

                                        alpha=2, gamma=2, random_state=0) ),

    ('rfr', RandomForestRegressor(n_estimators=5000, criterion='friedman_mse', max_features=0.75, random_state=1 ) )

]

er = VotingRegressor(estimators).fit(train_X, train_y) 

predictions = er.predict(val_X) 

mae_2 = mean_absolute_error(predictions, val_y) 

8. Try to analyze value of each column how I did for my website and add my own syntatic data for training.

8.1. Analysis with PermutationImportance

8.1.1. The most important features OverallQual (0.1939), GrLivArea (0.0967), GarageCars (0.0356) and less important TotalBsmtSF (0.0179), BsmtFinSF1 (0.0155), 1stFlrSF (0.0151), LotArea (0.0136), 2ndFlrSF (0.0127), KitchenQual_Ex (0.0113), Fireplaces (0.0089), Neighborhood(0.0084), YearBuilt, GarageArea, TotRmsAbvGrd, FullBath, ExterQual_TA, OverallCond, BsmtQual_Ex, MasVnrArea, BedroomAbvGr, YearRemodAdd, HalfBath, KitchenQual_TA, OpenPorchSF

8.1.2. Smallest contribution about zero. BsmtCond_Gd, BsmtCond_TA, BsmtCond_Po, Fence, HeatingQC_Fa, HeatingQC_Po, HeatingQC_Gd, ExterCond, 3SsnPorch, Alley, MiscVal, KitchenQual_Fa, BsmtHalfBath, PavedDrive_P, MasVnrType_BrkCmn, MasVnrType_Stone, MSZoning_RH, MSZoning_FV, GarageCond_Ex, GarageCond_Gd, GarageCond_Fa, GarageCond_Po, BsmtQual_Fa, BsmtQual_TA,  EnclosedPorch, ExterQual_Fa, ExterQual_Gd, ExterQual_Ex, SaleType, SaleCondition.

8.1.3. Try to delete red features. // Get worse

8.1.2. The problem is that I can't see all the list of feature values. // eli5.show_weights(perm, feature_names=val_X.columns.tolist(), top=100)

9. Make function which will bruttforce MSE for all feature combination and save the best combination.

9.1. Basic enumerator which generates all word combination from a list.

import itertools

features = ["area", "condition", "pool", "garage"]

for i in range(len(features) + 1):

for sub in itertools.combinations(features, i):

print(sub)

9.2. I won't continue to do this. Too many combinations. I do not have time for this.

9.2.1 What if I start from (all features -1) and every step will calculate one worse combination then delete this element. Enumerate combination and get five best results then exclude features that are not included. // It is not actually a good idea. It leads to overfit model on your validation dataset with bad robustness and such model will get bad result on test dataset.

FEATURE ENGINEERING

9.3. Try to use feature engineering, mutual information technique to find correlations between features.

9.3.1. Sum of unsignificant features PoolArea+MiscVal+3SsnPorch+EnclosedPorch gives a good column // Not really

9.3.1. Try visualization of every feature

import seaborn as sns

sns.relplot(x="value", y="SalePrice", col="variable", data=df.melt(id_vars="SalePrice", value_vars= ["first_feature", "second_feature"]), facet_kws=dict(sharex=False));

 

9.4. Try to make all columns ordinal then regroup order to make it linear. Especially zonning.

9.4.1. "MSSubClass" delete by 10 or 20 because number values descrete like. // Doesn't change anything

9.4.2. Regroup values to creat regression like distribution.  180 -> 0,  30 -> 2  , 190 -> 5, 160 -> 6, 125 -> 7, 80 -> 8, 70 -> 9, 120 -> 10, 50 -> 11, 75 -> 12, 20 -> 13, 60 -> 14

50 -> 12, 90 -> 3, 85 -> 4, 40 -> 8

// It improves significantly. I have to implement it to other categorical columns.

df['col_name'].loc[ df['col_name'] == 60.0 ] = 10.0

9.4.3. Neighborhood resort alphabetical names to get linear or do not apply ordinal transforamation. 2->100, 10 -> 101, 1 -> 102, 9 -> 103, 13 -> 104, 19 -> 105, 18 -> 106, 3 -> 107, 11 -> 108, 0 ->109, 12 -> 110, 14 -> 111, 17 -> 112, 7 -> 113, 20 -> 114, 4 -> 115, 5 -> 116, 6 -> 117, 8 -> 118, 24 -> 119, 23 -> 120, 21 -> 121, 22 -> 122, 16 -> 123, 15 -> 124 // Great. -2% of MAE

9.4.4. MSZoning 0 -> 10, 2 -> 11, 1 -> 12, 4 -> 13, 3 -> 14 // Doesn't help

9.4.5. "Condition1" join [3:8] and resort [1,2,[4:9],3]    5 - 10, 7 -11, 1 - 12, 0-13, 8 -14, 3 - 15, 6 - 16, 4 - 17, 2 - 18 // Helped a little

9.4.6. "OverallCond"  5 move to 8, 8 move to 5. // Get worse

9.4.7. ExterCond. 3 - 0, 1-1, 0-2, 2-3. // worse

9.4.8. "Foundation" 4->1, 5->2, 6->3 // Better

9.4.9. "BsmtFinType1" 3->end, 4-> start // Helped

9.4.10. "HalfBath" resort // Good

9.4.11. KitchenAbvGr resort // Nothing

9.4.12. TotRmsAbvGrd join [11:14] // Good

9.4.13. Fireplaces join [2:3] // Worse

9.4.14. GarageType 4 -> start, 2 -> end, 4 -> 5 // Nothing

9.4.15. GarageCars [3:4] join // Nothing

9.4.16. SaleCondition regroup // helpfull

9.4.17. Cut values which  are to large in LotArea, 1stFlrSF. 2ndFlr cut zeroes move them to center of mass. // Helps

9.4.17. What if to join all porch related columns into one and same for other same domain columns. // Porch column failed

9.4.17. Move zeroes in WoodDeckSF  // Bad idea

9.4.18. BsmtQual regroup // Bad

9.4.18. BsmtCond regroup // Good

9.4.19. "BsmtFinSF1" cut values > 2500 // Good

9.4.20. KitchenQual resort. // Good

9.4.21. GarageArea 0 values to 200 and >1500 cut // Nothing

9.4.22. GarageCond sort // Nothing

9.4.23. Fence sort // Good

9.4.24. PavedDrive sort // Bad

9.4.25. Exterior1st, LotConfig, LotShape, HouseStyle, MiscFeature sort // Bad

9.4.6. To cut outliners is generally a good idea.

 

"yearRemodAdd" 1950 delete.

"MasVnrArea" delete 0

"TotalBsmtSF" cut values > 3000

"GrLivArea" cut > 4800

"BsmtFullBath" [2:3] join

"BsmtHalfBath" [2:1] join

"HalfBath" [2:1] join

"KitchenAbvGr" join [0:1] and [2:3]

OpenPorchSF cut > 400

9.4.7. Add feature df["Spaciousness"] = (df.FirstFlrSf + df.2ndFlrSF) / df.TotRmsAbvGrd // arguable feature

9.4.8. Add feature df.OverallQual * df.OverallCond // nothing

9.4.9. Try square root of some area related features. // useless

9.4.10. Try to apply logarithm to features which are too skewed. // No difference for forests and you can get NaNs. Use better standartization.

9.4.11. Correlation between BsmtQual and TotalBsmtSF // It gives a strong feature but result is bad

9.4.12. Try to create df["Median"] = df.groupby("Neighborhood")["GrLivArea"].tranform("median") also try std and count. And count difference between median and actual living space. // Strong feature but without improving

9.4.13. Try GrLivArea + TotalBsmtSF // This is good butI already created it.

9.4.14. Try YearRemodAdd + TotalBsmtSF // Nothing

9.4.15. Try to sum baths columns.

9.4.16. Add a season feature // Not really good

def map_month_to_season(month):

    if month in [3, 4, 5]:

        return 1

    elif month in [6, 7, 8]:

        return 2

    elif month in [9, 10, 11]:

        return 3

    else:

        return 4

df_test_end['SeasonSold'] = df_test_end['MoSold'].apply(map_month_to_season)

9.4.17. imputed_Xo48['AgeOfGarage'] = imputed_Xo48['YrSold'] - imputed_Xo48['GarageYrBlt'] // Good

 

 

METHODS TO FIND CORRELATIONS

9.5. If we have some insignificant categorical value "CV" we can take significant value "SF" and build graphics for each category i.e. we take only those SF which corresponds to only one insignificant category of categorical variable.

import seaborn as sns

sns.lmplot( x=SF, y="Our_label_feature_name", hue="CV", col="CV", data=my_dataset_here, scatter_kws={"edgecolor": 'w'}, col_wrap=3, height=4, ) 

9.5.1. With this graph try to detect features which brin a lot of noize. Try to delete this rows. // Bad idea to delete rows.

9.5.2. Seems to be SalesCondition=Abnormal make a lot of noise. Try to delete this rows. Х2 = Х[X.my_column_name != "Abnormal"] // 70 rows deleted and MAE get worse

9.6. New feature which just summarize precense of value if it >0 // Gives a good result

9.7. What if to summarize all condition features but at first I have to rename content alphabetically from A (excellent) so Dummy be able to number them.

9.7. At firs try to rename alphabetically and watch how model will perform afte new ordering. // ordinal_encoder doesn't order alphabatically.

9.7.1. I will use manual ordering like, X2["ExterCond'].loc[X["ExterCond'] == "Ex'] = 4

9.8. With sns.lmplot try to make a lot of graphs with all combibations of bad features and try to find graph with good correlation. // I am not sure of improvement possibilty of this technique because of huge amount of zero values. I still have no idea how figurre it out. I cannot move them to the center of mass bcs I cannot change Y values. Maybe I have to calculate mean of those two groups and found which x value of cloud corresponds to mean Y value of zeros. But I won't do such a sopfisticated calculations for this task.

SaleCondition with BsmtFinType=4 has about 6 deg angle with PoolQC=0 (NA) has about 5 deg angle with BsmtHalfBath=0 has about 5 deg angle.

SaleCondition with FullBath=2 has about 5 deg angle.

SaleCondition with Fireplaces=1 has about 5 deg angle.

SaleCondition with HalfBath=1 has about 5 deg angle.

BsmtHalfBath with Fireplaces=1 has -4 deg.

Fence with FireplaceQu = 3 has -5 deg.

ExterCond with MasVnrType = 0 has 4 deg.

ExterCond with Foundation = 4 has 5 deg.

ExterCond with FireplaceQu = 0 has 4 deg.

GarageCond with Condition1 = 8 has 9 deg.

GarageCond with MSSubClass = 14 (20) has 9 deg. // Bad

GarageCond with MSZoning = 4 has 9 deg.

GarageCond with Fireplaces = 1 has 10 deg.

GarageCond with HeatingQC = 4 (ex) has 10 deg.

GarageCond with ExterCond = 2 has 10 deg.

GarageCond with Fence = 2 has 10 deg.

GarageCond with PoolQC = 0 (NA) has 10 deg.

GarageCond with SaleCondition = 4 has 10 deg.

GarageQual with FullBath = 2 has 10 deg.

GarageQual with BedroomAbvGr = 4 has 15 deg.

GarageQual with BsmtCond = 2 has 10 deg.

GarageQual with SaleCondition = 4 has 10 deg.

PavedDrive with Fireplaces =1 has 5 degree.

PavedDrive with BedroomAbvGr =3 has 5 degree.

BsmCond with FullBath =2 has 8 degree.

BsmCond with BedroomAbvGr =4 has 9 degree.

BsmCond with BsmtFinType1=4 has 10 degree.

MasVnrType with Fireplaces=1 has 6 degree.

MasVnrType with MSSubClass=14 has 7 degree.

MasVnrType with BsmtFullBath=1 has 7 degree.

HeatingQC with Fireplaces=1 has 11 degree. // Bad

HeatingQC with BsmtCond=2 has 6 degree.

HeatingQC with ExterCond=2 has 7 degree.

HeatingQC with PoolQC=0 has 7 degree.

all_count with CentralAir_Y=1 has 20 degree. // Nothing

all_count with BsmtFullBath=1 has 27 degree. // Bad

CONDITIONS with MasVnrType=1 (Stone) has 30 degree. // Bad

CONDITIONS with HeatingQC=4 (ex) has 35 degree. // Good. But CONDITION feature is better.

GrLivArea with MSSubClass=20 (14) has 30 degree.

 

9.9. Make feature which sums absolute value of each feanure. // Bad idea

9.10. Breakdown categorical names. Dataset_name["MSClass"] = Dataset_name.MSSubClass.str.split("_", n=1, expand=True)[0]

9.11. What if features with mostly zero values assign middle Y and X value from.

9.11.1. How in pandas calculate mean value? // my_dataset_name["my_column_name"].mean()

9.11.2. How to calculate mean only for values which are more then zero? // my_dataset_name[ my_dataset_name.my_column_name > 0 ].mean()

9.11.3.  But I have to calculate Price column values based on condition applied to a different column. // my_dataset_name["Price"].loc( my_dataset_name.my_column_name > 0 ).mean()

9.12. Try to make volume varibale from area and wall area. // It is actually hard to do. I've used MsnVnrArea but it is nor really effective

9.13. Try join strings Condition1 and Condition2 // Nothing

9.13.1. roofStyle and Roffmtl join gives a good feature

9.13.2. try (Exterior1st + Exterior2nd) * ExterCond 

9.14. Create some style related common feature // Good idea

 

10. Try to normalize numeric year values or other big values.

from sklearn.preprocessing import Normalizer

normalizer = Normalizer()

normalized_values = normalizer.fit_transform(df[num_columns])

10.1 Normalization to (0,1) just makes things worse.

10.2. Try to use from sklearn.preprocessing import MinMaxScaler to trim some 0 values. MinMaxScaler(feature_range=(1950,2010), clip=True)

10.3. Try just to substract 1950 from year columns. // Doesn't help.

10.4. try to normalize to standart deviation other numeric columns like area

10.5. What if impute to the "mean" then normalize to (0:1) and then scale to (0:10) // Worse

11. Try Neural Network. // MLPRegressor doesn't shows good results

11.1. keras with 1M parameters gives 13400 as the best result. And I've pretrained it on same housing datasets.

K-Means

12. Implement K-Means to create Cluster feature.

12.0. Try features LotArea LivingArea BsmtArea FirstFlArea and SecondFlrArea for clustering. // Nothing.

12.0.1. Try sort and normalize with dataset = ( dataset - dataset.mean(axis=0) ) / dataset.std(axis=0) // Better

12.0.2. If I add 10 clusters for all features with kmeans init=100 creates really strong feature.

12.1. Scaling should be helpfull.

12.2. Add cluster distance feature to dataset. // It is helpfull especially when I deleted some poor distance features and only one has left.

Try to normalize with dataset = ( dataset - dataset.mean(axis=0) ) / dataset.std(axis=0) other columns // Good for nn

 

PCA

13. PCA is  very powerfull technique which allows to find correlations in features even without knowledge about domain or even with no column names at all. If you have strong negative and strong positive pca coef you could try to multiply or devide. If strong positives then sum them.

13.1. Or you can use PCA components from pca.fit_transform(dataset) themselves as a feature.

13.2 Usage of PCA feature discovering technique.

from sklearn.decomposition import PCA

pca = PCA()

X = pca.fit_transform(X_scaled)

13.3. You can build very descriptive graph.

sns.clustermap(

df.corr("pearson", numeric_only=True),

vmin = -1.0,

vmax=1.0,

cmap="icefire",

method="complete",

annot=True,

**kwargs,

)

 

Pandas df.corr()

# Correlation between variables to check multicollinearity 

# Generate a mask for the upper triangle (taken from seaborn example gallery)

plt.subplots(figsize = (30,20))

mask = np.zeros_like(train_num.corr(), dtype=np.bool)

mask[np.triu_indices_from(mask)] = True

sns.heatmap(train_num.corr(), cmap=sns.diverging_palette(20, 220, n=200), mask = mask, annot=True, center = 0)

 

 

 

CLEAN DATA

14.0 Check typos.

14. If GarageYearBuild corrupt substitute it with Year of house built and vice versa. df["GarageYearBuild"] = df["GarageYearBuild"].where(df.GarageYearBuild <= 1900, df.YearBuild)

14.1. Check dataset's categoty names for grammar errors with df.column_name_here.unique() and compare it with documantation. // I didn't found any error.

14.2. Try to change MSSubClass to categotrical type df["MSSubClass"] = df["MSSubClass"].astype("category")

14.3. I just missed the fact that I have to add the None category to categorical columns for Nan values? othervise Nan values will be asiigned to wrong category.

MSZoning has 4 Nan. I have no idea how to impude them // Try most common.

Alley has 90% missing values

Exterior1st and Exterior2nd - 1 value missed // Try to impude into the most common.

MasVnrArea 23 NAN. Impude to 0.

BsmtQual and BsmtCond 80 missed // Try to None category if BsmtFinSF1 == 0 and TotalBsmtSF == 0 otherwise most common.

BsmtFinSF1 and TotalBsmtSF 1 is missing to Zero.

BsmtFullBath and BsmtHalfBat 2 are missed. To zero.

KitchenQual 1 is missed. To most common.

FireplaceQu half is missing. To NONE category. // More or less good

GarageType 157 are missing. To NONE category.

GarageYearBuilt 159 missed.

GarageQual and GarageCond 159 missed.  To NONE category.   // Make worse

PoolQC 99% are missing.  To NONE category. // Make worse

Fence 2350 are missing.

SaleType 1 is missing.  To most common.

14.4. Try to exclude rows where SalePrice is outlines or normalize SalePrize. // Bad idea leads to strong overfitting

14.5. Deleting features leads to overfitting especially if you use greed strategy.

 

Anomaly detection

1. Detect outliers and create special feature for outliers. For example SaleCondition=="Partial" // Nothing

2. Use IsolationForest to autodetect outliers. // 25 rows were deleted from 1600. Bad results

from sklearn.ensemble import IsolationForest

iso_forest = IsolationForest(max_samples=0.7, contamination=0.015, bootstrap=True, n_jobs=-1, random_state=100)

iso_forest.fit(imputed_Xo48) # Obtaining anomaly labels for the training dataset (-1 for anomalies and 1 for normal points)

 

train_outliers = iso_forest.predict(traino)

traino = traino[train_outliers == 1]

y = y[train_outliers == 1]

2.1. Try it before clusterization

3. Check anomaly if YearBuilt > GarageYrBlt 18, YearBuilt > YrSold 1, YearBuilt > YearRemodAdd 1

 

 

Target Encoding

1. Try to use lib $ pip install category_encoders or sklearn.preprocessing.TargetEncoder instead of ordinal encoder.

1.0. Usage

from sklearn.preprocessing import TargetEncoder

#from sklearn.model_selection import cross_validate

target = TargetEncoder(target_type="continuous", random_state=0)

X_trans = target.fit_transform(X, y)

1.0.1. Error: cannot import name 'TargetEncoder' from 'sklearn.preprocessing' (/usr/local/lib/python3.11/dist-packages/sklearn/preprocessing/__init__.py) // Use from category_encoders.target_encoder import TargetEncoder

 

WHAT REGRESSOR TO USE

1. I tried neural net but it doesn't show best resluts MAE=16000

from   keras.models import Sequential

from   keras.layers import Dense 

model = Sequential()   

model.add(keras.Input(shape=(train_X.shape[1],)))

model.add(Dense(train_X.shape[1], kernel_initializer='normal', activation='gelu'))

model.add(Dense(20000, kernel_initializer='normal', activation='relu'))

model.add(Dense(1, kernel_initializer='normal'))

model.compile(loss='mean_absolute_error', optimizer='adam');

model.fit(train_X_scaled, train_y, batch_size=16, epochs=100, validation_data=(val_X_scaled, val_y), validation_freq=10, verbose=1);

predictions = model.predict(val_X_scaled);

2. Good choise is XGBRegressor, HistGradientBoostingRegressor, LGBMRegressor, GradientBoostingRegressor, catboost   // they show MAE about 12800 - 13400.

3. catboost shows very good results on validation set but has strong overfitting on test set // MAE=12600 on validation set

cb = CatBoostRegressor(

    loss_function='MAE', 

    logging_level='Silent',

    n_estimators = 9000,

    learning_rate =0.01,

)

 

 

 

OPTIMIZE HYPERPARAMETERS

Use Optuna

Use scikit-optimize

1. GridSearchCV usage example // It is just a bruteforcing. Takes a lot of time.

from sklearn.model_selection import cross_val_score, GridSearchCV

param_grid = {'n_estimators': [5000,6000,7000,8000],'learning_rate': [0.01,0.02,0.03,0.04,0.05], 'max_depth':[1,2,3,4]}

gridsearch=GridSearchCV(gb,param_grid,n_jobs=4)

gridsearch.fit(train_X, train_y)

gridsearch.best_estimator_ 

 

 

Try impude different column with different starategies. Some with constant =0 some with mean etc dependenig on the domain. And you can use mean from join dataset.

 

For validation use K-Fold instead of test_training split to decrease overfitting probabilty.

 

2. Try

loo = LeaveOneOut()

scores = cross_val_score(model, X, y, cv=loo)

 

 

Join train and test datasets and perform clusterization and PCA on this big dataset // Good idea

 

Try to delete all zero mi_score feature // Bad results.

Target normalization with np.log1p(y) or QuantleTransformer produce bad results.

 

Or find same datasets. from sklearn.datasets import fetch_california_housing. Oklahoma, Texas, boston, NYC // That actually improves NN score to 14200 but it is not enough to beat random fradient booster.

 

Round up final prediction.

 

For linear regressors. (One-hot encoding needed).

 

Decrease skewness

 

Use visualization technique for my website SEO optimizer.