ardian407 commited on
Commit
8f2ce94
1 Parent(s): 59cd3f0

Upload 10 files

Browse files
Files changed (10) hide show
  1. app.py +9 -0
  2. dataset.csv +0 -0
  3. eda.py +162 -0
  4. hot_encoder.pkl +3 -0
  5. ord_encoder.pkl +3 -0
  6. pipelines.pkl +3 -0
  7. predictions.py +73 -0
  8. requirements.txt +8 -0
  9. rf_model.pkl +3 -0
  10. scaler.pkl +3 -0
app.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import eda
3
+ import predictions
4
+
5
+ halaman = st.sidebar.selectbox('Halaman: ',('EDA', 'Prediction'))
6
+ if halaman == 'EDA':
7
+ eda.run()
8
+ else:
9
+ predictions.run()
dataset.csv ADDED
The diff for this file is too large to render. See raw diff
 
eda.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import seaborn as sns
3
+ import plotly.express as px
4
+ import matplotlib.pyplot as plt
5
+ import pandas as pd
6
+ import numpy as np
7
+ from plotly.subplots import make_subplots
8
+ import plotly.graph_objects as go
9
+
10
+ def run():
11
+ # title
12
+ st.title('EDA Analysis Used Car Price')
13
+ st.write('EDA ini terfokus pada eksplorasi untuk memahami data lebih dalam dengan melihat distribusi data, korelasi atau hubungan antar kolom dan eksplorasi berdasarkan business domain.')
14
+ st.markdown('---')
15
+
16
+ dataset = pd.read_csv('dataset.csv')
17
+ st.markdown("<h4 style='text-align: center; color: white;'>Dataset Preview</h4>", unsafe_allow_html=True)
18
+ st.dataframe(dataset,hide_index=True, height=200, width=1000)
19
+ st.write("Deskripsi Kolom: ")
20
+ st.write('`model` = Tipe atau model mobil (categorical - nominal)')
21
+ st.write('`year` = Tahun pembuatan mobil (categorical - ordinal)')
22
+ st.write('`price` = Harga (dalam Pound Sterling - numerical)')
23
+ st.write('`transmission` = Tipe transmisi mobil (categorical - nominal)')
24
+ st.write('`mileage` = Jumlah jarak tempuh dalam miles (numerical)')
25
+ st.write('`fuelType` = Jenis bahan bakar (cateogrical - nominal)')
26
+ st.write('`tax` = Jumlah pajak dalam Pound Sterling')
27
+ st.write('`mpg`= Miles per Gallon (1 gallon = 3.78541 liter - numerical) ')
28
+ st.write('`engineSize` = Ukuran mesin (Numerical)')
29
+ st.write('`company` = Brand atau nama perusahaan pembuat mobil (categorical - nominal)')
30
+ st.markdown('---')
31
+
32
+ numeric_data = dataset[['mileage','tax','engineSize','mpg']]
33
+
34
+ st.markdown("<h3 style='text-align: center; color: white;'>Perkembangan Harga Pertahun</h3>", unsafe_allow_html=True)
35
+ year = dataset[['year', 'price']].groupby('year').mean()
36
+ audi = dataset[['year', 'price']][dataset['company'] == "Audi"].groupby('year').mean()
37
+ toyota = dataset[['year', 'price']][dataset['company'] == "Toyota"].groupby('year').mean()
38
+ hyundai = dataset[['year', 'price']][dataset['company'] == "Hyundai"].groupby('year').mean()
39
+ bmw = dataset[['year', 'price']][dataset['company'] == "BMW"].groupby('year').mean()
40
+
41
+ # Reindex the 'audi' DataFrame to match the years in the 'year' DataFrame
42
+ audi = audi.reindex(year.index, fill_value=0)
43
+ toyota = toyota.reindex(year.index, fill_value=0)
44
+ hyundai = hyundai.reindex(year.index, fill_value=0)
45
+ bmw = bmw.reindex(year.index, fill_value=0)
46
+
47
+ # Create a Plotly figure
48
+ fig = go.Figure()
49
+
50
+ # Plot the average price for all cars with a blue solid line
51
+ fig.add_trace(go.Scatter(x=year.index, y=year['price'], mode='lines', name='All Cars', line=dict(color='cyan')))
52
+
53
+ # Plot the average price for Audi cars with a red dashed line
54
+ fig.add_trace(go.Scatter(x=audi.index, y=audi['price'], mode='lines', name='Audi', line=dict(color='red', dash='dash')))
55
+ fig.add_trace(go.Scatter(x=toyota.index, y=toyota['price'], mode='lines', name='Toyota', line=dict(color='blue', dash='dash')))
56
+ fig.add_trace(go.Scatter(x=hyundai.index, y=hyundai['price'], mode='lines', name='Hyundai', line=dict(color='yellow', dash='dash')))
57
+ fig.add_trace(go.Scatter(x=bmw.index, y=bmw['price'], mode='lines', name='BMW', line=dict(color='white', dash='dash')))
58
+
59
+ # Customize the layout
60
+ fig.update_layout(
61
+ title='Average Price by Year',
62
+ xaxis_title='Year',
63
+ yaxis_title='Average Price',
64
+ xaxis=dict(tickvals=year.index, ticktext=year.index, tickangle=45),
65
+ legend=dict(x=0, y=1)
66
+ )
67
+
68
+ # Display the Plotly figure using Streamlit
69
+ st.plotly_chart(fig)
70
+ st.write('Dari chart di atas, kita bisa melihat bahwa:\n- Setiap perusahaan memiliki rata-rata yang berbeda dari tahun ke tahun.\n- Rata-rata harga pada semua perusahaan mengalami kenaikan yang mirip sebagaimana bertambahnya tahun. Ini menandakan semakin muda sebuah mobil, maka harga nya semakin tinggi.')
71
+
72
+ st.markdown('---')
73
+ st.markdown("<h3 style='text-align: center; color: white;'>Average Price berdasarkan Brand</h3>", unsafe_allow_html=True)
74
+ fig=plt.figure(figsize=(7,5))
75
+ ax=sns.barplot(dataset, x='company', y='price', estimator='mean', palette='viridis')
76
+ plt.bar_label(ax.containers[0], label_type='center', color='white')
77
+ st.pyplot(fig)
78
+ st.write('Terlihat bahwa company yang ada terbagi seperti terbagi menjadi 2 kelas. Kelas dengan rata-rata harga yang tinggi yaitu Audi dan BMW, lalu kelas dengan harga rata-rata yang rendah yaitu Toyota dan Hyundai.')
79
+ st.markdown('---')
80
+
81
+
82
+ st.markdown("<h3 style='text-align: center; color: white;'>Average Price Model berdasarkan Brand</h3>", unsafe_allow_html=True)
83
+ company = dataset['company'].unique().tolist()
84
+
85
+ fig=plt.figure(figsize=(20,30))
86
+ for i, comp in enumerate(company):
87
+ plt.subplot(3,2,i+1)
88
+ data = dataset[['model','price']][dataset['company']==comp].groupby('model').mean().sort_values("price", ascending=False)
89
+ ax=sns.barplot(data, x='price', y=data.index, palette='viridis')
90
+ plt.bar_label(ax.containers[0])
91
+ plt.title(f"Rata-Rata Harga {comp}")
92
+ st.pyplot(fig)
93
+ st.write('Kita bisa melihat bahwa setiap model dari setiap company memiliki harga rata-rata yang berbeda satu sama lain namun terdapat kemiripan antar model, hal ini akan digunakan sebagai tolak ukur pada proses pengurangan cardinality di feature engineering. ')
94
+ st.markdown('---')
95
+
96
+
97
+ st.markdown("<h3 style='text-align: center; color: white;'>Average Price berdasarkan Tipe Transmisi</h3>", unsafe_allow_html=True)
98
+
99
+ fig=plt.figure(figsize=(12,8))
100
+ ax=sns.barplot(dataset, x='transmission', y='price', estimator='mean', palette='Blues')
101
+ plt.bar_label(ax.containers[0], label_type='center', fontsize=14)
102
+ st.pyplot(fig)
103
+ st.write('Ketika melihat rata-rata harga setiap transmission, kita bisa lihat bahwa yang paling mahal justru adalah semi-auto, disusul automatic, lalu other, dan Manual. Ini bisa disebabkan oleh adanya outliers. Pada dunia nyata jika diurutkan dari yang termurah yaitu manual, semi-auto, automatic.')
104
+ st.markdown('---')
105
+
106
+ st.markdown("<h3 style='text-align: center; color: white;'>Rata-Rata Efisiensi Bahan Bakar berdasarkan Brand</h3>", unsafe_allow_html=True)
107
+
108
+ fig = plt.figure(figsize=(10, 8))
109
+ ax=sns.barplot(dataset, x='company', y='mpg', estimator='mean', palette='viridis')
110
+ plt.bar_label(ax.containers[0], label_type='center')
111
+ st.pyplot(fig)
112
+ st.write('Dari sini kita melihat bahwa Brand dengan efisiensi bahan bakar terbaik adalah Audi, disusul dengan Hyundai, BMW dan Toyota. Semakin kecil rata-rata efisiensi bahan bakar, semakin irit atau hemat konsumsi bahan bakar sebuah mobil.')
113
+ st.markdown('---')
114
+
115
+ st.markdown("<h3 style='text-align: center; color: white;'>Efisiensi Berdasarkan Transmission</h3>", unsafe_allow_html=True)
116
+
117
+ fig=plt.figure(figsize=(10,6))
118
+ ax = sns.barplot(data=dataset, x='transmission', y='mpg', estimator='mean')
119
+ plt.bar_label(ax.containers[0], label_type='center')
120
+ st.pyplot(fig)
121
+ st.write('Disini kita bisa melihat bahwa Semi-Auto memiliki efisiensi yang paling baik di antara tipe transmissi lain.')
122
+ st.markdown('---')
123
+
124
+
125
+ st.markdown("<h3 style='text-align: center; color: white;'>Data Distribution</h3>", unsafe_allow_html=True)
126
+ # list nama kolom
127
+ cols = dataset[['price', 'mileage', 'tax', 'mpg', 'engineSize']]
128
+ # figur size
129
+ fig=plt.figure(figsize=(30,13))
130
+
131
+ # iterasi untuk membuat chart
132
+ for i, col in enumerate(cols):
133
+ plt.subplot(2,3, i+1) # subplot
134
+ sns.histplot(dataset[col], kde=True, bins=30) #histogram plot
135
+ plt.title(f' Distribusi {col} \nskewness: {dataset[col].skew():.4f}') # judul plot beserta skewness
136
+ plt.xticks(rotation=20)
137
+ st.pyplot(fig)
138
+ st.write('Terlihat hanya kolom tax yang memiliki skewness mendekati normal.')
139
+ st.markdown('---')
140
+
141
+
142
+ st.markdown("<h3 style='text-align: center; color: white;'>Korelasi antara numerik Variables</h3>", unsafe_allow_html=True)
143
+ fig=plt.figure(figsize=(7,7))
144
+ sns.heatmap(numeric_data.corr("spearman"), annot=True, cmap='Blues')
145
+ st.pyplot(fig)
146
+ st.write('- Nilai korelasi terkuat terhadap price ada pada variable year dan engine Size.\n- Sedangkan variable yang paling lemah ada pada kolom Tax')
147
+ st.markdown('---')
148
+
149
+
150
+ st.markdown("<h3 style='text-align: center; color: white;'>Linearitas antara price dengan variable lain</h3>", unsafe_allow_html=True)
151
+ pair = ['mileage', 'year','engineSize', 'mpg']
152
+ fig=plt.figure(figsize=(15,10))
153
+ for i, col in enumerate(pair):
154
+ plt.subplot(2,2,i+1)
155
+ sns.scatterplot(dataset, y='price', x=col)
156
+ plt.title(f'Korelasi antara price dan {col}')
157
+ st.pyplot(fig)
158
+ st.write("Dari chart di atas dapat dikatakan:\n- Semakin tinggi jarak tempuh (mileage) sebuah mobil, maka semakin murah harganya. Mobil dengan jarak tempuh yang sedikit, cenderung memiliki harga yang tinggi.\n- Semakin muda usia mobil, harga nya pun semakin mahal. \n- Untuk engineSize, tidak terlalu terlihat pola pada scatter. Namun, kita bisa sedikitnya melihat bahwa ada kecenderungan ketika engineSize semakin besar, maka harga cenderung lebih mahal.\n- Hubungan antara price dan mpg menunjukan bahwa semakin efisien konsumsi bahan bakar mobil, maka harga cenderung bisa lebih mahal")
159
+ st.markdown('---')
160
+
161
+ if __name__ == '__main__':
162
+ run()
hot_encoder.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:24d936998400edb8909c98d04eb8d1391834490b914ed1755c85e265dd96e921
3
+ size 2605
ord_encoder.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3a62568e04a76876c9454105c97f25520efaa3e594b5dafaa7526cce6f7291f2
3
+ size 1444
pipelines.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6ad7b4bb4c8f8be475985afbfd1fa97992357a81666c12eaf1ce40095d37957e
3
+ size 178683728
predictions.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import joblib
4
+
5
+ # load pipelines dengan joblib
6
+ pipe = joblib.load('pipelines.pkl')
7
+
8
+ dataset = pd.read_csv('dataset.csv')
9
+ # buat fungsi untuk run
10
+ def run():
11
+ # buat form
12
+ st.write('## Predict Used Car Price')
13
+ my_dict = {"Audi": dataset['model'][dataset['company']=='Audi'].unique().tolist(),
14
+ "Toyota": dataset['model'][dataset['company']=='Toyota'].unique().tolist(),
15
+ "BMW": dataset['model'][dataset['company']=='BMW'].unique().tolist(),
16
+ "Hyundai": dataset['model'][dataset['company']=='Hyundai'].unique().tolist()}
17
+ col1, col2 = st.columns([1, 1])
18
+ with col1:
19
+ company = st.selectbox('Brand', options=my_dict.keys())
20
+ with col2:
21
+ model = st.selectbox('Pilih Model', options=my_dict[company])
22
+
23
+ column1, column2 = st.columns([2,2])
24
+ with column1:
25
+ year = st.selectbox('Tahun', options=[int(x) for x in range(2020, 1990, -1)])
26
+ with column2:
27
+ transimssion = st.selectbox('Tipe Transmisi', options=dataset['transmission'].unique().tolist())
28
+
29
+ kol1, kol2, kol3 = st.columns([3,1,1])
30
+ with kol1:
31
+ mileage = st.slider('Jarak Tempuh',0,100000,1000)
32
+ with kol2:
33
+ fueltype = st.selectbox('Jenis Bahan Bakar', options=dataset['fuelType'].unique().tolist())
34
+ with kol3:
35
+ mpg = st.number_input('Efisiensi', min_value=0, value=50, step=1, max_value=100, help="Input Efisiensi Bahan Bakar")
36
+ engineSize=st.selectbox('Ukuran Mesin', options=dataset['engineSize'].unique().tolist())
37
+ with st.form('Form Car Details'):
38
+
39
+ company=company
40
+ model=model
41
+ tahun=year
42
+ trans=transimssion
43
+ efisiensi = mpg
44
+ engine = engineSize
45
+ submitted = st.form_submit_button('Predict')
46
+
47
+
48
+ # dictionary hasil data input
49
+ data = {
50
+ 'model': model,
51
+ 'year': (int(tahun)),
52
+ 'transmission': trans,
53
+ 'mileage':mileage,
54
+ 'fuelType':fueltype,
55
+ 'mpg':efisiensi,
56
+ 'engineSize': engine,
57
+ 'company':company,
58
+ }
59
+
60
+ # data inference ke dataframe
61
+ data_inf = pd.DataFrame([data]).reset_index(drop=True)
62
+
63
+ # tampilkan hasil input dalam dataframe
64
+ st.dataframe(data_inf)
65
+
66
+ # if clause jika tombol sudah di tekan
67
+ if submitted:
68
+ prediction = pipe.predict(data_inf)
69
+ st.write(f'#### Prediction: GBP {str(int(prediction))} atau IDR {str(int(prediction)*19230.08)}')
70
+
71
+ # supaya halaman berjalan
72
+ if __name__ == '__main__':
73
+ run()
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ pandas
3
+ seaborn
4
+ matplotlib
5
+ numpy
6
+ scikit-learn==1.2.2
7
+ Pillow
8
+ plotly
rf_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eead2fd3069bfa560154c01ce9e3873f356cccc4d380340be057704aa67202b2
3
+ size 178667521
scaler.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:739a49283d91fa1462cf15b19f2a0f81cf39798b0b3edff44dd67b1e320b5b78
3
+ size 1135