예제 #1
0
    def __init__(self,
                 num_hidden_units=256,
                 global_pooling='avg',
                 regularizer_val=0.0001):

        # Network parameters
        self._num_hidden_units = num_hidden_units
        self._regularizer_value = regularizer_val
        self._regularizer = regularizers.l2(regularizer_val)
        self._global_pooling = global_pooling
def performCrossValidation(x_data, y_data):
    _metrics = metrics.metrics(DIMENSIONS, 2)

    for seed in range(ROUNDS):
        np.random.seed(seed)

        kfold = KFold(n_splits=KFOLDS, shuffle=True, random_state=seed)
        for train, test in kfold.split(x_data, y_data):
            from keras import backend as K
            K.clear_session()
            classes_train = pd.concat(
                [y_data[train], pd.get_dummies(y_data[train])],
                axis=1).drop(['Prior_Emotion'], axis=1)
            classes_test = pd.concat(
                [y_data[test], pd.get_dummies(y_data[test])],
                axis=1).drop(['Prior_Emotion'], axis=1)

            input_shape = sentence_enISEAR.shape[1]  # feature count
            model = Sequential()
            model.add(
                Dense(7,
                      input_shape=(input_shape, ),
                      activity_regularizer=regularizers.l2(0.01)))
            model.add(Activation('sigmoid'))
            model.compile(loss='binary_crossentropy',
                          metrics=['accuracy'],
                          optimizer='adam')
            model.fit(sentence_enISEAR[train],
                      vectors[train],
                      batch_size=BATCH_SIZE,
                      epochs=EPOCHS,
                      verbose=VERBOSITY,
                      class_weight=class_weight)

            vectors_test = vectors[test]
            ids_test = ids[test]
            weights = [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5]
            preds = model.predict(sentence_enISEAR[test])
            results = []
            for row in range(len(preds)):
                res = []
                for dim in range(len(DIMENSIONS)):
                    value = preds[row][dim]
                    if (value >= weights[dim]):
                        value = 1
                    else:
                        value = 0
                    res.append(value)
                results.append(res)

            predicted = np.array(results)
            _metrics.evaluateFold(predicted, vectors_test)

    _metrics.showFinalResults(args.format)
예제 #3
0
def action():  #此函数是控制整个采样,训练, 匹配测试的过程。
    global filename, total_EEG_data_number_for_test
    global step, directly_load_model_flag, openfile_name, directly_load_filename
    filename = ui.lineEdit.text()  #写入文件名

    if step == 3:  # 匹配测试
        disable_Gui()
        ui.label.setText("匹配测试中...")
        ui.label.repaint()
        ui.pushButton.setText("匹配测试中...")
        ui.pushButton.repaint()

        if directly_load_model_flag == False:
            model = load_model(filename + '_key.h5')
        if directly_load_model_flag == True:
            model = load_model(directly_load_filename)
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((server_address, 5204))  #5204 为 OPENBCI GUI的缺省服务器段的发送端口
        EEG_data_for_test = np.zeros(
            [total_EEG_data_number_for_test,
             total_EEG_Features])  # EEG_data_for_test为采样的测试EEG帧。
        temp_total_EEG_data_number_for_test = total_EEG_data_number_for_test
        total_EEG_data_number_for_test = 1  #把total_EEG_data_number_for_test赋值给temp_total_EEG_data_number_for_test后,total_EEG_data_number_for_test变为1,只是为了GUI的进度条显示测试的进度%。
        match_counter = 0  # 用于计数EEG通过测试的个数。
        for times in range(
                temp_total_EEG_data_number_for_test):  #这个大循环,内嵌一个1的小循环。
            for k in range(total_EEG_data_number_for_test):
                EEG_data_one_line = (s.recv(1024).decode('utf-8')).split(
                    'A')  ####按照字符"A"来截断每一条EEG数据,分割成24小份
                for i in range(total_EEG_Features):
                    if len(EEG_data_one_line
                           ) == 25:  #这个判断是为了避免有时候读取EEG时候,遇到换行符丢失的现象。
                        EEG_data_for_test[k][i] = float(EEG_data_one_line[i])
                    else:
                        EEG_data_for_test[k][i] = EEG_data_for_test[k - 1][i]

            test = model.predict(EEG_data_for_test, verbose=1)

            for k in range(total_EEG_data_number_for_test):
                if test[k] >= match_triger:
                    match_counter += 1
            ui.progressBar.setProperty(
                "value",
                (times + 1) / temp_total_EEG_data_number_for_test * 100)

            result_text = "匹配率为" + str(
                match_counter / temp_total_EEG_data_number_for_test *
                100) + "%"
            ui.label.setText(result_text)
            ui.label.repaint()
            ui.lcdNumber.display(match_counter /
                                 temp_total_EEG_data_number_for_test * 100)
            QApplication.processEvents()  #用于PyQt界面的刷新,保证流畅程度。
        result_text = "测试结束,最终匹配率为" + str(
            match_counter / temp_total_EEG_data_number_for_test * 100) + "%"
        ui.label.setText(result_text)
        ui.label.repaint()

        total_EEG_data_number_for_test = temp_total_EEG_data_number_for_test  #重新恢复全局变量total_EEG_data_number_for_test的值。
        ui.pushButton.setText("开始匹配测试")
        ui.pushButton.repaint()
        enable_Gui()

    if step == 2:  #机器学习
        disable_Gui()
        ui.label.setText("开始机器学习你的脑纹。")
        ui.label.repaint()
        ui.pushButton.setText("2-设置中...")
        ui.pushButton.repaint()

        ######################################### 开始训练 ######################################

        ####################### 读取代训练的EEG数据############################
        f = open(filename + 'EEG.txt', 'r')  #读取代训练的EEG数据
        All_EEG_data_lines = f.readlines()
        EEG_data_A = np.zeros([total_EEG_data_number, total_EEG_Features])

        for k in range(total_EEG_data_number):
            EEG_data_one_line = (All_EEG_data_lines[k].split('A')
                                 )  ####按照字符"A"来截断每一条EEG数据,分割成24小份
            for i in range(total_EEG_Features):
                if len(EEG_data_one_line
                       ) == 25:  #这个判断是为了避免有时候读取EEG时候,遇到换行符丢失的现象。
                    EEG_data_A[k][i] = float(EEG_data_one_line[i])
                else:
                    EEG_data_A[k][i] = EEG_data_A[k - 1][i]
        f.close()

        ###############读取代训练的EEG数据完毕######################

        ###############开始读取代陪训的Random 1/2 EEG数据######################
        f = open('random_EEG_1.txt', 'r')  #这是用于参与训练的他人EEG
        All_EEG_data_lines = f.readlines()
        EEG_data_B = np.zeros([total_EEG_data_number, total_EEG_Features])

        for k in range(total_EEG_data_number):
            EEG_data_one_line = (All_EEG_data_lines[k].split('A')
                                 )  ####按照字符"A"来截断每一条EEG数据,分割成24小份
            for i in range(total_EEG_Features):
                if len(EEG_data_one_line
                       ) == 25:  #这个判断是为了避免有时候读取EEG时候,遇到换行符丢失的现象。
                    EEG_data_B[k][i] = float(EEG_data_one_line[i])
                else:
                    EEG_data_B[k][i] = EEG_data_B[k - 1][i]
        f.close()

        ###############读取random_EEG_1完毕######################

        f = open('random_EEG_2.txt', 'r')  #这也是用于参与训练的他人EEG
        All_EEG_data_lines = f.readlines()
        EEG_data_C = np.zeros([total_EEG_data_number, total_EEG_Features])

        for k in range(total_EEG_data_number):
            EEG_data_one_line = (All_EEG_data_lines[k].split('A')
                                 )  ####按照字符"A"来截断每一条EEG数据,分割成24小份
            for i in range(total_EEG_Features):
                if len(EEG_data_one_line
                       ) == 25:  #这个判断是为了避免有时候读取EEG时候,遇到换行符丢失的现象。
                    EEG_data_C[k][i] = float(EEG_data_one_line[i])
                else:
                    EEG_data_C[k][i] = EEG_data_C[k - 1][i]
        f.close()

        ###############读取random_EEG_2完毕######################
        ##################读取代陪训的Random 1/2 EEG数据######################

        ########################开始合成总的数据样本(包括待训练数据,以及两个陪训数据#############################
        y0 = np.ones([total_EEG_data_number, 1])
        y1 = np.zeros([total_EEG_data_number, 1])
        y2 = np.zeros([total_EEG_data_number, 1])
        x = np.vstack((EEG_data_A, EEG_data_B, EEG_data_C))
        y = np.vstack((y0, y1, y2))

        ########################开始搭建神经网络#############################
        model = Sequential()
        model.add(Dense(240, input_shape=(24, )))
        model.add(Activation('relu'))
        model.add(Dropout(0.2))

        model.add(
            Dense(240,
                  kernel_regularizer=regularizers.l2(0.01),
                  bias_regularizer=regularizers.l2(0.01)))
        model.add(Activation('relu'))
        model.add(Dropout(0.2))

        model.add(
            Dense(240,
                  kernel_regularizer=regularizers.l2(0.01),
                  bias_regularizer=regularizers.l2(0.01)))
        model.add(Activation('relu'))
        model.add(Dropout(0.2))

        model.add(Dense(1))
        model.add(Activation('sigmoid'))

        model.compile(loss='binary_crossentropy',
                      optimizer='rmsprop',
                      metrics=['accuracy'])
        ########################神经网络搭建完毕#############################

        ################这个tb,是为了使用TensorBoard########################
        tb = TensorBoard(
            log_dir='./logs',  # log 目录
            histogram_freq=0,  # 按照何等频率(epoch)来计算直方图,0为不计算
            batch_size=32,  # 用多大量的数据计算直方图
            write_graph=True,  # 是否存储网络结构图
            write_grads=False,  # 是否可视化梯度直方图
            write_images=False,  # 是否可视化参数
            embeddings_freq=0,
            embeddings_layer_names=None,
            embeddings_metadata=None)

        # 在命令行,先conda activate envs,然后进入本代码所在的目录,然后用 tensorboard --logdir=logs/ 来看log
        # 然后打开chrome浏览器,输入http://localhost:6006/ 来查看
        # 如果出现tensorboard错误,那么需要修改 ...\lib\site-packages\tensorboard\manager.py,其中keras环境下的这个文件,我已经修改好了。
        ########################开始训练#############################
        for i in range(int(100 / 100)):  #这个for,是1次性训练,是为了在TensorBoard中查看训练情况。
            #for i in range(100):  #这个for,只是为了进度条的显示,所以分成 100次来训练。
            model.fit(x,
                      y,
                      epochs=int(training_times / 100 * 100),
                      batch_size=training_batch_size,
                      verbose=1,
                      shuffle=True,
                      callbacks=[tb])  #这一行带callbacks,是为了使用TensorBoard
            #model.fit(x, y, epochs=int(training_times/100), batch_size=training_batch_size,verbose = 1,shuffle=True) #这一行带callbacks,所以无法使用TensorBoard
            ui.progressBar.setProperty("value", i + 1)
            QApplication.processEvents()  #用于PyQt界面的刷新,保证流畅程度。

        model.save(filename + '_key.h5')
        ########################训练完毕,并保存训练好的神经网络#############################

        ui.label.setText("你的脑纹锁设置成功!")
        ui.label.repaint()
        ui.pushButton.setText("开始匹配测试")
        ui.pushButton.repaint()
        ui.progressBar.setProperty("value", 0)
        step = 3
        ui.label_2.setText("目前载入的是" + filename + "的已经训练好的脑纹")
        ui.label_2.repaint()
        enable_Gui()

    if step == 1:  #### 录制脑电波
        disable_Gui()
        ui.label.setText("开始录制你的脑纹信息,请保持不动。")
        ui.label.update()
        ui.pushButton.setText("1-录制脑纹中...")
        ui.pushButton.repaint()
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((server_address, 5204))
        f = open(filename + 'EEG.txt', 'w')
        for k in range(total_EEG_data_number):
            EEG_data = (s.recv(1024).decode('utf-8'))
            EEG_data_to_write = EEG_data + '\r\n'
            f.write(EEG_data_to_write)
            ui.progressBar.setProperty("value",
                                       k / total_EEG_data_number * 100 + 2)
            QApplication.processEvents()  #用于PyQt界面的刷新,保证流畅程度。
        f.close()
        step = 2
        ui.label_2.update()
        ui.label.setText("接下来神经网络开始学习并设置你的脑纹。")
        ui.label.update()
        ui.pushButton.setText("2-开始机器学习")
        ui.pushButton.repaint()
        enable_Gui()
    if step == 0:
        ui.label.setText("返回第一步,请输入你的名字。")
        ui.label.update()
        ui.pushButton.setText("1-重新开始录制脑纹")
        ui.pushButton.repaint()
        ui.label_2.setText("目前没有载入任何已经训练好的脑纹。")
        ui.label_2.repaint()
        step = 1