# 读取数据
data = pd.read_csv('data.csv')
# 获取特征和类别数据
X = data.iloc[:, :-1].values
y = data.iloc[:, -1].values
# 对类别进行编码
encoder = LabelEncoder()
y_encoded = encoder.fit_transform(y)
y_categorical = np_utils.to_categorical(y_encoded)
# 数据归一化
X = (X - X.mean()) / X.std()
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y_categorical, test_size=0.2, random_state=42)
# 定义模型
model = Sequential()
model.add(Conv1D(64, 3, activation='relu', input_shape=(45, 1)))
model.add(Conv1D(64, 3, activation='relu'))
model.add(MaxPooling1D(2))
model.add(Flatten())
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(4, activation='softmax'))
# 编译模型
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# 训练模型
history = model.fit(X_train.reshape(-1, 45, 1), y_train, validation_data=(X_test.reshape(-1, 45, 1), y_test), epochs=10, batch_size=32)
# 绘制准确率和损失函数曲线
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
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 left')
plt.show()
# 使用训练好的模型进行预测
predictions = model.predict(X_test.reshape(-1, 45, 1))
# 可视化预测结果
predicted_labels = np.argmax(predictions, axis=1)
true_labels = np.argmax(y_test, axis=1)
plt.figure(figsize=(10, 6))
plt.scatter(np.arange(len(y_test)), predicted_labels, marker='o', label='Predicted')
plt.scatter(np.arange(len(y_test)), true_labels, marker='x', label='True')
plt.title('Predicted vs True Labels')
plt.xlabel('Sample')
plt.ylabel('Label')
plt.legend()
plt.show()