import numpy as np import matplotlib.pyplot as plt from keras.models import Sequential from keras.layers import Dense, SimpleRNN from keras import backend as K from keras.models import Model from sklearn.cluster import KMeans # 生成sin函数数据 x = np.arange(0, 2*np.pi, 0.1) y = np.sin(x) # 可视化sin函数 plt.plot(x, y) plt.show() # 准备数据 dataX, dataY = [], [] for i in range(len(y)-1): dataX.append(y[i:i+1]) dataY.append(y[i+1]) dataX = np.array(dataX) dataY = np.array(dataY) # 划分训练集和测试集 train_size = int(len(dataY) * 0.7) test_size = len(dataY) - train_size trainX, testX = np.array(dataX[0:train_size]), np.array(dataX[train_size:len(dataX)]) trainY, testY = np.array(dataY[0:train_size]), np.array(dataY[train_size:len(dataY)]) # 调整输入数据的形状 trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1])) testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1])) # 定义模型结构 model = Sequential() model.add(SimpleRNN(units=10, input_shape=(1, 1))) model.add(Dense(units=1)) # 编译模型 model.compile(optimizer='adam', loss='mse') # 训练模型 history = model.fit(trainX, trainY, epochs=200, validation_data=(testX, testY)) # 可视化损失函数 plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model Loss') plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(['Train', 'Test'], loc='upper right') plt.show() #预测结果 trainPredict = model.predict(trainX) testPredict = model.predict(testX)可视化模型结构代码
时间: 2024-03-24 10:36:59 浏览: 128
import numpy as np import matplotlib.pyplot as plt import math
以下是可视化模型结构的代码:
```python
from keras.utils.vis_utils import plot_model
plot_model(model, to_file='model.png', show_shapes=True, show_layer_names=True)
```
上述代码会将模型结构绘制成一个图形,并保存为名为"model.png"的文件。你可以在代码中修改文件名来更改保存的文件名。
阅读全文