import keras
from keras import Sequential
from keras.layers import Dense, Dropout
from keras import backend
import numpy as np
from matplotlib import pyplot as plt
from keras.utils import to_categorical
np.seterr(divide='ignore', invalid='ignore')
gas = np.loadtxt('feature_result.txt')
# gas = all_data[np.where(all_data[:, 0] == 4)]
# np.savetxt('gas.txt', gas, fmt='%.5f'),目的是找出4号气体的浓度和所有数据
np.random.seed(133)
np.random.shuffle(gas)
gas_max_min = gas[:, 0:15]
# # z-score方法
# gas_mean = np.mean(gas_z_score, axis=0)
# gas_std = np.std(gas_z_score, axis=0)
# gas_new = (gas_z_score - gas_mean) / gas_std
from sklearn import preprocessing
min_max_scaler = preprocessing.MinMaxScaler()
gas_new = min_max_scaler.fit_transform(gas_max_min)
gas_train_attr = gas_new[:int(gas_new.shape[0] * 0.75)]
gas_train_label_origin = gas[:int(gas.shape[0] * 0.75), 15].reshape(-1, 1)
print(gas_train_label_origin)
gas_train_label = to_categorical(gas_train_label_origin) #转换为只有0和1的二进制类型
gas_test_attr = gas_new[int(gas_new.shape[0] * 0.75):]
gas_test_label_origin = gas[int(gas.shape[0] * 0.75):, 15].reshape(-1, 1)
gas_test_label = to_categorical(gas_test_label_origin)
print(gas_test_label_origin)
model = Sequential()
model.add(Dense(100, activation='relu'))
model.add(Dense(50, activation='relu'))
# model.add(Dense(50, activation='relu'))
model.add(Dropout(0.2))
# model.add(Dense(128, activation='relu'))
# model.add(Dropout(0.5))
# model.add(Dense(128, activation='relu'))
model.add(Dense(4, activation='softmax'))
# sgd = keras.optimizers.SGD(lr=0.1, decay=1e-6, nesterov=True)
model.compile(optimizer='adam', loss='mse', metrics=['accuracy'])
his = model.fit(gas_train_attr, gas_train_label, validation_data=(gas_test_attr, gas_test_label), epochs=2000)
# plt.plot(hist.history['acc'])
plt.plot(his.history['acc'])
plt.plot(his.history['val_acc'])
plt.title("")
plt.ylabel("Classification Accuracy")
plt.xlabel("epoch")
plt.legend(["Training set","Validation set"],loc="lower right")
plt.show()
# gas_val_predict = model.predict(gas_test_attr[:int(gas_test_attr.shape[0] * 0.5)])
gas_test_predict = model.predict(gas_test_attr)
gas_test_predict = (np.argmax(gas_test_predict, axis = 1)).reshape(-1, 1)
print(gas_test_predict)
gas_train_predict = model.predict(gas_train_attr)
gas_train_predict = (np.argmax(gas_train_predict, axis = 1)).reshape(-1, 1)
print(gas_train_predict)
# a=range(len(his.history['acc'])) #np.arange()返回的是一个一个array,而range返回的是一个list
# np.savetxt('min_max_sgd.txt', np.hstack((a, his.history['acc'])))
# for i in range(len(his.history['acc'])):
# a.append(his.history['acc'][i])
# model.evaluate(gas_test_attr, gas_test_label)
np.savetxt('gas_train_result.txt', np.hstack((gas_train_label_origin, gas_train_predict)),
fmt='%.5f')
np.savetxt('gas_test_result.txt', np.hstack((gas_test_label_origin, gas_test_predict)),
fmt='%.5f')
mlp_classification
最新推荐文章于 2025-03-22 19:11:54 发布