<jupyter_start><jupyter_text>Normalize Data<jupyter_code>scaler = StandardScaler()
# sklearn StandardScaler
# Standardize features by removing the mean and scaling to unit variance.
# z = (x - u) / s
# where u is the mean of the training samples or zero if with_mean=False, 
# and s is the standard deviation of the training samples or one if with_std=False.

dataset = scaler.fit_transform(df1.reshape(-1,1))
dataset[0]<jupyter_output><empty_output><jupyter_text>Train test split<jupyter_code>train_size = int(len(dataset)*0.7)
test_size = len(dataset) - train_size
train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]
print('train shape ', train.shape)
print('test shape ', test.shape)
def create_dataset(dataset, look_back=1):
    dataX, dataY = [], []
    for i in range(len(dataset)-look_back - 1):
        a = dataset[i:(i+look_back), 0]
        dataX.append(a)
        dataY.append(dataset[i+look_back,0])
    return np.array(dataX), np.array(dataY)
# create train and test dataset
look_back = 40

# train test split
trainX, trainY = create_dataset(train,look_back)
testX, testY = create_dataset(test, look_back)

# reshape input to be [samples, time steps, features]

trainX = np.reshape(trainX,(trainX.shape[0],trainX.shape[1],1))
testX = np.reshape(testX,(testX.shape[0],testX.shape[1],1))
batch_size = 1

model = Sequential()
model.add(LSTM(128, batch_input_shape=(batch_size, look_back, 1), stateful=True))
model.add(Dense(1))

model.compile(loss='mean_squared_error', optimizer='sgd')
for i in range(60):
    model.fit(trainX, trainY, epochs=1, batch_size=batch_size, verbose=2, shuffle=False)
    model.reset_states()
trainPredict = model.predict(trainX,batch_size=batch_size)
model.reset_states()
testPredict = model.predict(testX,batch_size=batch_size)
trainPredict = scaler.inverse_transform(trainPredict)
trainY = scaler.inverse_transform([trainY])
testPredict = scaler.inverse_transform(testPredict)
testY = scaler.inverse_transform([testY])
import math
trainScore = math.sqrt(mean_squared_error(trainY[0], trainPredict[:,0]))
print('train Score: %.2f RMSE' % (trainScore))
testScore = math.sqrt(mean_squared_error(testY[0], testPredict[:,0]))
print('Test Score: %.2f RMSE' % (testScore))
testPredict[-9:-1]
realdata = data.sort_values()
realdata[-9:-1]
predicted_data = pd.DataFrame(testPredict, index=realdata.index[-108:])
predicted_data
plt.figure(figsize=(14,5))

plt.plot(realdata, label='real data')
plt.plot(predicted_data, label='predicted')
plt.xticks([realdata.index[0], predicted_data.index[0], realdata.index[-1]])
plt.vlines(predicted_data.index[0], realdata.min(), realdata.max(), color='r', label='split')
plt.legend()
plt.xlabel('date')
plt.show()
testPredict.shape
from datetime import datetime, timedelta
def future_predict(model, last_look_back_days, future_days=50):
    future_predicts = np.array([])
    dt = datetime.strptime(realdata.index[-1], '%Y-%m-%d')
    dates = np.array([])
    
    for day in range(future_days):
        dataset = scaler.fit_transform(last_look_back_days.reshape(-1,1))
        testX, testY = create_dataset(dataset, look_back=len(last_look_back_days)-2)
        testX = np.reshape(testX, (testX.shape[0], testX.shape[1], 1))
        new_predict  = model.predict(testX, batch_size=batch_size)
        new_predict = scaler.inverse_transform(new_predict)
        future_predicts = np.append(future_predicts, new_predict)
        
        dates = np.append(dates, [dt + timedelta(days=day)])
        dates[day].strftime('%m/%d/%Y')
        
        model.reset_states()
        last_look_back_days = np.delete(last_look_back_days, 0)
        last_look_back_days = np.append(last_look_back_days, new_predict)
        
    predicts = pd.DataFrame(future_predicts, index=dates)
    predicts
    return predicts
predicts = future_predict(model, predicted_data.values[-200:],future_days=200)
predicts
plt.figure(figsize=(14,5))

plt.plot(predicts, label='predicts')
plt.legend()
plt.xlabel('date')
plt.show()
model.save(r'C:\Users\mengh\plotly dash covid app\COVID-dashboard')
model = keras.models.load_model(r'C:\Users\mengh\plotly dash covid app\COVID-dashboard')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14193393968405935, 'fraction_numerical': 0.016275730014360938, 'mean_word_length': 5.5501567398119125, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '146991', 'license': 'MIT', 'n_tokens_mistral': 1526, 'n_tokens_neox': 1472, 'n_words': 269, 'path': '.ipynb_checkpoints/covid-cases-prediction-checkpoint.ipynb', 'repo_name': 'menghanzhao/COVID-dashboard', 'size': '4178'}