Kaggle competition: House Prices - Advanced Regression Techniques
def get_test_dataset(ordered=False):
dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset 
<groupby>
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from sklearn.preprocessing import LabelEncoder,StandardScaler
from sklearn.model_selection import train_test_split,cross_val_score
from sklearn.neighbors import LocalOutlierFactor
from sklearn.impute import SimpleImputer
from sklearn.metrics import mean_absolute_error
from sklearn.ensemble import RandomForestRegressor,StackingRegressor,GradientBoostingRegressor
from sklearn.linear_model import LassoCV,RidgeCV,ElasticNetCV
from sklearn.svm import SVR
from xgboost.sklearn import XGBRegressor
import lightgbm as lbg
def count_data_items(filenames):
n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames]
return np.sum(n )<define_variables>
train=pd.read_csv('.. /input/house-prices-advanced-regression-techniques/train.csv',index_col='Id')
 test=pd.read_csv('.. /input/house-prices-advanced-regression-techniques/test.csv',index_col='Id')
 y=train['SalePrice']
X=train.append(test )
NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
 NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)
 NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))<define_variables>
def missing(X):
missing_cols={}
for i in range(len(X.columns)) :
if X.iloc[:,i].isnull().sum() >0:
missing_cols[X.iloc[:,i].name]=X.iloc[:,i].isnull().sum()
return missing_cols
X.drop(['Alley', 'FireplaceQu', 'PoolQC', 'Fence', 'MiscFeature'],axis=1,inplace=True )
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES<train_model>
null_cats=['BsmtQual', 'BsmtCond','BsmtExposure', 'BsmtFinType1','BsmtFinType2',
'GarageType','GarageFinish','GarageQual', 'GarageCond']
for f in null_cats:
X[f].fillna('None',inplace=True)
 null_nums=['MasVnrArea' ,'GarageYrBlt', 'GarageArea',
'GarageCars','BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF','TotalBsmtSF', 'BsmtFullBath', 'BsmtHalfBath']
for f in null_nums:
X[f].fillna(0,inplace=True)
 X['LotFrontage']=X.groupby('Neighborhood')['LotFrontage'].transform(lambda x:x.fillna(x.median()))
missing(X )
print("Training data shapes:")
 for image, label in get_training_dataset().take(3):
print(image.numpy().shape, label.numpy().shape)
 print("Training data label examples:", label.numpy())
 print("Validation data shapes:")
 for image, label in get_validation_dataset().take(3):
print(image.numpy().shape, label.numpy().shape)
 print("Validation data label examples:", label.numpy())
 print("Test data shapes:")
 for image, idnum in get_test_dataset().take(3):
print(image.numpy().shape, idnum.numpy().shape)
 print("Test data IDs:", idnum.numpy().astype('U'))<train_model>
label=LabelEncoder()
for feat in cat_cols:
X[feat]=label.fit_transform(X[feat] )
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset )<define_variables>
X_scaled=pd.DataFrame(StandardScaler().fit_transform(X))
X_scaled.columns=X.columns
X_scaled.index=X.index
X_scaled
y=np.log(y )
CLASSES = ['pink primrose', 'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea', 'wild geranium', 'tiger lily', 'moon orchid', 'bird of paradise', 'monkshood', 'globe thistle',
'snapdragon', "colt's foot", 'king protea', 'spear thistle', 'yellow iris', 'globe-flower', 'purple coneflower', 'peruvian lily', 'balloon flower', 'giant white arum lily',
'fire lily', 'pincushion flower', 'fritillary', 'red ginger', 'grape hyacinth', 'corn poppy', 'prince of wales feathers', 'stemless gentian', 'artichoke', 'sweet william',
'carnation', 'garden phlox', 'love in the mist', 'cosmos', 'alpine sea holly', 'ruby-lipped cattleya', 'cape flower', 'great masterwort', 'siam tulip', 'lenten rose',
'barberton daisy', 'daffodil', 'sword lily', 'poinsettia', 'bolero deep blue', 'wallflower', 'marigold', 'buttercup', 'daisy', 'common dandelion',
'petunia', 'wild pansy', 'primula', 'sunflower', 'lilac hibiscus', 'bishop of llandaff', 'gaura', 'geranium', 'orange dahlia', 'pink-yellow dahlia',
'cautleya spicata', 'japanese anemone', 'black-eyed susan', 'silverbush', 'californian poppy', 'osteospermum', 'spring crocus', 'iris', 'windflower', 'tree poppy',
'gazania', 'azalea', 'water lily', 'rose', 'thorn apple', 'morning glory', 'passion flower', 'lotus', 'toad lily', 'anthurium',
'frangipani', 'clematis', 'hibiscus', 'columbine', 'desert-rose', 'tree mallow', 'magnolia', 'cyclamen ', 'watercress', 'canna lily',
'hippeastrum ', 'bee balm', 'pink quill', 'foxglove', 'bougainvillea', 'camellia', 'mallow', 'mexican petunia', 'bromelia', 'blanket flower',
'trumpet creeper', 'blackberry lily', 'common tulip', 'wild rose'] 
<define_variables>
X_scaled.drop('SalePrice',inplace=True,axis=1)
 train=X_scaled[:1451]
test=X_scaled[1451:]
X_train,X_test,y_train,y_test=train_test_split(train, y, test_size=.2, random_state=42 )
display_batch_of_images(next(train_batch))<define_variables>
def model(X_train,y_train,X_test):
las=LassoCV(max_iter=1e7,)
 rid=RidgeCV()
enr=ElasticNetCV(max_iter=1e7)
 gbr=GradientBoostingRegressor()
svm=SVR(C= 20, epsilon= 0.008, gamma=0.0003)
 xgb1=XGBRegressor(objective='reg:squarederror',learning_rate=0.02,n_estimators=3000,subsample=0.7,reg_alpha=0.00006)
 lgbm=lbg.LGBMRegressor(boosting_type='gbdt',objective='regression',n_estimators=3000,learning_rate=0.01,max_bin=200,
bagging_fraction=0.75,bagging_freq=5,feature_fraction=0.2)
 estimators=[('ridge', rid),('lasso',las),('ENR',enr),('GBR',gbr),('SVR',svm),('XGB',xgb1),('LGBM',lgbm)]
stack_model=StackingRegressor(estimators=estimators,final_estimator=xgb1)
 stack_model.fit(X_train,y_train)
 y_stack=stack_model.predict(X_test)
 las.fit(X_train,y_train)
 rid.fit(X_train,y_train)
 enr.fit(X_train,y_train)
 gbr.fit(X_train,y_train)
 svm.fit(X_train,y_train)
 xgb1.fit(X_train,y_train)
 lgbm.fit(X_train,y_train)
 y1=las.predict(X_test)
 y2=rid.predict(X_test)
 y3=enr.predict(X_test)
 y4=gbr.predict(X_test)
 y5=svm.predict(X_test)
 y6=xgb1.predict(X_test)
 y7=lgbm.predict(X_test)
 y_pred=0.1*y1+0.1*y2+0.1*y3+0.1*y4+0.1*y5+0.1*y6+0.1*y7+0.3*y_stack
return y_pred
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )<define_variables>
y_pred=model(X_train,y_train,X_test)
 mean_absolute_error(y_pred,y_test )
display_batch_of_images(next(test_batch))<init_hyperparams>
y_pred=model(train,y,train)
 mean_absolute_error(y_pred,y )
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 5
LR_SUSTAIN_EPOCHS = 0
LR_EXP_DECAY =.8
def lrfn(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr =(LR_MAX - LR_START)/ LR_RAMPUP_EPOCHS * epoch + LR_START
elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:
lr = LR_MAX
else:
lr =(LR_MAX - LR_MIN)* LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)+ LR_MIN
return lr
lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)
 rng = [i for i in range(25 if EPOCHS<25 else EPOCHS)]
y = [lrfn(x)for x in rng]
plt.plot(rng, y)
 print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1]))<install_modules>
result=model(train,y,test )
!pip install -q efficientnet 
<choose_model_class>
res=pd.read_csv('.. /input/house-prices-advanced-regression-techniques/sample_submission.csv',index_col=None)
 res['SalePrice']=np.floor(np.exp(result))
res.to_csv('Submission.csv',index=False )