import numpy as np import matplotlib.pyplot as plt from keras.models import Sequential from keras.layers import Dense, Flatten, Conv1D, MaxPooling1D # 生成正弦函数数据 x = np.linspace(0, 100, 1000) y = np.sin(2*x+1) + 3 # 将数据转换为卷积神经网络需要的格式 X = np.zeros((len(x), 10)) for i in range(len(x)): for j in range(10): X[i][j] = y[(i+j)%len(x)] X = np.reshape(X, (X.shape[0], X.shape[1], 1)) # 构建卷积神经网络模型 model = Sequential() model.add(Conv1D(filters=32, kernel_size=3, activation='relu', input_shape=(10,1))) model.add(MaxPooling1D(pool_size=2)) model.add(Flatten()) model.add(Dense(100, activation='relu')) model.add(Dense(1, activation='linear')) # 编译模型 model.compile(loss='mse', optimizer='adam') # 训练模型并可视化损失函数 history = model.fit(X, y, epochs=100, batch_size=32, validation_split=0.2) loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1, len(loss)+1) plt.plot(epochs, loss, 'bo', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() # 预测并可视化结果 y_pred = model.predict(X) plt.plot(x, y, label='true') plt.plot(x, y_pred, label='predict') plt.legend() plt.show()修改这段代码使卷积神经网络模型可视化
时间: 2023-12-29 11:04:26 浏览: 130
要可视化卷积神经网络模型,可以使用 Keras 中的 `plot_model` 函数。修改代码如下:
```
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential, Model
from keras.layers import Dense, Flatten, Conv1D, MaxPooling1D, Input
from keras.utils import plot_model
# 生成正弦函数数据
x = np.linspace(0, 100, 1000)
y = np.sin(2*x+1) + 3
# 将数据转换为卷积神经网络需要的格式
X = np.zeros((len(x), 10))
for i in range(len(x)):
for j in range(10):
X[i][j] = y[(i+j)%len(x)]
X = np.reshape(X, (X.shape[0], X.shape[1], 1))
# 构建卷积神经网络模型
inputs = Input(shape=(10, 1))
conv1 = Conv1D(filters=32, kernel_size=3, activation='relu')(inputs)
pool1 = MaxPooling1D(pool_size=2)(conv1)
flatten = Flatten()(pool1)
dense1 = Dense(100, activation='relu')(flatten)
outputs = Dense(1, activation='linear')(dense1)
model = Model(inputs=inputs, outputs=outputs)
# 编译模型
model.compile(loss='mse', optimizer='adam')
# 可视化模型
plot_model(model, to_file='model.png', show_shapes=True, show_layer_names=False)
# 训练模型并可视化损失函数
history = model.fit(X, y, epochs=100, batch_size=32, validation_split=0.2)
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(loss)+1)
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
# 预测并可视化结果
y_pred = model.predict(X)
plt.plot(x, y, label='true')
plt.plot(x, y_pred, label='predict')
plt.legend()
plt.show()
```
修改后的代码可将卷积神经网络模型保存为 `model.png` 文件,并显示模型结构。
阅读全文