import numpy as np import pandas as pd from keras.models import Sequential from keras.layers import Conv1D, MaxPooling1D, Dense, Flatten # 加载数据 data = pd.read_csv('3c_left_1-6.csv') # 将数据转换为三维时序信号 x = data.iloc[:, 0:3].values x = x.reshape(x.shape[0], x.shape[1], 1) # 添加噪声 noise = np.random.normal(0, 1, x.shape) x_noise = x + noise # 构建模型 model = Sequential() model.add(Conv1D(32, kernel_size=3, activation='relu', input_shape=(3, 1))) model.add(MaxPooling1D(pool_size=2)) model.add(Conv1D(64, kernel_size=3, activation='relu')) model.add(MaxPooling1D(pool_size=2)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dense(3)) # 编译模型 model.compile(loss='mse', optimizer='adam') # 训练模型 model.fit(x_noise, x, epochs=50, batch_size=32) # 预测结果 x_pred = model.predict(x_noise) # 计算SNR、MSE、PSNR snr = 10 * np.log10(np.sum(x ** 2) / np.sum((x - x_pred) ** 2)) mse = np.mean((x - x_pred) ** 2) psnr = 10 * np.log10((np.max(x) ** 2) / mse) # 保存结果 result = pd.DataFrame({'SNR': [snr], 'MSE': [mse], 'PSNR': [psnr]}) result.to_csv('result.csv', index=False) 报错为File "G:\project2\gaussian.py", line 20, in <module> model.add(MaxPooling1D(pool_size=2))ValueError: Negative dimension size caused by subtracting 2 from 1 for 'max_pooling1d_1/MaxPool' (op: 'MaxPool') with input shapes: [?,1,1,32].
时间: 2023-06-15 20:05:15 浏览: 184
这个错误是因为在添加第一个池化层后,输出张量的空间维度被缩小到了1,而在添加第二个池化层时,池化窗口大小为2,会导致输出张量的空间维度变成负数。解决方法是将第一个池化层的池化窗口大小改为1或者不使用池化层。修改代码如下:
```
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import Conv1D, MaxPooling1D, Dense, Flatten
# 加载数据
data = pd.read_csv('3c_left_1-6.csv')
# 将数据转换为三维时序信号
x = data.iloc[:, 0:3].values
x = x.reshape(x.shape[0], x.shape[1], 1)
# 添加噪声
noise = np.random.normal(0, 1, x.shape)
x_noise = x + noise
# 构建模型
model = Sequential()
model.add(Conv1D(32, kernel_size=3, activation='relu', input_shape=(3, 1)))
model.add(Conv1D(64, kernel_size=3, activation='relu'))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(3))
# 编译模型
model.compile(loss='mse', optimizer='adam')
# 训练模型
model.fit(x_noise, x, epochs=50, batch_size=32)
# 预测结果
x_pred = model.predict(x_noise)
# 计算SNR、MSE、PSNR
snr = 10 * np.log10(np.sum(x ** 2) / np.sum((x - x_pred) ** 2))
mse = np.mean((x - x_pred) ** 2)
psnr = 10 * np.log10((np.max(x) ** 2) / mse)
# 保存结果
result = pd.DataFrame({'SNR': [snr], 'MSE': [mse], 'PSNR': [psnr]})
result.to_csv('result.csv', index=False)
```
阅读全文