import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import VotingClassifier
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.wrappers.scikit_learn import KerasClassifier
from keras.utils import to_categorical
from sklearn import datasets
from keras.layers import LSTM, Dense, Bidirectional, Conv1D, MaxPooling1D, Flatten, Input,Dropout
# df = datasets.load_iris() # 利用load函数装载数据集
#
# X = df['data']
# y = df['target']
data = pd.read_csv('E:/samples_2.csv')
# 提取X和y
X = data.iloc[:, :-1].values
y = data.iloc[:, -1].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=2)
# 对标签进行one-hot编码
y_train_encoded = to_categorical(y_train)
y_test_encoded = to_categorical(y_test)
def create_ann():
model = Sequential()
model.add(Bidirectional(LSTM(64, return_sequences=True), input_shape=(12, 1)))
model.add(Dropout(0.2))
model.add(Bidirectional(LSTM(units=64, return_sequences=False)))
model.add(Dropout(0.2))
model.add(Dense(5, activation='softmax'))
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
return model
def create_ann2():
model = Sequential()
model.add(Conv1D(filters=32, kernel_size=3, activation='relu', input_shape=(12, 1)))
model.add(MaxPooling1D(pool_size=2))
model.add(LSTM(units=64))
model.add(Dropout(0.2))
model.add(Dense(5, activation='softmax'))
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
return model
ann_clf = KerasClassifier(build_fn=create_ann, epochs=10, batch_size=32, verbose=0,)
ann2_clf = KerasClassifier(build_fn=create_ann, epochs=10, batch_size=32, verbose=0)
ann_clf._estimator_type = "classifier"
ann2_clf._estimator_type = "classifier"
voting_clf = VotingClassifier(estimators=[('ann', ann_clf), ('ann2', ann2_clf)], voting='hard')
voting_clf.fit(X_train, y_train)
# 在测试集上评估模型
score = voting_clf.score(X_test, y_test)
print("集成模型的准确率:", score)
jjmzjjjj
于 2024-09-11 10:06:02 首次发布