小编Nic*_*ais的帖子

如何从Keras的早期停止中看到最好的时代的损失?

我已经成功地在我的 Keras 模型中实现了提前停止,但我不确定如何看待最佳时代的损失。

es = EarlyStopping(monitor='val_out_soft_loss', 
            mode='min',
            restore_best_weights=True, 
            verbose=2, 
            patience=10)

model.fit(tr_x,
          tr_y,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          callbacks=[es],
          validation_data=(val_x, val_y))
loss = model.history.history["val_out_soft_loss"][-1]
return model, loss
Run Code Online (Sandbox Code Playgroud)

我定义损失分数的方式意味着返回的分数来自最后一个时期,而不是最好的时期。

例子:

from sklearn.model_selection import train_test_split, KFold
losses = []
models = []
for k in range(2):
    kfold = KFold(5, random_state = 42 + k, shuffle = True)
    for k_fold, (tr_inds, val_inds) in enumerate(kfold.split(train_y)):
        print("-----------")
        print("-----------")
        model, loss = get_model(64, 100)
        models.append(model)
        print(k_fold, loss)
        losses.append(loss)
print("-------")
print(losses)
print(np.mean(losses))

Epoch 23/100
18536/18536 [==============================] - 7s 362us/step - …
Run Code Online (Sandbox Code Playgroud)

python machine-learning neural-network keras tensorflow

4
推荐指数
1
解决办法
1278
查看次数

当达到特定的验证准确度时如何停止训练?

我正在训练一个卷积网络,一旦验证错误达到​​ 90%,我想停止训练。我考虑过使用 EarlyStopping 并将基线设置为 0.90,但是只要验证准确度低于给定时期数的基线(此处仅为 0),它就会停止训练。所以我的代码是:

es=EarlyStopping(monitor='val_acc',mode='auto',verbose=1,baseline=.90,patience=0)
history = model.fit(training_images, training_labels, validation_data=(test_images, test_labels), epochs=30, verbose=2,callbacks=[es])
Run Code Online (Sandbox Code Playgroud)

当我使用此代码时,我的训练在第一个具有给定结果的 epoch 后停止:

训练 60000 个样本,验证 10000 个样本

纪元 1/30 60000/60000 - 7s - 损失:0.4600 - acc:0.8330 - val_loss:0.3426 - val_acc:0.8787

一旦验证准确率达到 90% 或以上,我还能尝试停止训练吗?

下面是代码的其余部分:

  tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(28, 28, 1)),
  tf.keras.layers.MaxPooling2D(2, 2),
  tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28, 28, 1)),
  tf.keras.layers.MaxPooling2D(2, 2),
  tf.keras.layers.Flatten(),
  tf.keras.layers.Dense(152, activation='relu'),
  tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer=Adam(learning_rate=0.001),loss='sparse_categorical_crossentropy', metrics=['accuracy'])
es=EarlyStopping(monitor='val_acc',mode='auto',verbose=1,baseline=.90,patience=0)
history = model.fit(training_images, training_labels, validation_data=(test_images, test_labels), epochs=30, verbose=2,callbacks=[es])
Run Code Online (Sandbox Code Playgroud)

谢谢!

python deep-learning conv-neural-network keras tensorflow

4
推荐指数
1
解决办法
2620
查看次数

AttributeError:模块“tensorflow”没有属性“layers”

我正在尝试实现 VGG,但收到上述奇怪的错误。我在 Ubuntu 上运行 TFv2。这可能是因为我没有运行 CUDA 吗?

代码来自这里

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

# Imports

import time
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
# tf.logging.set_verbosity(tf.logging.INFO)

from tensorflow.keras.layers import Conv2D, Dense, Flatten

np.random.seed(1)

mnist = tf.keras.datasets.mnist

(train_data, train_labels), (eval_data, eval_labels) = mnist.load_data()

train_data, train_labels = train_data / 255.0, train_labels / 255.0

# Add a channels dimension
train_data = train_data[..., tf.newaxis]
train_labels = train_labels[..., tf.newaxis]

index = …
Run Code Online (Sandbox Code Playgroud)

python tensorflow

4
推荐指数
1
解决办法
3万
查看次数

将形状不等的数组列表转换为 Tensorflow 2 数据集:ValueError:无法将非矩形 Python 序列转换为 Tensor

我以不等形状数组列表的形式标记数据:

array([array([1179,    6,  208,    2, 1625,   92,    9, 3870,    3, 2136,  435,
          5, 2453, 2180,   44,    1,  226,  166,    3, 4409,   49, 6728,
         ...
         10,   17, 1396,  106, 8002, 7968,  111,   33, 1130,   60,  181,
       7988, 7974, 7970])], dtype=object)
Run Code Online (Sandbox Code Playgroud)

以及各自的目标:

Out[74]: array([0, 0, 0, ..., 0, 0, 1], dtype=object)
Run Code Online (Sandbox Code Playgroud)

我正在尝试将它们转换为 padded tf.data.Dataset(),但它不允许我将不相等的形状转换为张量。我会得到这个错误:

ValueError: Can't convert non-rectangular Python sequence to Tensor.
Run Code Online (Sandbox Code Playgroud)

完整的代码在这里。假设我的起点是在之后y = ...

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
import tensorflow_datasets as tfds …
Run Code Online (Sandbox Code Playgroud)

python keras tensorflow tensorflow-datasets tensorflow2.0

4
推荐指数
1
解决办法
3470
查看次数

在 Tensorflow 2 中手动设置 trainable_variables 权重

我必须在张量流的模型中设置 trainable_variables 值,而不是使用优化器。有什么功能或者方法可以实现吗?我展示了一个示例代码:我想设置 mnist_model.trainable_variables 值。

for epoch in range(0,1):
  with tf.GradientTape() as tape:
  prediction = mnist_model(mnist_images, training=True)


  loss_value = loss(mnist_labels, prediction)

variables = mnist_model.trainable_variables
loss_history.append(loss_value.numpy())
grads = tape.gradient(loss_value, variables)
Run Code Online (Sandbox Code Playgroud)

python keras tensorflow

4
推荐指数
1
解决办法
5241
查看次数

使用 Matplotlib 将 Pytorch 张量显示为图像

我正在尝试显示存储为 pytorch 张量的图像。

trainset = datasets.ImageFolder('data/Cat_Dog_data/train/', transform=transforms)
trainload = torch.utils.data.DataLoader(trainset, batch_size=32, shuffle=True)

images, labels = iter(trainload).next()
image = images[0]
image.shape 

>>> torch.Size([3, 224, 224]) # pyplot doesn't like this, so reshape

image = image.reshape(224,224,3)
plt.imshow(image.numpy())
Run Code Online (Sandbox Code Playgroud)

此方法显示同一图像的 3 x 3 网格,始终以灰度显示。例如:

在此处输入图片说明

如何解决此问题以便正确显示单色图像?

python machine-learning matplotlib pytorch

4
推荐指数
1
解决办法
5555
查看次数

经过一些迭代后,matplotlib“无法分配位图”

我找不到避免这种崩溃的解决方案。

我已经清理了附加的代码,因为它包含问题而没有其他内容。

无论图像大小如何,程序在 368 次迭代后就会崩溃。

我也尝试了在论坛中找到的内容,但没有找到解决方案( plt.close('all'), gc.collect().... )。

import matplotlib.pyplot as plt
import cv2


compteur = 0
image = cv2.imread(r"D:\OneDrive\Bureau\New folder\12345.jpg")


while True:

    print('1')
    ax_user = plt.imshow(image)

    print('2')
    plt.close('all')

    print (f'\n{compteur}:\t')
    compteur += 1 



367:
1
2

368:
1
Fail to allocate bitmap
Run Code Online (Sandbox Code Playgroud)

python matplotlib

4
推荐指数
1
解决办法
2361
查看次数

在python中删除撇号前的多余空格

我被要求为一个使用两个列表的类编写一个程序。一个列表包含 7 个人的姓名(我使用了总统的名字),另一个包含他们的 7 个电话号码。该程序的目标是让用户输入朋友的姓名,然后程序显示该朋友的电话号码。我让程序按照我想要的方式工作,但输出在其中放置了一个我不想要的额外空间。输出如下所示:

Your friend George Washington 's phone number is: 249-451-2869
Run Code Online (Sandbox Code Playgroud)

我想删除“Washington”和“'s”之间的空格,使其读起来更自然。我尝试了不同版本的 strip() 但无法摆脱讨厌的空间。下面是该程序的主要代码:

personName = nameGenerator() #function to allow user to enter name
nameIndex = IsNameInList(personName, Friends) #function that checks the user's input to see if input is #in the name list
print('Your friend',Friends[nameIndex],"\'s phone number is:",Phone_Numbers[nameIndex]) #Friends is name list, Phone_Numbers is numbers list, nameIndex stores the index of the proper name and phone number
Run Code Online (Sandbox Code Playgroud)

python

3
推荐指数
1
解决办法
123
查看次数

使用 ImageDataGenerator 随机正交、90 度旋转

我使用以下代码使用发票图像训练 CNN 模型。

train_datagen = ImageDataGenerator( 
                rescale = 1. / 255, 
                 shear_range = 0.2, 
                  zoom_range = 0.2, 
            horizontal_flip = True
            ) 

test_datagen = ImageDataGenerator(rescale = 1. / 255) 

train_generator = train_datagen.flow_from_directory(train_data_dir, 
                              target_size =(img_width, img_height), 
                     batch_size = batch_size) 

validation_generator = test_datagen.flow_from_directory( 
                                    validation_data_dir, 
                   target_size =(img_width, img_height), 
          batch_size = batch_size) 

model.fit_generator(train_generator, 
    steps_per_epoch = nb_train_samples // batch_size, 
    epochs = epochs, validation_data = validation_generator, 
    validation_steps = nb_validation_samples // batch_size) 
Run Code Online (Sandbox Code Playgroud)

问题是我在训练数据集中只使用了直立图像。我所有的图像都如下图所示:

训练期间使用的直立图像

训练结束后,当我想发送如下所示的图像时,我的模型无法预测其正确的类别。

错误的预测图像

如下所示,我将horizo​​ntal_flip = True发送到ImageDataGenerator

train_datagen = ImageDataGenerator( 
                rescale = 1. / 255, 
                 shear_range = …
Run Code Online (Sandbox Code Playgroud)

python image-processing conv-neural-network keras tensorflow

3
推荐指数
1
解决办法
2131
查看次数

如何使用 Plotly 制作简单的多级桑基图?

我有一个像这样的 DataFrame,我试图用 Sankey 图来描述它:

import pandas as pd

pd.DataFrame({
    'animal': ['dog', 'cat', 'cat', 'dog', 'cat'],
    'sex': ['male', 'female', 'female', 'male', 'male'],
    'status': ['wild', 'domesticated', 'domesticated', 'wild', 'domesticated'],
    'count': [8, 10, 11, 14, 6]
})
Run Code Online (Sandbox Code Playgroud)
    animal  sex     status          count
0   dog     male    wild            8
1   cat     female  domesticated    10
2   cat     female  domesticated    11
3   dog     male    wild            14
4   cat     male    domesticated    6
Run Code Online (Sandbox Code Playgroud)

我试图按照文档中的步骤操作,但无法使其工作 - 我无法理解哪些分支在哪里。这是示例代码:

import plotly.graph_objects as go

fig = go.Figure(data=[go.Sankey(
    node = dict(
      pad = 15, …
Run Code Online (Sandbox Code Playgroud)

python pandas plotly sankey-diagram plotly-python

3
推荐指数
1
解决办法
9578
查看次数