之前发过两个帖子,一个是改的别人的鸢尾花分类,另一个忘了改的那一篇一维卷积神经网络的了,两个代码都显得不尽人意。鸢尾花分类将一个样本转化成三个特征样本训练,会导致训练自己东西的时候样本要做的非常大。第二个帖子的方法虽然一条条的训练,但是在写拓扑结构的时候定义了:
def baseline_model():
这样不仅会使人不明白为什么定义这个,而且将代码高端化,比如:加残差训练等等,这时候会发现很难挂一些东西进去,经常报错,对网络的创新就比较困难:
于是综合两种代码,本宝宝改造出了最最直观的代码:
import numpy as np
import pandas as pd
import keras
import tensorflow as tf
from keras.models import Sequential
from keras.wrappers.scikit_learn import KerasClassifier
from keras.utils import np_utils,plot_model
from sklearn.model_selection import cross_val_score,train_test_split,KFold
from sklearn.preprocessing import LabelEncoder
from keras.layers import Dense, Activation, Flatten, Convolution1D, Dropout,MaxPooling1D,BatchNormalization,GlobalAveragePooling1D
from keras.models import load_model
#from keras.layers import Dense,Dropout,Flatten,Conv1D,MaxPooling1D
from keras.models import model_from_json
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import itertools
from keras import layers
from keras.optimizers import SGD
# 载入数据
df = pd.read_csv(r'C:/Users/pc/Desktop/14改.csv')
X = np.expand_dims(df.values[:, 0:1024].astype(float), axis=2)
Y = df.values[:, 1024]
# 湿度分类编码为数字
encoder = LabelEncoder()
Y_encoded = encoder.fit_transform(Y)
Y_onehot = np_utils.to_categorical(Y_encoded)
# 划分训练集,测试集
X_train, X_test, Y_train, Y_test = train_test_split(X, Y_onehot, test_size=0.3, random_state=0)
# 定义神经网络
model = Sequential()
model.add(Convolution1D(nb_filter=16, filter_length=128,strides=2,padding='same', input_shape=(1024, 1),activation='relu'))#第一个卷积层
model.add(Dropout(0.5))
model.add(BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001, center=True, scale=True, beta_initializer='zeros', gamma_initializer='ones', moving_mean_initializer='zeros', moving_variance_initializer='ones', beta_regularizer=None, gamma_regularizer=None, beta_constraint=None, gamma_constraint=None))
# model.add(MaxPooling1D(2,strides=2,padding='same'))
model.add(Convolution1D(32,32,strides=1,padding='same',activation='relu'))
model.add(MaxPooling1D(2,strides=2,padding='same'))
model.add(Flatten())
model.add(Dense(100,activation='relu'))
model.add(Dense(9, activation='softmax'))
#model.add(Dense(nb_class))
#model.add(Activation('softmax'))
#plot_model(model, to_file='./model_classifier.png', show_shapes=True)
print(model.summary())
sgd = SGD(lr=0.01, nesterov=True, decay=1e-6, momentum=0.9)
model.compile(loss='categorical_crossentropy',optimizer='adam', metrics=['accuracy'])
#model.fit(build_fn=model, epochs=5, batch_size=4, verbose=1)
history=model.fit(X_train, Y_train,epochs=5,validation_data=(X_test, Y_test),batch_size=4)
import matplotlib.pyplot as plt
#model.save('fei1313改_model.h5')
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.plot(history.history['loss'],'_',label='train_loss')
plt.plot(history.history['val_loss'],':',label='val_loss')
plt.plot(history.history['accuracy'],'.',label='train_acc')
plt.plot(history.history['val_accuracy'],'r',label='val_acc')
plt.show()
这样就显得比较简单清晰,往里面挂一些高端算法也就比较容易点:
训练结果如下:
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv1d_5 (Conv1D) (None, 512, 16) 2064
_________________________________________________________________
dropout_3 (Dropout) (None, 512, 16) 0
_________________________________________________________________
batch_normalization_3 (Batch (None, 512, 16) 64
_________________________________________________________________
conv1d_6 (Conv1D) (None, 512, 32) 16416
_________________________________________________________________
max_pooling1d_3 (MaxPooling1 (None, 256, 32) 0
_________________________________________________________________
flatten_1 (Flatten) (None, 8192) 0
_________________________________________________________________
dense_4 (Dense) (None, 100) 819300
_________________________________________________________________
dense_5 (Dense) (None, 9) 909
=================================================================
Total params: 838,753
Trainable params: 838,721
Non-trainable params: 32
_________________________________________________________________
None
Train on 6034 samples, validate on 2587 samples
Epoch 1/5
6034/6034 [==============================] - 51s 9ms/step - loss: 0.6591 - accuracy: 0.7473 - val_loss: 0.2103 - val_accuracy: 0.9045
Epoch 2/5
6034/6034 [==============================] - 42s 7ms/step - loss: 0.1440 - accuracy: 0.9420 - val_loss: 0.3055 - val_accuracy: 0.9173
Epoch 3/5
6034/6034 [==============================] - 42s 7ms/step - loss: 0.0744 - accuracy: 0.9735 - val_loss: 0.0720 - val_accuracy: 0.9760
Epoch 4/5
6034/6034 [==============================] - 42s 7ms/step - loss: 0.0625 - accuracy: 0.9786 - val_loss: 0.0510 - val_accuracy: 0.9907
Epoch 5/5
6034/6034 [==============================] - 41s 7ms/step - loss: 0.0534 - accuracy: 0.9849 - val_loss: 0.0483 - val_accuracy: 0.9845
这次用的是9分类,数据集可以参照上一篇的,地址如下:
训练数据集https://pan.baidu.com/s/1WVChuo5d5eNLvctXpWNfEA
密码iulk
永久有效
将代码中的:
model.add(Dense(9, activation='softmax'))
改成:
model.add(Dense(2, activation='softmax'))
就可以运行起来了。
``
研二了,时间有限,能力有限,精力有限,所以大部分都是改改别人的代码。自己真正的做一个处出来可能真的会秃顶
数据来源于河工程机械实验室零件多种损伤振动信号