sidcww commited on
Commit
49cb95b
·
verified ·
1 Parent(s): 22733db

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -0
app.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ from tensorflow.keras.models import Sequential
6
+ from tensorflow.keras.layers import Dense, LSTM
7
+ from sklearn.preprocessing import MinMaxScaler
8
+ from sklearn.metrics import mean_squared_error
9
+ import tensorflow as tf
10
+
11
+ def create_dataset(dataset, look_back=1):
12
+ dataX, dataY = [], []
13
+ for i in range(len(dataset)-look_back-1):
14
+ a = dataset[i:(i+look_back), 0]
15
+ dataX.append(a)
16
+ dataY.append(dataset[i + look_back, 0])
17
+ return np.array(dataX), np.array(dataY)
18
+
19
+ def train_and_predict(file):
20
+ # Load and preprocess data
21
+ dataframe = pd.read_csv(file.name, usecols=[1], engine='python', encoding="big5")
22
+ dataset = dataframe.values.astype('float32')
23
+
24
+ # Normalize the dataset
25
+ scaler = MinMaxScaler(feature_range=(0, 1))
26
+ dataset = scaler.fit_transform(dataset)
27
+
28
+ # Split into train and test sets
29
+ train_size = int(len(dataset) * 0.67)
30
+ test_size = len(dataset) - train_size
31
+ train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]
32
+
33
+ # Reshape into X=t and Y=t+1
34
+ look_back = 1
35
+ trainX, trainY = create_dataset(train, look_back)
36
+ testX, testY = create_dataset(test, look_back)
37
+ trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
38
+ testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
39
+
40
+ # Create and fit the LSTM network
41
+ model = Sequential()
42
+ model.add(LSTM(4, input_shape=(1, look_back)))
43
+ model.add(Dense(1))
44
+ model.compile(loss='mean_squared_error', optimizer='adam')
45
+ model.fit(trainX, trainY, epochs=50, batch_size=1, verbose=0)
46
+
47
+ # Make predictions
48
+ trainPredict = model.predict(trainX)
49
+ testPredict = model.predict(testX)
50
+
51
+ # Invert predictions
52
+ trainPredict = scaler.inverse_transform(trainPredict)
53
+ trainY = scaler.inverse_transform([trainY])
54
+ testPredict = scaler.inverse_transform(testPredict)
55
+ testY = scaler.inverse_transform([testY])
56
+
57
+ # Calculate RMSE
58
+ trainScore = np.sqrt(mean_squared_error(trainY[0], trainPredict[:,0]))
59
+ testScore = np.sqrt(mean_squared_error(testY[0], testPredict[:,0]))
60
+
61
+ # Prepare plot data
62
+ trainPredictPlot = np.empty_like(dataset)
63
+ trainPredictPlot[:, :] = np.nan
64
+ trainPredictPlot[look_back:len(trainPredict)+look_back, :] = trainPredict
65
+ testPredictPlot = np.empty_like(dataset)
66
+ testPredictPlot[:, :] = np.nan
67
+ testPredictPlot[len(trainPredict)+(look_back*2)+1:len(dataset)-1, :] = testPredict
68
+
69
+ # Create plot
70
+ plt.figure(figsize=(12, 8))
71
+ plt.plot(scaler.inverse_transform(dataset), label='Original Data', color='blue')
72
+ plt.plot(trainPredictPlot, label='Training Predictions', linestyle='--', color='green')
73
+ plt.plot(testPredictPlot, label='Test Predictions', linestyle='--', color='red')
74
+ plt.xlabel('Time')
75
+ plt.ylabel('Scaled Values')
76
+ plt.title('Original Data and Predictions')
77
+ plt.legend()
78
+ plt.grid(True, linestyle='--', alpha=0.7)
79
+
80
+ return plt, f'Train Score: {trainScore:.2f} RMSE', f'Test Score: {testScore:.2f} RMSE'
81
+
82
+ # Create Gradio interface
83
+ iface = gr.Interface(
84
+ fn=train_and_predict,
85
+ inputs=gr.File(label="Upload CSV file"),
86
+ outputs=[
87
+ gr.Plot(label="Predictions Plot"),
88
+ gr.Textbox(label="Train Score"),
89
+ gr.Textbox(label="Test Score")
90
+ ],
91
+ title="LSTM Stock Price Prediction",
92
+ description="Upload a CSV file with stock prices to train an LSTM model and see predictions."
93
+ )
94
+
95
+ # Launch the interface
96
+ iface.launch()