-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprediction_net.py
93 lines (76 loc) · 2.94 KB
/
prediction_net.py
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
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 21 11:44:20 2019
@author: tanma
"""
import pandas as pd, numpy as np
from sklearn.preprocessing import StandardScaler
from keras.models import Model
from keras.callbacks import ModelCheckpoint
from keras.layers import Input, SpatialDropout1D, GRU, LSTM,Conv1D, concatenate, Dense
from keras.layers import GlobalAveragePooling1D, GlobalMaxPooling1D, Bidirectional
from keras.layers import CuDNNLSTM, CuDNNGRU
from bearing_cal import calculate_initial_compass_bearing as cal
from geographiclib.geodesic import Geodesic
import matplotlib.pyplot as plt
id_ = 30
pnew = pd.read_csv('no.csv')
pnew = pnew[pnew.track_id == id_]
copy = pnew.drop(['time','track_id','Unnamed: 0'],axis = 1)
pnew = pnew.drop(['time','track_id','Unnamed: 0','longitude','latitude'],axis = 1)
def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
n_vars = 1 if type(data) is list else data.shape[1]
df = pd.DataFrame(data)
cols, names = list(), list()
for i in range(n_in, 0, -1):
cols.append(df.shift(i))
names += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)]
for i in range(0, n_out):
cols.append(df.shift(-i))
if i == 0:
names += [('var%d(t)' % (j+1)) for j in range(n_vars)]
else:
names += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)]
agg = pd.concat(cols, axis=1)
agg.columns = names
if dropnan:
agg.dropna(inplace=True)
return agg
whatever = pnew.iloc[:,0].values.reshape((-1,3581)).flatten() + np.random.randint(low = -5,high = 5,size = (pnew.shape[0]))
pnew['speed'] = whatever
scaler = StandardScaler()
what = scaler.fit_transform(pnew)
agg = series_to_supervised(what)
values = agg.values
timestep = 1
train = values[:2000000,:]
X_train = []
y_train = []
for i in range(timestep, len(pnew)-1):
X_train.append(train[i-timestep:i, :len(pnew.columns)])
y_train.append(train[i-timestep, len(pnew.columns):])
X_train, y_train = np.array(X_train), np.array(y_train)
inp = Input(shape=(X_train.shape[1],X_train.shape[2]))
x = CuDNNLSTM(256, return_sequences = True)(inp)
y = CuDNNGRU(128, return_sequences = True)(inp)
x = concatenate([x,y])
x = SpatialDropout1D(0.2)(x)
x = Conv1D(64, kernel_size = 3, padding = "same")(x)
max_pool = GlobalMaxPooling1D()(x)
avg_pool = GlobalAveragePooling1D()(x)
x = concatenate([max_pool,avg_pool])
x = Dense(1024)(x)
preds = Dense(len(pnew.columns))(x)
model = Model(inp,preds)
model.compile(loss = 'mse', optimizer = 'nadam')
filepath = "weight-improvement-{epoch:02d}-{loss:4f}.hd5"
checkpoint = ModelCheckpoint(filepath,monitor='val_loss',verbose=1,save_best_only=True,mode='min')
callbacks=[checkpoint]
model.fit(X_train,y_train,epochs = 20,batch_size = 1, callbacks = callbacks, validation_split = 0.25)
y_pred = model.predict(X_train)
model.save('model.h5')
plt.plot(y_pred[5:,0],y_pred[5:,1], color = 'red')
plt.plot(y_train[5:,0],y_train[5:,1], color = 'blue')
plt.show()
vector = np.array(copy.iloc[5,:].values)
x = model.predict(np.reshape(vector[[0,3]],(1,1,2)))