z

    xiaoxiao2022-06-26  144

    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('all_data.txt', delimiter=' ', dtype='float32') # 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_z_score = gas[:, 2:] # 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_z_score) gas_train_attr = gas_new[:int(gas_new.shape[0] * 0.7)] gas_train_label = gas[:int(gas.shape[0] * 0.7), 0] gas_train_label = to_categorical(gas_train_label) gas_train_label = gas_train_label[:,1:] gas_test_attr = gas_new[int(gas_new.shape[0] * 0.7):] gas_test_label = gas[int(gas.shape[0] * 0.7):, 0] gas_test_label = to_categorical(gas_test_label) gas_test_label = gas_test_label[:,1:] model = Sequential() model.add(Dense(100, activation='relu')) model.add(Dense(100, activation='softmax')) # model.add(Dropout(0.5)) # model.add(Dense(128, activation='relu')) # model.add(Dropout(0.5)) # model.add(Dense(128, activation='relu')) model.add(Dense(6)) sgd = keras.optimizers.SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True) model.compile(optimizer=sgd, loss='mse', metrics=['accuracy']) his = model.fit(gas_train_attr, gas_train_label, validation_data=(gas_test_attr[:int(gas_test_attr.shape[0] * 0.5)], gas_test_label[:int(gas_test_label.shape[0] * 0.5)]), epochs=100) # 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[int(gas_test_attr.shape[0] * 0.5):]) gas_train_predict = model.predict(gas_train_attr) gas_all_predict = model.predict(gas[:, 2:]) 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.reshape(-1, 1), gas_train_predict.reshape(-1, 1))), fmt='%.5f') np.savetxt('gas_val_result.txt', np.hstack( (gas_test_label[:int(gas_test_attr.shape[0] * 0.5)].reshape(-1, 1), gas_val_predict.reshape(-1, 1))), fmt='%.5f') np.savetxt('gas_test_result.txt', np.hstack( (gas_test_label[int(gas_test_attr.shape[0] * 0.5):].reshape(-1, 1), gas_test_predict.reshape(-1, 1))), fmt='%.5f')

    最新回复(0)