Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -3,21 +3,16 @@ 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 |
-
|
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,44 +21,51 @@ try:
|
|
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 |
-
#
|
35 |
-
st.
|
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 |
except FileNotFoundError:
|
69 |
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 configuration
|
7 |
+
st.set_page_config(page_title="Crime Rate Predictor", layout="centered")
|
8 |
+
st.title("🔮 Crime Rate Prediction for Indian States/UTs")
|
9 |
|
10 |
+
# CSV path (Hosted online)
|
11 |
+
csv_path = "https://huggingface.co/spaces/MLDeveloper/crime_rate_predicition/resolve/main/RS_Session_255_AS_116.1%20(2).csv"
|
12 |
|
13 |
try:
|
14 |
+
# Load and preprocess data
|
15 |
df = pd.read_csv(csv_path)
|
|
|
|
|
|
|
|
|
|
|
16 |
data = df[[
|
17 |
'State/UT',
|
18 |
'Number of Cases Registered - 2018-19',
|
|
|
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 |
+
# --- User Inputs ---
|
28 |
+
st.subheader("📝 Enter Details to Predict Future Crime Rates")
|
29 |
+
|
30 |
+
# Dropdown for State selection
|
31 |
+
state_input = st.selectbox("Select State/UT", sorted(data['State/UT'].unique()))
|
32 |
+
|
33 |
+
# Slider for year selection
|
34 |
+
year_input = st.slider("Select Starting Year", 2022, 2026, 2022)
|
35 |
|
36 |
+
if state_input:
|
37 |
+
if state_input in data['State/UT'].values:
|
38 |
+
selected_row = data[data['State/UT'] == state_input].iloc[0]
|
39 |
+
X_train = pd.DataFrame({'Year': [2018, 2019, 2020, 2021]})
|
40 |
+
y_train = selected_row[['2018', '2019', '2020', '2021']].values
|
41 |
|
42 |
+
# Train model and predict
|
43 |
+
model = LinearRegression()
|
44 |
+
model.fit(X_train, y_train)
|
45 |
|
46 |
+
future_years = list(range(year_input, 2028))
|
47 |
+
predictions = model.predict(pd.DataFrame({'Year': future_years}))
|
48 |
|
49 |
+
result_df = pd.DataFrame({
|
50 |
+
'Year': future_years,
|
51 |
+
'Predicted Crime Cases': [max(0, int(pred)) for pred in predictions]
|
52 |
+
})
|
|
|
53 |
|
54 |
+
# Show predictions
|
55 |
+
st.subheader(f"📈 Predicted Crime Rate for {state_input} ({year_input} to 2027)")
|
56 |
+
st.dataframe(result_df, use_container_width=True)
|
57 |
|
58 |
+
# Plot
|
59 |
+
fig, ax = plt.subplots()
|
60 |
+
ax.plot(result_df['Year'], result_df['Predicted Crime Cases'], marker='o', linestyle='--', color='orangered')
|
61 |
+
ax.set_xlabel("Year")
|
62 |
+
ax.set_ylabel("Predicted Crime Cases")
|
63 |
+
ax.set_title(f"{state_input} Crime Rate Prediction")
|
64 |
+
st.pyplot(fig)
|
65 |
+
else:
|
66 |
+
st.warning("⚠️ Please enter a valid State/UT name from the dataset.")
|
67 |
+
else:
|
68 |
+
st.info("👈 Please enter a State/UT name to begin prediction.")
|
69 |
|
70 |
except FileNotFoundError:
|
71 |
st.error(f"❌ File not found at path: {csv_path}. Please check the path.")
|