LSTM预测sin(X)

1.模型

多层LSTM

2.用到的函数

tf.nn.rnn_cell.BasicLSTMCell(num_units)

num_units这个参数的大小就是LSTM输出结果的维度。例如num_units=128, 那么LSTM网络最后输出就是一个128维的向量。http://www.mtcnn.com/?p=529

tf.nn.dynamic_rnn

https://blog.youkuaiyun.com/junjun150013652/article/details/81331448

tf.contrib.layers.fully_connected(inputs,num_outputs)

增加一个全连接层
自动初始化w和b
激活函数默认为relu函数
输出个数由num_outputs指定

tf.losses.mean_squared_error

https://www.w3cschool.cn/tensorflow_python/tensorflow_python-zkxr2x87.html

3.代码

import numpy as np
import tensorflow as tf
import matplotlib as mpl
mpl.use('Agg')
from matplotlib import pyplot as plt

import warnings
warnings.filterwarnings("ignore")

hidden_size = 30
num_layers = 2

timesteps = 10
training_steps = 1000
batch_size = 32

training_examples = 10000
testing_examples  =1000
sample_gap = 0.01

def generate_data(seq) :
    x = []
    y = []
    for i in range(len(seq) - timesteps) :
        x.append([seq[i: i + timesteps]])
        y.append([seq[i + timesteps]])
        
    return np.array(x, dtype=np.float32), np.array(y, dtype=np.float32)

def lstm_model(x, y, is_training) :
    cell = tf.nn.rnn_cell.MultiRNNCell(
            [tf.nn.rnn_cell.BasicLSTMCell(hidden_size)
            for _ in range(num_layers)])
    
    outputs, _ = tf.nn.dynamic_rnn(cell, x, dtype=tf.float32)
    
    # 下标为-1表示取出列表的最后一行数据值
    output = outputs[:, -1, :]
    
    predictions = tf.contrib.layers.fully_connected(
                    output, 1, activation_fn=None)
    
    if not is_training :
        return predictions, None, None
    
    loss = tf.losses.mean_squared_error(labels=y, predictions=predictions)
    
    trian_op = tf.contrib.layers.optimize_loss(
                loss, tf.train.get_global_step(),
                optimizer='Adagrad', learning_rate=0.1)
    
    return predictions, loss, trian_op

def train(sess, train_x, train_y) :
    ds = tf.data.Dataset.from_tensor_slices((train_x, train_y))
    ds = ds.repeat().shuffle(1000).batch(batch_size)
    x, y = ds.make_one_shot_iterator().get_next()
    
    with tf.variable_scope("model", reuse=tf.AUTO_REUSE) :
        predictions, loss, train_op = lstm_model(x, y, True)
        
    sess.run(tf.global_variables_initializer())
    
    for i in range (training_steps) :
        _, l = sess.run([train_op, loss])
        if i % 100 == 0 :
            print("train step: " + str(i) + ", loss: " + str(l))
            
def run_eval(sess, test_x, test_y) :
    ds = tf.data.Dataset.from_tensor_slices((test_x, test_y))
    ds = ds.batch(1)
    x, y = ds.make_one_shot_iterator().get_next()
    
    with tf.variable_scope("model", reuse=True) :
        predection, _, _ = lstm_model(x, [0,0], False)
        
    predictions = []
    labels = []
    for i in range(testing_examples) :
        p, l = sess.run([predection, y])
        predictions.append(p)
        labels.append(l)
        
    predictions = np.array(predictions).squeeze()
    labels = np.array(labels).squeeze()
    rmse = np.sqrt(((predictions - labels) ** 2).mean(axis=0))
    print("Mean square error is: %f" % rmse)
    
    %matplotlib inline
    plt.figure()
    plt.plot(predictions, label='predictions')
    plt.plot(labels,  label='real_sin')
    plt.legend()
    plt.show()
    
test_start = (training_examples + timesteps) * sample_gap
test_end = test_start + (testing_examples + timesteps) * sample_gap
test_x, test_y = generate_data(np.sin(np.linspace(
                    0, test_start, training_examples+timesteps, dtype=np.float32)))

with tf.Session() as sess :
    train(sess, train_x, train_y)
    run_eval(sess, test_x, test_y)
    
  

 

 

 

 

 

 

 

### 使用LSTM神经网络预测复合正弦函数 为了实现这一目标,需要构建并训练一个LSTM模型来捕捉复合正弦波的时间序列特征。以下是详细的Python代码示例: #### 数据准备 首先定义复合正弦波的数据集生成器。 ```python import numpy as np import matplotlib.pyplot as plt def generate_data(seq_length=50, num_samples=1000): t = np.linspace(0, seq_length * (num_samples / 100), num_samples) freqs = [2, 3, 5] # 复合频率 amplitudes = [1, 0.5, 0.7] # 对应振幅 data = sum([amp * np.sin(freq * t) for amp, freq in zip(amplitudes, freqs)]) X = [] y = [] for i in range(len(data)-seq_length): X.append(data[i:i+seq_length]) y.append(data[i+seq_length]) return np.array(X).reshape(-1, seq_length, 1), np.array(y) X_train, y_train = generate_data() plt.plot(np.arange(len(X_train)), X_train[:, :, 0].flatten()) plt.title('Composite Sine Wave Training Data') plt.show() ``` 此部分创建了一个由多个不同频率组成的合成正弦波作为输入数据,并将其划分为适合喂入LSTM层的形式[^1]。 #### 构建LSTM模型 接着建立Keras框架下的LSTM架构用于拟合上述时间序列。 ```python from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense, Dropout model = Sequential([ LSTM(units=50, activation='relu', input_shape=(X_train.shape[1], 1)), Dropout(rate=0.2), Dense(units=1)]) model.compile(optimizer='adam', loss='mse') history = model.fit( X_train, y_train, epochs=20, batch_size=32, validation_split=0.2, verbose=1) plt.figure(figsize=(8,4)) plt.plot(history.history['loss'], label='Training Loss') plt.plot(history.history['val_loss'], label='Validation Loss') plt.legend() plt.grid(True) plt.xlabel('Epochs') plt.ylabel('Loss Value') plt.title('Model Convergence During Training') plt.show() ``` 这段脚本搭建了一种简单的单向LSTM结构,其中包含了丢弃法(Dropout)防止过拟合现象的发生;并通过均方误差(MSE)度量损失函数来进行优化调整权重参数[^2]。 #### 测试与可视化结果 最后一步是对新样本执行推理操作并将实际输出同预期值对比展示出来。 ```python test_seq_len = 50 future_steps = 100 last_sequence = X_train[-1] predictions = [] for step in range(future_steps): next_pred = model.predict(last_sequence.reshape((1,test_seq_len,1))) predictions.append(next_pred.flatten()[0]) last_sequence[:-1,:] = last_sequence[1:,:] last_sequence[-1] = next_pred predicted_values = np.concatenate((y_train[:len(predictions)], predictions)) time_points = np.arange(predicted_values.size) plt.figure(figsize=(10,6)) plt.plot(time_points, predicted_values, 'r-', lw=2, label="Predictions") plt.plot(time_points[:-(future_steps)], y_train, 'b--', alpha=.5, label="True Values") plt.axvline(x=time_points[-future_steps]-1,color='k',linestyle=':',label='Prediction Start Point') plt.fill_between(time_points[-future_steps:], min(predicted_values), max(predicted_values), color='gray',alpha=0.3,label='Forecast Region') plt.legend(loc='upper center') plt.title('Comparison Between True and Predicted Composite Sinusoidal Waves') plt.tight_layout() plt.show() ``` 该绘图命令展示了原始的真实值以及未来一段时间内的预估值之间的关系,直观反映了LSTM对于复杂周期模式的学习能力和泛化性能[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值