ositamiles commited on
Commit
5985633
·
verified ·
1 Parent(s): 2344b76

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -166
app.py CHANGED
@@ -1,175 +1,142 @@
1
  import streamlit as st
2
  import pandas as pd
3
  import numpy as np
4
- import matplotlib.pyplot as plt
5
- from sklearn.preprocessing import LabelEncoder, StandardScaler
6
- from sklearn.model_selection import train_test_split
7
- import tensorflow as tf
8
- from tensorflow.keras.models import Sequential, load_model
9
- from tensorflow.keras.layers import Dense
10
- import joblib
11
- import os
12
-
13
- # Set page config
14
- st.set_page_config(page_title="Dynamic Game Pricing App", layout="wide")
15
-
16
- # Function to load or create data
17
- @st.cache_data
18
- def load_data():
19
- if os.path.exists('game_data.csv'):
20
- df = pd.read_csv('game_data.csv')
21
- else:
22
- # Sample dataset
23
- data = {
24
- 'game_id': range(1, 101),
25
- 'genre': np.random.choice(['RPG', 'FPS', 'Strategy', 'Puzzle', 'Sports'], 100),
26
- 'region': np.random.choice(['Africa', 'NA', 'EU', 'Asia', 'SA'], 100),
27
- 'release_year': np.random.randint(2018, 2024, 100),
28
- 'demand_index': np.random.uniform(0.1, 1.0, 100),
29
- 'competitor_price': np.random.uniform(20, 60, 100),
30
- 'past_sales': np.random.randint(100, 1000, 100),
31
- 'suggested_price': np.random.uniform(25, 65, 100)
32
- }
33
- df = pd.DataFrame(data)
34
- df.to_csv('game_data.csv', index=False)
35
-
36
- # Print column names for debugging
37
- st.sidebar.write("Available columns:", df.columns.tolist())
38
-
39
- return df
40
 
41
- # Load data
42
- df = load_data()
43
-
44
- # Sidebar for navigation and target column selection
45
- page = st.sidebar.selectbox("Choose a page", ["Data Explorer", "Model Training", "Price Prediction"])
46
- target_col = st.sidebar.selectbox("Select target column", df.columns.tolist())
 
 
 
 
 
 
 
47
 
48
- if page == "Data Explorer":
49
- st.title("Data Explorer")
50
- st.write(df)
51
-
52
- st.subheader("Data Statistics")
53
- st.write(df.describe())
54
-
55
- st.subheader("Data Visualization")
56
- fig, ax = plt.subplots(1, 2, figsize=(15, 5))
57
-
58
- numeric_cols = df.select_dtypes(include=['int64', 'float64']).columns
59
- x_col1 = st.selectbox("Select X-axis for first plot", numeric_cols, index=0)
60
- x_col2 = st.selectbox("Select X-axis for second plot", numeric_cols, index=min(1, len(numeric_cols)-1))
61
-
62
- ax[0].scatter(df[x_col1], df[target_col])
63
- ax[0].set_xlabel(x_col1)
64
- ax[0].set_ylabel(target_col)
65
- ax[0].set_title(f'{x_col1} vs {target_col}')
66
-
67
- ax[1].scatter(df[x_col2], df[target_col])
68
- ax[1].set_xlabel(x_col2)
69
- ax[1].set_ylabel(target_col)
70
- ax[1].set_title(f'{x_col2} vs {target_col}')
71
-
72
- st.pyplot(fig)
73
 
74
- elif page == "Model Training":
75
- st.title("Model Training")
76
-
77
- # Data preprocessing
78
- categorical_cols = df.select_dtypes(include=['object']).columns
79
- numeric_cols = df.select_dtypes(include=['int64', 'float64']).columns
80
-
81
- # Remove target column from features
82
- feature_cols = [col for col in numeric_cols if col != target_col]
83
-
84
- encoders = {}
85
- for col in categorical_cols:
86
- encoders[col] = LabelEncoder()
87
- df[f'{col}_encoded'] = encoders[col].fit_transform(df[col])
88
- feature_cols.append(f'{col}_encoded')
89
-
90
- X = df[feature_cols]
91
- y = df[target_col]
92
-
93
- scaler = StandardScaler()
94
- X_scaled = scaler.fit_transform(X)
95
-
96
- # Split the data
97
- X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
98
-
99
- # Model architecture
100
  model = Sequential([
101
- Dense(64, activation='relu', input_shape=(X_train.shape[1],)),
102
- Dense(32, activation='relu'),
103
- Dense(16, activation='relu'),
104
  Dense(1)
105
  ])
106
-
107
- model.compile(optimizer='adam', loss='mean_squared_error', metrics=['mae'])
108
-
109
- # Training
110
- if st.button("Train Model"):
111
- with st.spinner("Training in progress..."):
112
- history = model.fit(X_train, y_train, validation_split=0.2, epochs=100, batch_size=32, verbose=0)
113
-
114
- st.success("Model trained successfully!")
115
-
116
- # Plot training history
117
- fig, ax = plt.subplots(figsize=(10, 5))
118
- ax.plot(history.history['loss'], label='Training Loss')
119
- ax.plot(history.history['val_loss'], label='Validation Loss')
120
- ax.set_xlabel('Epoch')
121
- ax.set_ylabel('Loss')
122
- ax.legend()
123
- st.pyplot(fig)
124
-
125
- # Save model and preprocessing objects
126
- model.save('dynamic_pricing_model.h5')
127
- joblib.dump(scaler, 'scaler.pkl')
128
- joblib.dump(encoders, 'encoders.pkl')
129
- joblib.dump(feature_cols, 'feature_cols.pkl')
130
- joblib.dump(target_col, 'target_col.pkl')
131
-
132
- st.info("Model and preprocessing objects saved.")
133
-
134
- elif page == "Price Prediction":
135
- st.title("Price Prediction")
136
-
137
- # Load saved model and objects
138
- if os.path.exists('dynamic_pricing_model.h5'):
139
- model = load_model('dynamic_pricing_model.h5')
140
- scaler = joblib.load('scaler.pkl')
141
- encoders = joblib.load('encoders.pkl')
142
- feature_cols = joblib.load('feature_cols.pkl')
143
- saved_target_col = joblib.load('target_col.pkl')
144
-
145
- if saved_target_col != target_col:
146
- st.warning(f"Warning: The current target column ({target_col}) is different from the one used for training ({saved_target_col}). Consider retraining the model.")
147
-
148
- # User input
149
- input_data = {}
150
- for col in feature_cols:
151
- if col.endswith('_encoded'):
152
- original_col = col[:-8] # Remove '_encoded' suffix
153
- if original_col in encoders:
154
- value = st.selectbox(f"Select {original_col}", encoders[original_col].classes_)
155
- input_data[col] = encoders[original_col].transform([value])[0]
156
- else:
157
- if 'year' in col.lower():
158
- input_data[col] = st.slider(f"{col}", int(df[col].min()), int(df[col].max()), int(df[col].mean()))
159
- elif 'price' in col.lower() or 'sales' in col.lower():
160
- input_data[col] = st.slider(f"{col}", float(df[col].min()), float(df[col].max()), float(df[col].mean()))
161
- else:
162
- input_data[col] = st.slider(f"{col}", float(df[col].min()), float(df[col].max()), float(df[col].mean()))
163
-
164
- # Prepare input for prediction
165
- input_df = pd.DataFrame([input_data])
166
- input_scaled = scaler.transform(input_df)
167
-
168
- # Make prediction
169
- if st.button("Predict Price"):
170
- predicted_price = model.predict(input_scaled)[0][0]
171
- st.success(f"Predicted {saved_target_col}: {predicted_price:.2f}")
172
- else:
173
- st.warning("Please train the model first!")
174
-
175
- st.sidebar.info("This app demonstrates dynamic pricing for game codes using a Feedforward ANN.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import pandas as pd
3
  import numpy as np
4
+ import plotly.graph_objects as go
5
+ from sklearn.ensemble import GradientBoostingRegressor
6
+ from sklearn.preprocessing import StandardScaler
7
+ from tensorflow.keras.models import Sequential
8
+ from tensorflow.keras.layers import LSTM, Dense
9
+ import gym
10
+ from stable_baselines3 import PPO
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
+ # Simulated data and functions
13
+ def generate_sample_data(n_samples=1000):
14
+ dates = pd.date_range(start='2023-01-01', periods=n_samples)
15
+ df = pd.DataFrame({
16
+ 'date': dates,
17
+ 'base_price': np.random.uniform(4000000, 6000000, n_samples),
18
+ 'competitor_price': np.random.uniform(4500000, 5500000, n_samples),
19
+ 'demand': np.random.normal(100, 20, n_samples),
20
+ 'social_media_sentiment': np.random.uniform(-1, 1, n_samples),
21
+ 'economic_indicator': np.random.uniform(0.8, 1.2, n_samples),
22
+ })
23
+ df['price'] = df['base_price'] * (1 + 0.1 * df['social_media_sentiment']) * df['economic_indicator']
24
+ return df
25
 
26
+ # Step 1: Regression Model
27
+ def train_regression_model(data):
28
+ X = data[['competitor_price', 'demand', 'social_media_sentiment', 'economic_indicator']]
29
+ y = data['price']
30
+ model = GradientBoostingRegressor()
31
+ model.fit(X, y)
32
+ return model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
+ # Step 2: LSTM Model
35
+ def create_lstm_model(input_shape):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  model = Sequential([
37
+ LSTM(64, input_shape=input_shape, return_sequences=True),
38
+ LSTM(32),
 
39
  Dense(1)
40
  ])
41
+ model.compile(optimizer='adam', loss='mse')
42
+ return model
43
+
44
+ def prepare_lstm_data(data, look_back=30):
45
+ X, y = [], []
46
+ for i in range(len(data) - look_back):
47
+ X.append(data[i:(i + look_back)])
48
+ y.append(data[i + look_back])
49
+ return np.array(X), np.array(y)
50
+
51
+ # Step 3: Reinforcement Learning Environment
52
+ class PricingEnv(gym.Env):
53
+ def __init__(self, data):
54
+ super(PricingEnv, self).__init__()
55
+ self.data = data
56
+ self.current_step = 0
57
+ self.action_space = gym.spaces.Box(low=0.9, high=1.1, shape=(1,))
58
+ self.observation_space = gym.spaces.Box(low=-np.inf, high=np.inf, shape=(5,))
59
+
60
+ def reset(self):
61
+ self.current_step = 0
62
+ return self._get_observation()
63
+
64
+ def step(self, action):
65
+ self.current_step += 1
66
+ if self.current_step >= len(self.data):
67
+ return self._get_observation(), 0, True, {}
68
+
69
+ current_price = self.data.iloc[self.current_step]['price']
70
+ new_price = current_price * action[0]
71
+ reward = self._calculate_reward(new_price)
72
+
73
+ return self._get_observation(), reward, False, {}
74
+
75
+ def _get_observation(self):
76
+ obs = self.data.iloc[self.current_step][['competitor_price', 'demand', 'social_media_sentiment', 'economic_indicator', 'price']].values
77
+ return obs
78
+
79
+ def _calculate_reward(self, new_price):
80
+ base_demand = self.data.iloc[self.current_step]['demand']
81
+ price_elasticity = -1.5
82
+ demand = base_demand * (new_price / self.data.iloc[self.current_step]['price']) ** price_elasticity
83
+ revenue = new_price * demand
84
+ cost = 3000000 # Assuming a fixed cost
85
+ profit = revenue - cost
86
+ return profit
87
+
88
+ # Streamlit App
89
+ def main():
90
+ st.title("Dynamic Pricing System for GTA V Source Code")
91
+
92
+ # Generate sample data
93
+ data = generate_sample_data()
94
+
95
+ # Step 1: Regression Model
96
+ st.header("Step 1: Regression Model")
97
+ regression_model = train_regression_model(data)
98
+ latest_data = data.iloc[-1]
99
+ initial_price = regression_model.predict(latest_data[['competitor_price', 'demand', 'social_media_sentiment', 'economic_indicator']].values.reshape(1, -1))[0]
100
+ st.write(f"Initial price estimation: ${initial_price:,.2f}")
101
+
102
+ # Step 2: LSTM Model
103
+ st.header("Step 2: LSTM Model for Time-Series Adjustment")
104
+ scaler = StandardScaler()
105
+ scaled_data = scaler.fit_transform(data[['price']])
106
+ X, y = prepare_lstm_data(scaled_data)
107
+ lstm_model = create_lstm_model((X.shape[1], 1))
108
+ lstm_model.fit(X, y, epochs=50, batch_size=32, verbose=0)
109
+
110
+ last_30_days = scaled_data[-30:].reshape(1, 30, 1)
111
+ lstm_prediction = lstm_model.predict(last_30_days)
112
+ adjusted_price = scaler.inverse_transform(lstm_prediction)[0][0]
113
+ st.write(f"LSTM adjusted price: ${adjusted_price:,.2f}")
114
+
115
+ # Step 3: Reinforcement Learning
116
+ st.header("Step 3: Reinforcement Learning for Dynamic Optimization")
117
+ env = PricingEnv(data)
118
+ model = PPO("MlpPolicy", env, verbose=0)
119
+ model.learn(total_timesteps=10000)
120
+
121
+ obs = env.reset()
122
+ rl_action, _ = model.predict(obs)
123
+ final_price = adjusted_price * rl_action[0]
124
+ st.write(f"Final dynamically optimized price: ${final_price:,.2f}")
125
+
126
+ # Interactive price adjustment
127
+ st.header("Interactive Price Adjustment")
128
+ user_adjustment = st.slider("Adjust the final price (%)", -20, 20, 0)
129
+ user_price = final_price * (1 + user_adjustment / 100)
130
+ st.write(f"User adjusted price: ${user_price:,.2f}")
131
+
132
+ # Visualize pricing history
133
+ st.header("Pricing History")
134
+ fig = go.Figure()
135
+ fig.add_trace(go.Scatter(x=data['date'], y=data['price'], mode='lines', name='Historical Price'))
136
+ fig.add_trace(go.Scatter(x=[data['date'].iloc[-1]], y=[final_price], mode='markers', name='AI Suggested Price', marker=dict(size=10, color='red')))
137
+ fig.add_trace(go.Scatter(x=[data['date'].iloc[-1]], y=[user_price], mode='markers', name='User Adjusted Price', marker=dict(size=10, color='green')))
138
+ fig.update_layout(title='GTA V Source Code Pricing History', xaxis_title='Date', yaxis_title='Price ($)')
139
+ st.plotly_chart(fig)
140
+
141
+ if __name__ == "__main__":
142
+ main()