import pandas as pd import numpy as np import matplotlib.pyplot as plt from keras.models import Model, Input from keras.layers import Conv1D, BatchNormalization, Activation, Add, Flatten, Dense from keras.optimizers import Adam # 读取CSV文件 data = pd.read_csv("3c_left_1-6.csv", header=None) # 将数据转换为Numpy数组 data = data.values # 定义输入形状 input_shape = (data.shape[1], 1) # 定义深度残差网络 def residual_network(inputs): # 第一层卷积层 x = Conv1D(32, 3, padding="same")(inputs) x = BatchNormalization()(x) x = Activation("relu")(x) # 残差块 for i in range(5): y = Conv1D(32, 3, padding="same")(x) y = BatchNormalization()(y) y = Activation("relu")(y) y = Conv1D(32, 3, padding="same")(y) y = BatchNormalization()(y) y = Add()([x, y]) x = Activation("relu")(y) # 全局池化层和全连接层 x = Flatten()(x) x = Dense(128, activation="relu")(x) x = Dense(data.shape[1], activation="linear")(x) outputs = Add()([x, inputs]) return outputs # 构建模型 inputs = Input(shape=input_shape) outputs = residual_network(inputs) model = Model(inputs=inputs, outputs=outputs) # 编译模型 model.compile(loss="mean_squared_error", optimizer=Adam()) # 训练模型 model.fit(data[..., np.newaxis], data[..., np.newaxis, np.newaxis], epochs=100) # 预测数据 predicted_data = model.predict(data[..., np.newaxis]) predicted_data = np.squeeze(predicted_data) # 可视化去噪前后的数据 fig, axs = plt.subplots(3, 1, figsize=(12, 8)) for i in range(3): axs[i].plot(data[:, i], label="Original Signal") axs[i].plot(predicted_data[:, i], label="Denoised Signal") axs[i].legend() plt.savefig("denoised_signal.png") # 将去噪后的数据保存为CSV文件 df = pd.DataFrame(predicted_data, columns=["x", "y", "z"]) df.to_csv("denoised_data.csv", index=False)报错为Traceback (most recent call last): File "G:\project2\main.py", line 51, in <module> model.fit(data[..., np.newaxis], data[..., np.newaxis, np.newaxis], epochs=100) File "G:\python\envs\tensorflow\lib\site-packages\keras\engine\training.py", line 1154, in fit batch_size=batch_size) File "G:\python\envs\tensorflow\lib\site-packages\keras\engine\training.py", line 621, in _standardize_user_data exception_prefix='target') File "G:\python\envs\tensorflow\lib\site-packages\keras\engine\training_utils.py", line 135, in standardize_input_data 'with shape ' + str(data_shape)) ValueError: Error when checking target: expected add_6 to have 3 dimensions, but got array with shape (575206, 3, 1, 1)
时间: 2023-06-13 19:08:01 浏览: 139
python数据分析与可视化 import pandas as pd import numpy as np import m
这个错误是因为模型的输出是三维的,但是目标数据的维度不匹配。在训练模型时,你传入的目标数据的维度应该是 (batch_size, data_shape),而你传入的数据的维度是 (batch_size, data_shape, 1, 1)。你可以尝试将目标数据的维度改为 (batch_size, data_shape, 1)。修改代码如下:
```
model.fit(data[..., np.newaxis], data[..., np.newaxis], epochs=100)
```
改为:
```
model.fit(data[..., np.newaxis], data[..., np.newaxis], epochs=100)
```
另外,你在定义模型时,最后一层的输出是通过 Add()([x, inputs]) 得到的,这个操作会将输入和输出相加,如果你想要得到去噪后的信号,可以将最后一层的输出改为只有 x,即:
```
outputs = x
```
这样最后得到的就是去噪后的信号了。
阅读全文