como crear rnn en keras

Solutions on MaxInterview for como crear rnn en keras by the best coders in the world

showing results for - "como crear rnn en keras"
Edoardo
26 Aug 2017
1import numpy 
2import matplotlib.pyplot as plt 
3import pandas 
4import math 
5from keras.models import Sequential 
6from keras.layers import Dense 
7from keras.layers import LSTM 
8from keras.layers import Reshape 
9from sklearn.preprocessing import MinMaxScaler 
10from sklearn.metrics import mean_squared_error 
11# generate sine wavepip 
12def make_sine_with_noise(_start, _stop, _step, _phase_shift, gain): 
13    x = numpy.arange(_start, _stop, step = _step) 
14    noise = numpy.random.uniform(-0.1, 0.1, size = len(x)) 
15    y = gain*0.5*numpy.sin(x+_phase_shift) 
16    y = numpy.add(noise, y) 
17    return x, y 
18# convert an array of values into a dataset matrix 
19def create_dataset(dataset, look_back=1, look_ahead=1): 
20    dataX, dataY = [], [] 
21    for i in range(len(dataset) - look_back - look_ahead - 1): 
22     a = dataset[i:(i + look_back), :] 
23     dataX.append(a) 
24     b = dataset[(i + look_back):(i + look_back + look_ahead), :] 
25     dataY.append(b) 
26    return numpy.array(dataX), numpy.array(dataY) 
27# fix random seed for reproducibility 
28numpy.random.seed(7) 
29# generate sine wave 
30x1, y1 = make_sine_with_noise(0, 200, 1/24, 0, 1) 
31x2, y2 = make_sine_with_noise(0, 200, 1/24, math.pi/4, 3) 
32x3, y3 = make_sine_with_noise(0, 200, 1/24, math.pi/2, 20) 
33# plt.plot(x1, y1) 
34# plt.plot(x2, y2) 
35# plt.plot(x3, y3) 
36# plt.show() 
37#transform to pandas dataframe 
38dataframe = pandas.DataFrame({'y1': y1, 'y2': y2, 'x3': y3}) 
39dataset = dataframe.values 
40dataset = dataset.astype('float32') 
41# normalize the dataset 
42scaler = MinMaxScaler(feature_range=(0, 1)) 
43dataset = scaler.fit_transform(dataset) 
44#split into train and test sets 
45train_size = int(len(dataset) * 0.67) 
46test_size = len(dataset) - train_size 
47train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:] 
48# reshape into X=t and Y=t+1 
49look_back = 10 
50look_ahead = 5 
51trainX, trainY = create_dataset(train, look_back, look_ahead) 
52testX, testY = create_dataset(test, look_back, look_ahead) 
53print(trainX.shape) 
54print(trainY.shape) 
55# reshape input to be [samples, time steps, features] 
56trainX = numpy.reshape(trainX, (trainX.shape[0], trainX.shape[1], trainX.shape[2])) 
57testX = numpy.reshape(testX, (testX.shape[0], testX.shape[1], testX.shape[2])) 
58# create and fit the LSTM network 
59model = Sequential() 
60model.add(LSTM(look_ahead, input_shape=(trainX.shape[1], trainX.shape[2]), return_sequences=True)) 
61model.add(LSTM(look_ahead, input_shape=(look_ahead, trainX.shape[2]))) 
62model.add(Dense(trainY.shape[1]*trainY.shape[2])) 
63model.add(Reshape((trainY.shape[1], trainY.shape[2]))) 
64model.compile(loss='mean_squared_error', optimizer='adam') 
65model.fit(trainX, trainY, epochs=1, batch_size=1, verbose=1) 
66# make prediction 
67trainPredict = model.predict(trainX) 
68testPredict = model.predict(testX) 
69
70#save model 
71model.save('my_sin_prediction_model.h5') 
72
73trainPredictPlottable = trainPredict[::look_ahead] 
74trainPredictPlottable = [item for sublist in trainPredictPlottable for item in sublist] 
75trainPredictPlottable = scaler.inverse_transform(numpy.array(trainPredictPlottable)) 
76# create single testPredict array concatenating every 'look_ahed' prediction array 
77testPredictPlottable = testPredict[::look_ahead] 
78testPredictPlottable = [item for sublist in testPredictPlottable for item in sublist] 
79testPredictPlottable = scaler.inverse_transform(numpy.array(testPredictPlottable)) 
80# testPredictPlottable = testPredictPlottable[:-look_ahead] 
81# shift train predictions for plotting 
82trainPredictPlot = numpy.empty_like(dataset) 
83trainPredictPlot[:, :] = numpy.nan 
84trainPredictPlot[look_back:len(trainPredictPlottable)+look_back, :] = trainPredictPlottable 
85# shift test predictions for plotting 
86testPredictPlot = numpy.empty_like(dataset) 
87testPredictPlot[:, :] = numpy.nan 
88testPredictPlot[len(dataset)-len(testPredictPlottable):len(dataset), :] = testPredictPlottable 
89# plot baseline and predictions 
90dataset = scaler.inverse_transform(dataset) 
91plt.plot(dataset, color='k') 
92plt.plot(trainPredictPlot) 
93plt.plot(testPredictPlot) 
94plt.show() 
similar questions
queries leading to this page
como crear rnn en keras