我尝试实施precision并recall作为自定义指标,如https://datascience.stackexchange.com/questions/45165/how-to-get-accuracy-f1-precision-and-recall-for-a-keras-model/45166#45166 ?newreg=6190503b2be14e8aa2c0069d0a52749e,但由于某种原因,这些数字是关闭的(我确实知道批次问题的平均值,这不是我要说的)。
所以我尝试实施另一个指标:
def p1(y_true, y_pred):
return K.sum(y_true)
Run Code Online (Sandbox Code Playgroud)
只是为了看看会发生什么......我希望看到一个直线图,其中1包含我的数据集中的's数量(我正在研究一个有binary_crossentropy损失的二元分类问题)。
因为 Keras 将自定义指标计算为每批结果的平均值,如果我有一个大小为 32 的批处理,我希望这个p1指标返回 16,但我得到了 15。如果我使用一个大小为 16 的批处理,我得到接近 7.9 的东西。那是我尝试使用该fit方法的时候。
我还在训练模型后手动计算了验证精度,它确实给了我一个与我val_precision从历史上看到的最后一个不同的数字。那是使用fir_generator,在这种情况下batch_size没有提供,所以我假设它一次计算整个验证数据集的度量。
另一个重要的细节是,当我使用相同的数据集进行训练和验证时,即使我在最后一个时期获得相同的真阳性和预测阳性的数字,训练和验证精度也不同(1 和 0.6)。
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
Run Code Online (Sandbox Code Playgroud)
显然 32.0 / (32.0 + K.epsilon()) = 0.6000000238418579
知道出了什么问题吗?
可能有帮助的东西:
def p1(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
return 1.0 / (true_positives …Run Code Online (Sandbox Code Playgroud) 这个问题与How can I check a fusion_matrix afterfine-tuning with custom datasets?相同。,在数据科学堆栈交换上。
我想在使用自定义数据集进行微调后检查一个混淆矩阵,包括精度、召回率和 f1 分数,如下所示。
微调过程和任务是Hugging Face 上的使用自定义数据集微调教程上的IMDb 评论的序列分类。
用Trainer完成微调后,在这种情况下如何检查confusion_matrix?
fusion_matrix 的图像,包括精度、召回率和 f1-score原始站点:仅作为输出图像的示例
predictions = np.argmax(trainer.test(test_x), axis=1)
# Confusion matrix and classification report.
print(classification_report(test_y, predictions))
precision recall f1-score support
0 0.75 0.79 0.77 1000
1 0.81 0.87 0.84 1000
2 0.63 0.61 0.62 1000
3 0.55 0.47 0.50 1000
4 0.66 0.66 0.66 1000
5 0.62 0.64 0.63 1000
6 0.74 0.83 0.78 1000 …Run Code Online (Sandbox Code Playgroud) nlp machine-learning python-3.x pytorch huggingface-transformers
我对如何使用max_queue_size,workers感到use_multiprocessing困惑Keras 文档
有人可以举个例子,说明如果您有的话,您将如何使用它们
以下是我根据对这三个字段的不科学猜测来使用它的方法。
classifier.fit_generator(training_set,
steps_per_epoch = 8000,
epochs = 25,
validation_data = test_set,
validation_steps = 2000/32,
max_queue_size = 10,
use_multiprocessing = False,
workers=1)
Run Code Online (Sandbox Code Playgroud) 我已经开始使用 TensorFlow 2.0,并且在某一方面有点不确定。
假设我有这个用例:在使用 摄取数据时,tf.data.Dataset我想对某些图像应用一些特定的增强操作。但是,我现在用的是外部库要求,该图像是numpy的阵列,而不是张量。
使用时tf.data.Dataset.from_tensor_slices(),流动数据需要是张量类型。具体例子:
def my_function(tensor_image):
print(tensor_image.numpy()
return
data = tf.data.Dataset.from_tensor_slices(tensor_images).map(my_function)
Run Code Online (Sandbox Code Playgroud)
上面的代码不起作用产生一个
“张量”对象没有属性“numpy”错误。
我已经阅读了关于 TensorFlow 2.0 的文档,指出如果想要使用任意的 Python 逻辑,则应该使用tf.py_function 或仅使用TensorFlow 原语:
How to convert "tensor" to "numpy" array in tensorflow?
我的问题如下:是否有另一种方法可以在带有自定义装饰器的函数中使用任意 python 代码/比使用更简单的方法tf.py_function?
老实说,对我来说,似乎必须有一种比传递给 a 更优雅的方法tf.py_function,转换为 numpy 数组,执行操作 A、B、C、D,然后重新转换为张量并产生结果。
我是 Tensorflow 领域的新手,正在研究 mnist 数据集分类的简单示例。我想知道除了准确性和损失(并可能显示它们)之外,如何获得其他指标(例如精度、召回率等)。这是我的代码:
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.callbacks import TensorBoard
import os
#load mnist dataset
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
#create and compile the model
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])
model.summary()
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
#model checkpoint (only if there is an improvement)
checkpoint_path = "logs/weights-improvement-{epoch:02d}-{accuracy:.2f}.hdf5"
cp_callback = ModelCheckpoint(checkpoint_path, monitor='accuracy',save_best_only=True,verbose=1, mode='max')
#Tensorboard
NAME = "tensorboard_{}".format(int(time.time())) #name of …Run Code Online (Sandbox Code Playgroud) 我想用 Keras 训练我的模型。我正在使用一个巨大的数据集,其中一个训练周期有超过 30000 个步骤。我的问题是,我不想在检查验证数据集上的模型改进之前等待一个纪元。有没有办法让 Keras 每 1000 步训练数据评估一次验证数据?我认为一种选择是使用回调,但是 Keras 有内置的解决方案吗?
if train:
log('Start training')
history = model.fit(train_dataset,
steps_per_epoch=train_steps,
epochs=50,
validation_data=val_dataset,
validation_steps=val_steps,
callbacks=[
keras.callbacks.EarlyStopping(
monitor='loss',
patience=10,
restore_best_weights=True,
),
keras.callbacks.ModelCheckpoint(
filepath=f'model.h5',
monitor='val_loss',
save_best_only=True,
save_weights_only=True,
),
keras.callbacks.ReduceLROnPlateau(
monitor = "val_loss",
factor = 0.5,
patience = 3,
min_lr=0.001,
),
],
)
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 tf.keras 中的 EfficientNet 模型,但由于某种原因,这似乎不起作用。
import tensorflow.keras.applications as apps
help(apps)
Run Code Online (Sandbox Code Playgroud)
未列为EfficientNetB0型号。相似地,
import tensorflow.keras.applications.EfficientNetB0
Run Code Online (Sandbox Code Playgroud)
印刷
ModuleNotFoundError:没有名为“tensorflow.keras.applications.EfficientNetB0”的模块
我当前的 Keras.applications 是 1.0.8,这似乎是最新版本。我的 Keras 版本是 2.2.5,tensorflow 版本是 1.15。此外,对于独立的 keras 版本,同样的行为也很明显。
难道这不应该仅通过 keras.application 版本来解决吗?这是否与tensorflow版本有关(意味着也许只有tf 2可以使用它们?)。最后,我可以使用解决这个问题的方法吗?
我将转移学习与 effectivenet_B0 结合使用,我想做的是在网络学习时逐渐解冻层。首先,我在整个网络之上训练 1 个密集层,而其他所有层都被冻结。我使用此代码来冻结图层:
for layer in model_base.layers[:-2]:
layer.trainable = False
Run Code Online (Sandbox Code Playgroud)
然后我使用以下代码解冻整个模型并冻结我需要的确切层:
model.trainable = True
for layer in model_base.layers[:-13]:
layer.trainable = False
Run Code Online (Sandbox Code Playgroud)
一切正常。我再进行一次 model.compile,它就开始从原来的地方开始训练,太棒了。但是,当我再次解冻所有层时
model.trainable = True
Run Code Online (Sandbox Code Playgroud)
并尝试进行微调,我的模型从头开始学习。
我尝试了不同的方法和方法来解决这个问题,但似乎没有任何效果。我也尝试对模型中的所有batch_normalization层使用layer.training = False和,但它也没有帮助。layer.trainable = False
尝试将 Densenet121 功能块添加到模型中。我需要以这种格式编写 Keras 模型,而不是使用
model=Sequential()
model.add()
Run Code Online (Sandbox Code Playgroud)
方法 build_img_encod 函数出了什么问题
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-62-69dd207148e0> in <module>()
----> 1 x = build_img_encod()
3 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/input_spec.py in assert_input_compatibility(input_spec, inputs, layer_name)
164 spec.min_ndim is not None or
165 spec.max_ndim is not None):
--> 166 if x.shape.ndims is None:
167 raise ValueError('Input ' + str(input_index) + ' of layer ' +
168 layer_name + ' is incompatible with the layer: '
AttributeError: 'Functional' object has no attribute 'shape'
Run Code Online (Sandbox Code Playgroud)
def build_img_encod( …Run Code Online (Sandbox Code Playgroud) model.compile(optimizer='adam',loss='categorical_crossentropy', metrics=['accuracy'])
history = model.fit(train_data,epochs = 1,validation_data = test_data,verbose=1, callbacks =[earlystopping, csv_logger])
9/87606 [..............................] - ETA: 20:44 - loss: 0.2311 - accuracy: 0.8889
Cleanup called...
Cleanup called...
Cleanup called...
Cleanup called...
Cleanup called...
Cleanup called...
Cleanup called...
Cleanup called...
Cleanup called...
Cleanup called...
Cleanup called...
Cleanup called...
Cleanup called...
Cleanup called...
Cleanup called...
Cleanup called...
Cleanup called...
Cleanup called...
Cleanup called...
Cleanup called...
Cleanup called...
Cleanup called...
Run Code Online (Sandbox Code Playgroud)