用CNN实现脑电信号分类的python代码
时间: 2024-04-15 13:27:57 浏览: 175
以下是一个使用卷积神经网络(CNN)实现脑电信号分类的简单示例代码:
```python
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers
# 加载数据集
data = np.load('eeg_data.npz')
X_train, y_train = data['X_train'], data['y_train']
X_test, y_test = data['X_test'], data['y_test']
# 将数据转换为适合CNN的形状
X_train = np.expand_dims(X_train, axis=3)
X_test = np.expand_dims(X_test, axis=3)
# 构建CNN模型
model = tf.keras.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(X_train.shape[1:])),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(2, activation='softmax')
])
# 编译和训练模型
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(X_train, y_train, epochs=10, batch_size=32)
# 在测试集上评估模型性能
loss, accuracy = model.evaluate(X_test, y_test)
print(f'Test loss: {loss}')
print(f'Test accuracy: {accuracy}')
```
请注意,这只是一个简单的示例代码,实际应用中可能需要根据具体情况进行调整和优化。此外,还需要适配你的数据集和标签,并根据需要进行数据预处理和模型调参。
阅读全文