首页 > 解决方案 > 您如何将 Keras 模型摘要写入数据框?

问题描述

首先,我要说这不是正确运行 Keras 模型的方法。应该有一个训练集和测试集。任务是严格培养直觉,所以没有测试集。

我正在通过神经元、激活函数、批次和层的几种排列来运行模型。这是我正在使用的代码。

from sklearn.datasets import make_classification
X1, y1 = make_classification(n_samples=90000, n_features=17, n_informative=6, n_redundant=0, n_repeated=0, n_classes=8, n_clusters_per_class=3, weights=None, flip_y=.3, class_sep=.4, hypercube=False, shift=3, scale=2, shuffle=True, random_state=840780)

class_num = 8

# ----------------------------------------------------------------

import itertools

final_param_list = []

# param_list_gen order is  units, activation function, batch size, layers
param_list_gen = [[10, 20, 50], ["sigmoid", "relu", "LeakyReLU"], [8, 16, 32], [1, 2]]
for element in itertools.product(*param_list_gen):
    final_param_list.append(element)

# --------------------------------------------------------------------------------------

from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten, LeakyReLU
from keras.callbacks import History
import tensorflow as tf
import numpy as np
import pandas as pd

# --------------------------------------------------------------------------------------



# --------  Model 1 - permutations of neurons, activation funtions batch size and layers -------- #

for param in final_param_list:
    q2model1 = Sequential()

    # hidden layer 1
    q2model1.add(Dense(param[0]))
    if param[1] != 'LeakyReLU':
        q2model1.add(Activation(param[1]))
    else:
        q2model1.add(LeakyReLU(alpha=0.1))

    if param[3] == 2:
        # hidden layer 2
        q2model1.add(Dense(param[0]))
        if param[1] != 'LeakyReLU':
            q2model1.add(Activation(param[1]))
        else:
            q2model1.add(LeakyReLU(alpha=0.1))

    # output layer
    q2model1.add(Dense(class_num, activation='softmax'))

    q2model1.compile(loss='sparse_categorical_crossentropy', optimizer='RMSProp', metrics=['accuracy'])

    # Step 3: Fit the model

    history = q2model1.fit(X1, y1, epochs=20)

似乎工作正常。现在,我的任务是输出每个 epoch 的准确度,包括神经元、激活函数、批次、层

现在,这给了我每个时代的所有准确性

print(history.history['acc'])

这给了我参数

print(param)

这给了我一个总结,虽然我不确定这是否是最好的方法

print(q2model1.summary())

有没有办法将每个纪元打印到熊猫数据框,看起来像这样?

阶段(列表索引 + 1)| # 神经元 | 激活功能 | 批量 | 层 | 加速时代1 | 加速时代2 | ...... | 加速时代20

就是这样。如果您在模型本身中发现任何明显错误的内容,或者如果我遗漏了一些关键代码,请告诉我

标签: pythonpandastensorflowkeras

解决方案


你可以试试:

import pandas as pd

# assuming you stored your model.fit results in a 'history' variable:
history = model.fit(x_train, y_train, epochs=20)

# convert the history.history dictionary to a pandas dataframe:     
hist_df = pd.DataFrame(history.history) 

# checkout result with print e.g.:    
print(hist_df)

# or the describe() method:
hist_df.describe()

Keras 也有一个 CSVLogger:https ://keras.io/callbacks/#csvlogger ,这可能很有趣。


推荐阅读