-
Notifications
You must be signed in to change notification settings - Fork 0
/
Code.py
238 lines (174 loc) · 7.63 KB
/
Code.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# -*- coding: utf-8 -*-
"""Model.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1rrDu6vAA-WBFXNRYGlotAg52q2V9N4qg
# <font color='blue'>House Pricing:</font> <font color='red'>Advance Regression Technique</font>
* **Part 1 - Data Preprocessing**
1. Importing libraries
2. Importing the dataset
3. Dataset information
4. Dropping unnecessary columns
- "Train"
- "Test"
5. Taking care of misssing data
- "Train" Numerical
- "Train" Categorical
- "Test" Numerical
- "Test" Categorical
- Updated info()
6. Encoding categorical data
- "Train"
- "Test"
- Updated head()
7. Spliting the Train & Test datasets
8. Feature Scaling
9. Dimensionality reduction
* **Part 2 - Training the Regression model**
1. RandomForest
2. Other algorithms
3. Accuracy score
* **Part 3 - Creating a submission.csv**
# <font color='blue'>Part 1 - Data Preprocessing</font>
# Importing libraries
"""
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
"""# Importing the dataset"""
train_df = pd.read_csv('train.csv')
test_df = pd.read_csv('test.csv')
"""# Dataset information"""
# data type and missing values of each column
train_df.info()
test_df.info()
# Description of both datasets
train_df.describe()
test_df.describe()
# 1st 5 rows of every column for overview
train_df.head()
test_df.head()
plt.rcParams['figure.figsize']=35,35
g = sns.heatmap(train_df.corr(),annot=True, fmt = ".1f")
sns.distplot(train_df['SalePrice'])
sns.barplot(x='YearBuilt', y='SalePrice', data=train_df)
sns.barplot(x='SaleCondition', y='SalePrice', data=train_df)
sns.barplot(x='YrSold', y='SalePrice', data=train_df)
"""# Dropping unnecessary columns
### "Train"
"""
train_df=train_df.drop("Id",axis=1)
train_df=train_df.drop("Alley",axis=1)
train_df=train_df.drop("PoolQC",axis=1)
train_df=train_df.drop("Fence",axis=1)
train_df=train_df.drop("MiscFeature",axis=1)
"""### "Test""""
test_df=test_df.drop("Alley",axis=1)
test_df=test_df.drop("PoolQC",axis=1)
test_df=test_df.drop("Fence",axis=1)
test_df=test_df.drop("MiscFeature",axis=1)
"""# Taking care of misssing data
### "Train" Numerical
"""
train_df["LotFrontage"] = train_df["LotFrontage"].fillna(train_df["LotFrontage"].mean())
train_df["MasVnrArea"] = train_df["MasVnrArea"].fillna(train_df["MasVnrArea"].mean())
train_df["GarageYrBlt"] = train_df["GarageYrBlt"].fillna(2001)
"""### "Train" Categorical"""
c = ("GarageType", "GarageFinish", "GarageQual", "GarageCond", "BsmtFinType2", "BsmtCond", "BsmtQual", "BsmtExposure", "MasVnrType", "Electrical", "FireplaceQu", "BsmtFinType1")
for col in c:
if train_df[col].dtype == "object":
train_df[col] = train_df[col].fillna("None")
''' OR
for col in ("GarageType", "GarageFinish", "GarageQual", "GarageCond", "BsmtFinType2", "BsmtCond", "BsmtQual", "BsmtExposure", "MasVnrType", "Electrical", "FireplaceQu", "BsmtFinType1"):
test_df[col] = test_df[col].fillna('None')
'''
"""### "Test" Numerical"""
test_df["LotFrontage"] = test_df["LotFrontage"].fillna(test_df["LotFrontage"].mean())
test_df["MasVnrArea"] = test_df["MasVnrArea"].fillna(test_df["MasVnrArea"].mean())
test_df["GarageYrBlt"] = test_df["GarageYrBlt"].fillna(2001)
test_df["GarageCars"] = test_df["GarageCars"].fillna(0)
test_df["GarageArea"] = test_df["GarageArea"].fillna(test_df["GarageArea"].mean())
test_df["BsmtFullBath"] = test_df["BsmtFullBath"].fillna(0)
test_df["BsmtHalfBath"] = test_df["BsmtHalfBath"].fillna(0)
test_df["BsmtFinSF1"] = test_df["BsmtFinSF1"].fillna(test_df["BsmtFinSF1"].mean())
test_df["BsmtFinSF2"] = test_df["BsmtFinSF2"].fillna(test_df["BsmtFinSF2"].mean())
test_df["TotalBsmtSF"] = test_df["TotalBsmtSF"].fillna(test_df["TotalBsmtSF"].mean())
test_df["BsmtUnfSF"] = test_df["BsmtUnfSF"].fillna(test_df["BsmtUnfSF"].mean())
"""### "Test" Categorical"""
c = ("GarageType", "GarageFinish", "GarageQual", "GarageCond", "BsmtFinType2", "BsmtCond", "BsmtQual", "BsmtExposure", "MasVnrType", "Electrical","MSZoning","Utilities","Exterior1st","Exterior2nd","KitchenQual","Functional","FireplaceQu","SaleType", "BsmtFinType1")
for col in c:
if test_df[col].dtype == "object":
test_df[col] = test_df[col].fillna("None")
''' OR
for col in ("GarageType", "GarageFinish", "GarageQual", "GarageCond", "BsmtFinType2", "BsmtCond", "BsmtQual", "BsmtExposure", "MasVnrType", "Electrical","MSZoning","Utilities","Exterior1st","Exterior2nd","KitchenQual","Functional","FireplaceQu","SaleType", "BsmtFinType1"):
test_df[col] = test_df[col].fillna('None')
'''
"""### Updated info()"""
# All the missing values are filled
train_df.info()
test_df.info()
"""# Encoding categorical data with LabelEncoder()
### "Train"
"""
from sklearn.preprocessing import LabelEncoder
catagory_cols = ('MSZoning','Street','LotShape','LandContour','Utilities','LotConfig','LandSlope','Neighborhood','Condition1','Condition2','BldgType', 'HouseStyle', 'RoofStyle','RoofMatl','Exterior1st','Exterior2nd','ExterCond','Foundation','Heating','HeatingQC','CentralAir','KitchenQual','Functional','FireplaceQu','PavedDrive','SaleType','SaleCondition', "GarageType", "GarageFinish", "GarageQual", "GarageCond", "BsmtFinType2", "BsmtCond", "BsmtQual", "BsmtExposure", "MasVnrType", "Electrical", "BsmtFinType1", "ExterQual")
for c in catagory_cols:
le = LabelEncoder()
train_df[c]= le.fit_transform(train_df[c].values)
"""### "Test""""
from sklearn.preprocessing import LabelEncoder
catagory_cols = ('MSZoning','Street','LotShape','LandContour','Utilities','LotConfig','LandSlope','Neighborhood','Condition1','Condition2','BldgType', 'HouseStyle', 'RoofStyle','RoofMatl','Exterior1st','Exterior2nd','ExterCond','Foundation','Heating','HeatingQC','CentralAir','KitchenQual','Functional','FireplaceQu','PavedDrive','SaleType','SaleCondition', "GarageType", "GarageFinish", "GarageQual", "GarageCond", "BsmtFinType2", "BsmtCond", "BsmtQual", "BsmtExposure", "MasVnrType", "Electrical", "BsmtFinType1", "ExterQual")
for c in catagory_cols:
le = LabelEncoder()
test_df[c]= le.fit_transform(test_df[c].values)
"""### Updated head()"""
# All the categorical data is encoded with numbers
train_df.head()
test_df.head()
"""# Spliting the Train & Test datasets"""
X_train = train_df.drop("SalePrice", axis=1)
Y_train = train_df["SalePrice"]
X_test = test_df.drop("Id", axis=1).copy()
''' OR
X_train = train_df[:, 0:-1]
Y_train = train_df[:, -1]
X_test = test_df[:, 1:]
'''
"""# Feature Scaling"""
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
print(X_train)
print(Y_train)
"""# Dimensionality Reduction"""
# Principle Component Analysis
from sklearn.decomposition import PCA
pca = PCA(n_components = 10)
X_train = pca.fit_transform(X_train)
X_test = pca.transform(X_test)
"""# <font color='blue'>Part 2 - Training the Regression model on the Training set</font>"""
from sklearn.ensemble import RandomForestRegressor
regressor = RandomForestRegressor(n_estimators = 200, random_state = 0)
regressor.fit(X_train, Y_train)
Y_pred = regressor.predict(X_test)
"""### Other Algorithms"""
''' OR
from xgboost import XGBRegressor
regressor = XGBRegressor()
regressor.fit(X_train, Y_train)
Y_pred = regressor.predict(X_test)
'''
"""### Accuracy score"""
from sklearn.metrics import accuracy_score
regressor.score(X_train, Y_train)
regressor = round(regressor.score(X_train, Y_train) * 100, 2)
regressor
"""# <font color='blue'>Part 3 - Creating a submission.csv</font>"""
submission = pd.DataFrame({
"Id": test_df["Id"],
"SalePrice": Y_pred
})
print(submission)
#submission.to_csv('RandomForest.csv', index=False)