File size: 10,547 Bytes
2a70c18 |
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 |
# app.py
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
# Page configuration
st.set_page_config(page_title="Data Analysis Platform", layout="wide")
# Initialize session state
if 'data' not in st.session_state:
# Create sample data
np.random.seed(42)
dates = pd.date_range('2023-01-01', periods=100, freq='D')
st.session_state.data = pd.DataFrame({
'date': dates,
'sales': np.random.normal(1000, 200, 100),
'visitors': np.random.normal(500, 100, 100),
'conversion_rate': np.random.uniform(0.01, 0.05, 100),
'customer_satisfaction': np.random.normal(4.2, 0.5, 100),
'region': np.random.choice(['North', 'South', 'East', 'West'], 100)
})
# Sidebar for navigation
st.sidebar.title("Data Analytics Platform")
page = st.sidebar.radio("Navigation", ["Home", "Data Explorer", "Visualization", "Predictions"])
# Home page
if page == "Home":
st.title("Data Analysis Platform")
st.markdown("""
Welcome to the Data Analysis Platform. Explore your data with powerful
visualizations and machine learning insights.
""")
col1, col2 = st.columns(2)
with col1:
st.subheader("Upload Your Dataset")
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
if uploaded_file is not None:
try:
st.session_state.data = pd.read_csv(uploaded_file)
st.success("Data uploaded successfully!")
except Exception as e:
st.error(f"Error uploading file: {e}")
with col2:
st.subheader("Dataset Overview")
st.write(st.session_state.data.describe())
# Data Explorer page
elif page == "Data Explorer":
st.title("Data Explorer")
# Data summary
st.subheader("Dataset Summary")
st.write(f"Shape: {st.session_state.data.shape[0]} rows, {st.session_state.data.shape[1]} columns")
# Show first few rows
st.subheader("Data Preview")
st.dataframe(st.session_state.data.head())
# Column analysis
st.subheader("Column Analysis")
col1, col2 = st.columns(2)
with col1:
column = st.selectbox("Select column to analyze:", st.session_state.data.columns)
with col2:
if pd.api.types.is_numeric_dtype(st.session_state.data[column]):
analysis_type = st.selectbox(
"Analysis type:",
["Distribution", "Time Series"] if "date" in column.lower() else ["Distribution"]
)
else:
analysis_type = st.selectbox("Analysis type:", ["Value Counts"])
# Display analysis
if pd.api.types.is_numeric_dtype(st.session_state.data[column]):
st.write(f"**Min:** {st.session_state.data[column].min():.2f}")
st.write(f"**Max:** {st.session_state.data[column].max():.2f}")
st.write(f"**Mean:** {st.session_state.data[column].mean():.2f}")
st.write(f"**Median:** {st.session_state.data[column].median():.2f}")
st.write(f"**Std Dev:** {st.session_state.data[column].std():.2f}")
fig, ax = plt.subplots(figsize=(10, 6))
sns.histplot(st.session_state.data[column], ax=ax, kde=True)
ax.set_title(f"Distribution of {column}")
st.pyplot(fig)
else:
value_counts = st.session_state.data[column].value_counts()
st.write(f"**Unique Values:** {len(value_counts)}")
st.write(f"**Most Common:** {value_counts.index[0]} ({value_counts.iloc[0]} occurrences)")
fig, ax = plt.subplots(figsize=(10, 6))
value_counts.plot(kind='bar', ax=ax)
ax.set_title(f"Value counts for {column}")
st.pyplot(fig)
# Visualization page
elif page == "Visualization":
st.title("Data Visualization")
chart_type = st.selectbox(
"Select chart type:",
["Bar Chart", "Line Chart", "Scatter Plot", "Heatmap"]
)
if chart_type in ["Bar Chart", "Line Chart"]:
col1, col2 = st.columns(2)
with col1:
x_column = st.selectbox("X-axis:", st.session_state.data.columns)
with col2:
y_column = st.selectbox("Y-axis:",
[col for col in st.session_state.data.columns
if pd.api.types.is_numeric_dtype(st.session_state.data[col])])
# Aggregation for categorical x-axis
if not pd.api.types.is_numeric_dtype(st.session_state.data[x_column]):
agg_data = st.session_state.data.groupby(x_column)[y_column].mean().reset_index()
fig, ax = plt.subplots(figsize=(10, 6))
if chart_type == "Bar Chart":
sns.barplot(x=x_column, y=y_column, data=agg_data, ax=ax)
else: # Line chart
sns.lineplot(x=x_column, y=y_column, data=agg_data, ax=ax, marker='o')
ax.set_title(f"{y_column} by {x_column}")
st.pyplot(fig)
else:
fig, ax = plt.subplots(figsize=(10, 6))
if chart_type == "Bar Chart":
sns.barplot(x=x_column, y=y_column, data=st.session_state.data, ax=ax)
else: # Line chart
sns.lineplot(x=x_column, y=y_column, data=st.session_state.data, ax=ax)
ax.set_title(f"{y_column} vs {x_column}")
st.pyplot(fig)
elif chart_type == "Scatter Plot":
col1, col2 = st.columns(2)
with col1:
x_column = st.selectbox("X-axis:",
[col for col in st.session_state.data.columns
if pd.api.types.is_numeric_dtype(st.session_state.data[col])])
with col2:
y_column = st.selectbox("Y-axis:",
[col for col in st.session_state.data.columns
if pd.api.types.is_numeric_dtype(st.session_state.data[col]) and col != x_column])
fig, ax = plt.subplots(figsize=(10, 6))
sns.scatterplot(x=x_column, y=y_column, data=st.session_state.data, ax=ax)
ax.set_title(f"{y_column} vs {x_column}")
st.pyplot(fig)
elif chart_type == "Heatmap":
numeric_cols = st.session_state.data.select_dtypes(include=['number']).columns.tolist()
correlation = st.session_state.data[numeric_cols].corr()
fig, ax = plt.subplots(figsize=(10, 8))
sns.heatmap(correlation, annot=True, cmap='coolwarm', ax=ax)
ax.set_title("Correlation Heatmap")
st.pyplot(fig)
# Predictions page
elif page == "Predictions":
st.title("ML Predictions")
numeric_cols = st.session_state.data.select_dtypes(include=['number']).columns.tolist()
st.subheader("Train a Model")
col1, col2 = st.columns(2)
with col1:
target_column = st.selectbox("Target variable:", numeric_cols)
with col2:
model_type = st.selectbox("Model type:", ["Linear Regression", "Random Forest"])
# Select features
feature_cols = [col for col in numeric_cols if col != target_column]
selected_features = st.multiselect("Select features:", feature_cols, default=feature_cols)
if st.button("Train Model"):
if len(selected_features) > 0:
# Prepare data
X = st.session_state.data[selected_features]
y = st.session_state.data[target_column]
# Split data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Scale features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Train model
if model_type == "Linear Regression":
model = LinearRegression()
else:
model = RandomForestRegressor(n_estimators=100, random_state=42)
model.fit(X_train_scaled, y_train)
# Evaluate
train_score = model.score(X_train_scaled, y_train)
test_score = model.score(X_test_scaled, y_test)
st.session_state.model = model
st.session_state.scaler = scaler
st.session_state.features = selected_features
st.success("Model trained successfully!")
st.write(f"Training R² score: {train_score:.4f}")
st.write(f"Testing R² score: {test_score:.4f}")
# Feature importance for Random Forest
if model_type == "Random Forest":
importance = pd.DataFrame({
'Feature': selected_features,
'Importance': model.feature_importances_
}).sort_values('Importance', ascending=False)
fig, ax = plt.subplots(figsize=(10, 6))
sns.barplot(x='Importance', y='Feature', data=importance, ax=ax)
ax.set_title("Feature Importance")
st.pyplot(fig)
else:
st.error("Please select at least one feature")
# Make predictions section
st.subheader("Make Predictions")
if 'model' in st.session_state:
input_data = {}
# Create input fields for each feature
for feature in st.session_state.features:
min_val = float(st.session_state.data[feature].min())
max_val = float(st.session_state.data[feature].max())
mean_val = float(st.session_state.data[feature].mean())
input_data[feature] = st.slider(
f"Input {feature}:",
min_value=min_val,
max_value=max_val,
value=mean_val
)
if st.button("Predict"):
# Prepare input for prediction
input_df = pd.DataFrame([input_data])
input_scaled = st.session_state.scaler.transform(input_df)
# Make prediction
prediction = st.session_state.model.predict(input_scaled)[0]
st.success(f"Predicted {target_column}: {prediction:.2f}")
else:
st.info("Train a model first to make predictions") |