-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecond_hand_car.py
More file actions
180 lines (136 loc) · 4.98 KB
/
second_hand_car.py
File metadata and controls
180 lines (136 loc) · 4.98 KB
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
# -*- coding: utf-8 -*-
"""Second hand car
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1X9g82wzjzVufCMMdpKssQHZ0jgArMsWZ
"""
import tensorflow as tf ### models
import pandas as pd ### reading and processing data
import seaborn as sns ### vizualzation
from tensorflow.keras.layers import Normalization, Dense, InputLayer
from keras.models import Sequential
from keras.layers import Dense
import numpy as np
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.losses import MeanSquaredError, Huber, MeanAbsoluteError
import matplotlib.pyplot as plt
from tensorflow.keras.metrics import RootMeanSquaredError
"""**Data Preperation**"""
data = pd.read_csv("train.csv", ",")
data.head()
data.shape
sns.pairplot(data[['years', 'km', 'rating', 'condition', 'economy','top speed', 'hp', 'torque', 'current price']], diag_kind='kde')
tensor_data = tf.constant(data)
tensor_data = tf.cast(tensor_data,tf.float32)
print(tensor_data)
print(tensor_data[:8])
tensor_data = tf.random.shuffle(tensor_data)
print(tensor_data[:8])
X = tensor_data [:, 3:-1]
print(X[:8])
y = tensor_data [:,-1]
print(y.shape)
y = tf.expand_dims(y, axis = -1)
print(y[:5])
normalizer = Normalization(mean=5, variance=4)
X_normalized = tf.constant([[3, 4, 5, 6, 7],
[4, 5, 6, 7, 8]])
normalizer(X_normalized)
normalizer = Normalization()
X_normalized = tf.constant([[3, 4, 5, 6, 7],
[4, 5, 6, 7, 8]])
normalizer.adapt(X_normalized)
normalizer(X_normalized)
print((3-3.5)/0.5)
print("",(4-3.5)/0.5)
normalizer = Normalization()
X_normalized = tf.constant([[3, 4, 5, 6, 7],
[4, 10, 6, 7, 8],
[32, 1, 56, 3, 5]])
normalizer.adapt(X_normalized)
normalizer(X_normalized)
print(X.shape)
TRAIN_RATIO = 0.8
VAL_RATIO = 0.1
TEST_RATIO = 0.1
DATASET_SIZE = len(X)
X_train = X[:int(DATASET_SIZE*TRAIN_RATIO)]
y_train = y[:int(DATASET_SIZE*TRAIN_RATIO)]
print(X_train.shape)
print(y_train.shape)
train_dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train))
train_dataset = train_dataset.shuffle(buffer_size=8,
reshuffle_each_iteration=True).batch(32).prefetch(tf.data.AUTOTUNE)
for t in train_dataset:
print(X, y)
break
X_train = X[:int(DATASET_SIZE * TRAIN_RATIO)]
y_train = y[:int(DATASET_SIZE * TRAIN_RATIO)]
X_val = X[int(DATASET_SIZE * TRAIN_RATIO):int(DATASET_SIZE * (TRAIN_RATIO + VAL_RATIO))]
y_val = y[int(DATASET_SIZE * TRAIN_RATIO):int(DATASET_SIZE * (TRAIN_RATIO + VAL_RATIO))]
print(X_val.shape)
print(y_val.shape)
val_dataset = tf.data.Dataset.from_tensor_slices((X_val, y_val))
val_dataset = train_dataset.shuffle(buffer_size=8,
reshuffle_each_iteration=True).batch(32).prefetch(tf.data.AUTOTUNE)
X_test = tf.data.Dataset.from_tensor_slices((X_test, y_test))
y_test = train_dataset.shuffle(buffer_size=8,
reshuffle_each_iteration=True).batch(32).prefetch(tf.data.AUTOTUNE)
X_test = X[int(DATASET_SIZE * (TRAIN_RATIO+VAL_RATIO)):]
y_test = y[int(DATASET_SIZE * (TRAIN_RATIO+VAL_RATIO)):]
print(X_val.shape)
print(y_val.shape)
normalizer = Normalization()
normalizer.adapt(X_train)
normalizer(X)[:5]
model = tf.keras.Sequential([
InputLayer(input_shape=(8,)),
normalizer,
Dense(128, activation='relu'),
Dense(128, activation='relu'),
Dense(128, activation='relu'),
Dense(1)
])
model.summary()
tf.keras.utils.plot_model(model, to_file="model.png", show_shapes=True)
model.compile(optimizer = Adam(learning_rate=0.1),
loss = MeanAbsoluteError(),
metrics = RootMeanSquaredError())
history = model.fit(train_dataset,
validation_data=(X_val, y_val) ,
epochs = 100, verbose = 1)
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val_loss'])
plt.show()
plt.plot(history.history['root_mean_squared_error'])
plt.plot(history.history['val_root_mean_squared_error'])
plt.title('model performance')
plt.ylabel('rmse')
plt.xlabel('epoch')
plt.legend(['train', 'val'])
plt.show()
model.evaluate(X_test, y_test)
plt.plot(history.history['root_mean_squared_error'])
plt.plot(history.history['val_root_mean_squared_error'])
plt.title('model performance')
plt.ylabel('rmse')
plt.xlabel('epoch')
plt.legend(['train', 'val'])
plt.show()
model.evaluate(X_test,y_test)
X_test
model.predict(tf.expand_dims(X_test[0], axis = 0))
y_pred = list(model.predict(X_test)[:,0])
print(y_pred)
ind = np.arange(100)
plt.figure(figsize=(40, 20))
width = 0.1
plt.bar(ind, y_pred, width, label='Predicted Car Price')
plt.bar(ind + width, y_true, width, label='Actual Car Price')
plt.xlabel('Actual vs Predicted Prices')
plt.ylabel('Car Price Prices')
plt.show