-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiamonds.py
275 lines (191 loc) · 7.74 KB
/
diamonds.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# -*- coding: utf-8 -*-
"""Diamonds.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/17s6z3iAjiYYqSaFISWDtV5-7C5KInlt9
"""
import pandas as pd
diamond=pd.read_csv("diamonds.csv")
# Commented out IPython magic to ensure Python compatibility.
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
# %matplotlib inline
diamonds=diamond.copy()
diamonds.head()
diamonds.info()
diamonds["cut"].unique()
diamonds["cut"].value_counts()
diamonds["color"].unique()
diamonds["color"].value_counts()
diamonds["clarity"].unique()
diamonds["clarity"].value_counts()
diamonds.describe()
diamonds=diamonds.drop("Unnamed: 0",axis=1)
diamonds = diamonds.loc[(diamonds[['x','y','z']]!=0).all(axis=1)]
diamonds.shape
diamonds.hist(bins=50, figsize=(20,15))
plt.show()
plt.figure(figsize=(10, 8))
diamonds.plot(kind="scatter",x="price",y="carat",alpha=0.1)
plt.figure(figsize=(10, 8))
diamonds.plot(kind="scatter",x="x",y="price")
plt.figure(figsize=(10, 8))
diamonds.plot(kind="scatter",x="y",y="price")
plt.figure(figsize=(10, 8))
diamonds.plot(kind="scatter",x="z",y="price")
plt.figure(figsize=(10, 8))
diamonds.plot(kind="scatter",x="depth",y="price")
plt.figure(figsize=(10, 8))
diamonds.plot(kind="scatter",x="table",y="price")
sns.displot(diamonds['price'])
sns.countplot( data=diamonds,x='cut')
sns.countplot( data=diamonds,x='clarity')
sns.countplot( data=diamonds,x='color')
plt.figure(figsize=(10, 8))
sns.boxplot(data=diamonds, x="depth", y="cut")
plt.show()
plt.figure(figsize=(10, 8))
sns.boxplot(data=diamonds["carat"])
plt.show()
plt.figure(figsize=(10, 8))
sns.boxplot(data=diamonds["x"])
plt.show()
plt.figure(figsize=(10, 8))
sns.boxplot(data=diamonds["y"])
plt.show()
plt.figure(figsize=(10, 8))
sns.boxplot(data=diamonds["z"])
plt.show()
plt.figure(figsize=(10, 8))
sns.boxplot(data=diamonds["price"])
plt.show()
plt.figure(figsize=(10, 8))
sns.boxplot(data=diamonds, x="price", y="cut")
plt.show()
plt.figure(figsize=(10, 8))
sns.boxplot(data=diamonds, x="price", y="clarity")
plt.show()
plt.figure(figsize=(10, 8))
sns.boxplot(data=diamonds, x="price", y="color")
plt.show()
corr_mat=diamonds.corr()
corr_mat["price"].sort_values(ascending=False)
a = sns.heatmap(corr_mat, annot=True)
"""# Feature Engineering"""
x = diamonds[diamonds['clarity'] == 'SI1'].index #getting the indices where clarity is SI1
diamonds.loc[x, 'clarity'] = 'SI'
x = diamonds[diamonds['clarity'] == 'SI2'].index #getting the indices where clarity is SI2
diamonds.loc[x, 'clarity'] = 'SI'
#Here we do the same for VS1, VS2
x = diamonds[diamonds['clarity'] == 'VS1'].index
diamonds.loc[x, 'clarity'] = 'VS'
x = diamonds[diamonds['clarity'] == 'VS2'].index
diamonds.loc[x, 'clarity'] = 'VS'
#And the same for VVS1, VVS2
x = diamonds[diamonds['clarity'] == 'VVS1'].index
diamonds.loc[x, 'clarity'] = 'VVS'
x = diamonds[diamonds['clarity'] == 'VVS2'].index
diamonds.loc[x, 'clarity'] = 'VVS'
# colors D, E and F represent the same thing link --> https://www.brides.com/thmb/5r1fBKJXP1Dw71Jun5-rdtR1ex0=/1500x1000/filters:no_upscale():max_bytes(150000):strip_icc()/diamond-color-chart-5093397_horizontal-b8d3872096fd47c78d244d40cc920099.png
#so we will replace them with one value
x = list(diamonds[diamonds['color'] == 'D'].index) + list(diamonds[diamonds['color'] == 'E'].index) + list(diamonds[diamonds['color'] == 'F'].index)
diamonds.loc[x, 'color'] = 'Colorless'
#Here the same for colors G, H, I and J
x = list(diamonds[diamonds['color'] == 'G'].index) + list(diamonds[diamonds['color'] == 'H'].index) + list(diamonds[diamonds['color'] == 'I'].index) + list(diamonds[diamonds['color'] == 'J'].index)
diamonds.loc[x, 'color'] = 'NearColorless'
"""Dealing with Outliers"""
mean_pr= diamonds['price'].mean()
stander_pr=diamonds.price.std()
upper_limit=mean_pr + 3*stander_pr
lower_limit=mean_pr- 3*stander_pr
diamonds=diamonds[(diamonds['price']<upper_limit) & (diamonds.price>lower_limit)]
diamonds
"""Dropping unnecessary features"""
diamonds=diamonds.drop(["depth","table"], axis=1)
diamonds.head()
"""## **handling categorical features **"""
from sklearn.preprocessing import OrdinalEncoder
ordinal_encoder = OrdinalEncoder()
OE = OrdinalEncoder(categories = [['Fair', 'Good', 'Very Good', 'Premium', 'Ideal'], ['I1', 'SI', 'VS', 'VVS', 'IF'], ['NearColorless', 'Colorless']])
diamonds[['cut', 'clarity', 'color']] = OE.fit_transform(diamonds[['cut', 'clarity', 'color']])
diamonds.head()
"""# ***scalling***"""
from sklearn.preprocessing import StandardScaler
std_scaler = StandardScaler()
diamonds[["carat","x","y","z"]] = std_scaler.fit_transform(diamonds[["carat","x","y","z"]])
diamonds.head()
"""splitting data"""
diamonds_prep=diamonds.drop("price",axis=1)
y=diamonds["price"].copy()
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test = train_test_split(diamonds_prep,y, test_size=0.08, random_state=42)
"""Training and evaluation of training set using Linear Regression Model"""
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(x_train,y_train)
#lin_reg.fit(diampnds_prepared, diamonds_label)
diamonds_predictions = lin_reg.predict(x_train)
lin_mse = mean_squared_error(y_train, diamonds_predictions)
lin_rmse = np.sqrt(lin_mse)
lin_rmse
"""## Training and evaluation of training set Decision Tree model"""
from sklearn.tree import DecisionTreeRegressor
tree_reg = DecisionTreeRegressor()
tree_reg.fit(x_train,y_train)
diamonds_tree_predictions = tree_reg.predict(x_train)
tree_mse = mean_squared_error(y_train, diamonds_tree_predictions)
tree_rmse = np.sqrt(tree_mse)
tree_rmse
"""## Using cross validation to make sure the model didn't overfit """
from sklearn.model_selection import cross_val_score
scores = cross_val_score(tree_reg, x_train, y_train, scoring = "neg_mean_squared_error", cv = 10)
tree_rmse_scores = np.sqrt(-scores)
print("Scores : ", tree_rmse_scores)
print("Mean : ", tree_rmse_scores.mean())
print("Std : ", tree_rmse_scores.std())
"""Evaluation using Cross_validation"""
from sklearn.model_selection import cross_val_score
scores = cross_val_score(tree_reg, x_train, y_train,scoring="neg_mean_squared_error", cv=10)
tree_rmse_scores = np.sqrt(-scores)
def display_scores(scores):
print("Scores:", scores)
print("Mean:", scores.mean())
print("Standard deviation:", scores.std())
display_scores(tree_rmse_scores)
lin_scores = cross_val_score(lin_reg, x_train, y_train, scoring="neg_mean_squared_error", cv=10)
lin_rmse_scores = np.sqrt(-lin_scores)
display_scores(lin_rmse_scores)
"""Training and evaluation of training set using Random Forest"""
from sklearn.ensemble import RandomForestRegressor
forest_reg = RandomForestRegressor()
forest_reg.fit(x_train, y_train)
diamonds_forest_predictions = forest_reg.predict(x_train)
forest_mse = mean_squared_error(y_train, diamonds_forest_predictions)
forest_rmse = np.sqrt(forest_mse)
forest_rmse
forest_scores = cross_val_score(forest_reg, x_train, y_train, scoring="neg_mean_squared_error", cv=10)
forest_rmse_scores = np.sqrt(-lin_scores)
display_scores(forest_rmse_scores)
"""Evaluating on Test-set
Linear Model
"""
diamonds_ts_predictions = lin_reg.predict(x_test)
lin_mse = mean_squared_error(y_test, diamonds_ts_predictions)
lin_rmse = np.sqrt(lin_mse)
lin_rmse
plt.scatter(diamonds_ts_predictions,y_test)
plt.title('Prediction vs Actuals')
plt.show()
lin_reg.score(x_test,y_test)
"""Decision tree model"""
diamonds_ts_tree_predictions = tree_reg.predict(x_test)
tree_mse = mean_squared_error(y_test, diamonds_ts_predictions)
tree_rmse = np.sqrt(tree_mse)
tree_rmse
plt.scatter(diamonds_ts_tree_predictions,y_test,c='lightblue')
plt.title('Prediction vs Actuals')
plt.show()
tree_reg.score(x_test,y_test)