Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -3,16 +3,21 @@ import pandas as pd
|
|
3 |
from sklearn.linear_model import LinearRegression
|
4 |
import matplotlib.pyplot as plt
|
5 |
|
6 |
-
# Page
|
7 |
-
st.set_page_config(page_title="Crime Rate
|
8 |
-
st.title("
|
9 |
|
10 |
-
# CSV path (
|
11 |
-
csv_path = "
|
12 |
|
13 |
try:
|
14 |
-
# Load
|
15 |
df = pd.read_csv(csv_path)
|
|
|
|
|
|
|
|
|
|
|
16 |
data = df[[
|
17 |
'State/UT',
|
18 |
'Number of Cases Registered - 2018-19',
|
@@ -21,47 +26,44 @@ try:
|
|
21 |
'Number of Cases Registered - 2021-22 (up to 31.10.2021)'
|
22 |
]].copy()
|
23 |
data.columns = ['State/UT', '2018', '2019', '2020', '2021']
|
|
|
|
|
24 |
for col in ['2018', '2019', '2020', '2021']:
|
25 |
data[col] = pd.to_numeric(data[col], errors='coerce').fillna(0).astype(int)
|
26 |
|
27 |
-
#
|
28 |
-
st.
|
29 |
-
|
30 |
-
|
31 |
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
|
38 |
-
|
39 |
-
|
40 |
-
model.fit(X_train, y_train)
|
41 |
|
42 |
-
|
43 |
-
|
44 |
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
|
|
49 |
|
50 |
-
|
51 |
-
|
52 |
-
st.dataframe(result_df, use_container_width=True)
|
53 |
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
else:
|
62 |
-
st.warning("⚠️ Please enter a valid State/UT name from the dataset.")
|
63 |
-
else:
|
64 |
-
st.info("👈 Please enter a State/UT name to begin prediction.")
|
65 |
|
66 |
except FileNotFoundError:
|
67 |
st.error(f"❌ File not found at path: {csv_path}. Please check the path.")
|
|
|
3 |
from sklearn.linear_model import LinearRegression
|
4 |
import matplotlib.pyplot as plt
|
5 |
|
6 |
+
# Page config
|
7 |
+
st.set_page_config(page_title="Crime Rate Prediction", layout="wide")
|
8 |
+
st.title("📊 Crime Rate Prediction Based on Past Data")
|
9 |
|
10 |
+
# CSV path (Make sure this file is uploaded in Streamlit cloud if deployed)
|
11 |
+
csv_path = "crime_data.csv"
|
12 |
|
13 |
try:
|
14 |
+
# Load the dataset
|
15 |
df = pd.read_csv(csv_path)
|
16 |
+
|
17 |
+
st.subheader("📄 Raw Dataset")
|
18 |
+
st.dataframe(df)
|
19 |
+
|
20 |
+
# Preprocess
|
21 |
data = df[[
|
22 |
'State/UT',
|
23 |
'Number of Cases Registered - 2018-19',
|
|
|
26 |
'Number of Cases Registered - 2021-22 (up to 31.10.2021)'
|
27 |
]].copy()
|
28 |
data.columns = ['State/UT', '2018', '2019', '2020', '2021']
|
29 |
+
|
30 |
+
# Convert string numbers to integers (if needed)
|
31 |
for col in ['2018', '2019', '2020', '2021']:
|
32 |
data[col] = pd.to_numeric(data[col], errors='coerce').fillna(0).astype(int)
|
33 |
|
34 |
+
# Sidebar for user input
|
35 |
+
st.sidebar.header("🔍 Predict Future Crime")
|
36 |
+
selected_state = st.sidebar.selectbox("Select a State/UT", data['State/UT'].unique())
|
37 |
+
start_year = st.sidebar.slider("Select starting year for prediction", 2022, 2026, 2022)
|
38 |
|
39 |
+
# Perform prediction for selected state
|
40 |
+
selected_row = data[data['State/UT'] == selected_state].iloc[0]
|
41 |
+
years = [2018, 2019, 2020, 2021]
|
42 |
+
X_train = pd.DataFrame({'Year': years})
|
43 |
+
y_train = selected_row[['2018', '2019', '2020', '2021']].values
|
44 |
|
45 |
+
model = LinearRegression()
|
46 |
+
model.fit(X_train, y_train)
|
|
|
47 |
|
48 |
+
future_years = list(range(start_year, 2028))
|
49 |
+
predictions = model.predict(pd.DataFrame({'Year': future_years}))
|
50 |
|
51 |
+
# Prepare result DataFrame
|
52 |
+
result_df = pd.DataFrame({
|
53 |
+
'Year': future_years,
|
54 |
+
'Predicted Crime Cases': [max(0, int(pred)) for pred in predictions]
|
55 |
+
})
|
56 |
|
57 |
+
st.subheader(f"📈 Predicted Crime Rate in {selected_state} ({start_year}–2027)")
|
58 |
+
st.dataframe(result_df)
|
|
|
59 |
|
60 |
+
# Plotting
|
61 |
+
fig2, ax2 = plt.subplots()
|
62 |
+
ax2.plot(result_df['Year'], result_df['Predicted Crime Cases'], marker='o', linestyle='--', color='teal')
|
63 |
+
ax2.set_xlabel("Year")
|
64 |
+
ax2.set_ylabel("Predicted Crime Cases")
|
65 |
+
ax2.set_title(f"Crime Trend Prediction for {selected_state}")
|
66 |
+
st.pyplot(fig2)
|
|
|
|
|
|
|
|
|
67 |
|
68 |
except FileNotFoundError:
|
69 |
st.error(f"❌ File not found at path: {csv_path}. Please check the path.")
|