小编sri*_*tel的帖子

如何将 Tensorflow BatchNormalization 与 GradientTape 结合使用?

假设我们有一个使用 BatchNormalization 的简单 Keras 模型:

model = tf.keras.Sequential([
                     tf.keras.layers.InputLayer(input_shape=(1,)),
                     tf.keras.layers.BatchNormalization()
])
Run Code Online (Sandbox Code Playgroud)

如何实际使用 GradientTape?以下似乎不起作用,因为它没有更新移动平均线?

# model training... we want the output values to be close to 150
for i in range(1000):
  x = np.random.randint(100, 110, 10).astype(np.float32)
  with tf.GradientTape() as tape:
    y = model(np.expand_dims(x, axis=1))
    loss = tf.reduce_mean(tf.square(y - 150))
  grads = tape.gradient(loss, model.variables)
  opt.apply_gradients(zip(grads, model.variables))
Run Code Online (Sandbox Code Playgroud)

特别是,如果您检查移动平均值,它们将保持不变(检查 model.variables,平均值始终为 0 和 1)。我知道可以使用 .fit() 和 .predict(),但我想使用 GradientTape 并且我不知道如何执行此操作。某些版本的文档建议更新 update_ops,但这似乎在急切模式下不起作用。

特别是,经过上述训练后,以下代码将不会输出任何接近 150 的结果。

x = np.random.randint(200, 210, 100).astype(np.float32)
print(model(np.expand_dims(x, axis=1)))
Run Code Online (Sandbox Code Playgroud)

python keras tensorflow batch-normalization gradienttape

5
推荐指数
1
解决办法
1488
查看次数

如何访问生成器提供的 Keras 自定义损失函数中的样本权重?

我有一个生成器函数,它在某些图像目录上无限循环并输出 3 元组的形式

[img1, img2], label, weight
Run Code Online (Sandbox Code Playgroud)

其中img1img2batch_size x M x N x 3张量,并且labelweight各自batch_size的X 1张量。

fit_generator在用 Keras 训练模型时向函数提供了这个生成器。

对于这个模型,我有一个自定义的余弦对比损失函数,

def cosine_constrastive_loss(y_true, y_pred):
    cosine_distance = 1 - y_pred
    margin = 0.9
    cdist = y_true * y_pred + (1 - y_true) * keras.backend.maximum(margin - y_pred, 0.0)
    return keras.backend.mean(cdist)
Run Code Online (Sandbox Code Playgroud)

从结构上讲,我的模型一切正常。没有错误,它正在按预期消耗来自生成器的输入和标签。

但现在我正在寻求直接使用每个批次的权重参数,并cosine_contrastive_loss根据特定于样本的权重在内部执行一些自定义逻辑。

如何在执行损失函数时从一批样本的结构中访问此参数?

请注意,由于它是一个无限循环的生成器,因此无法预先计算权重或动态计算它们以将权重归入损失函数或生成它们。

它们具有一致地产生具有所产生的样品,并确有定制逻辑在我的数据生成器,从性能动态地确定的权重img1img2并且label在此刻它们用于分批生成。

python deep-learning keras tensorflow loss-function

5
推荐指数
1
解决办法
3671
查看次数

如何保存一个热编码器?

我正在尝试从 keras 保存一个热编码器,以便在不同的文本上再次使用它,但保持相同的编码。

这是我的代码:

df = pd.read_csv('dataset.csv ')
vocab_size = 200000
encoded_docs = [one_hot(d, vocab_size) for d in df.text]
Run Code Online (Sandbox Code Playgroud)

如何保存该编码器并稍后再次使用?

我在研究中发现了这一点,但 one_hot() 似乎是一个函数而不是一个对象(抱歉,如果这是完全错误的,我对 python 相当陌生)。

python pandas keras tensorflow one-hot-encoding

5
推荐指数
2
解决办法
1万
查看次数

使用 Tensorflow 2 的 Keras Functional API 时传递 `training=true`

在 TF1 中以图形模式运行时,我相信在使用函数式 API 时需要连接training=Truetraining=False通过 feeddicts。在 TF2 中执行此操作的正确方法是什么?

我相信这是在使用时自动处理的tf.keras.Sequential。例如,我不需要training文档中的以下示例中指定:

model = tf.keras.Sequential([
    tf.keras.layers.Conv2D(32, 3, activation='relu',
                           kernel_regularizer=tf.keras.regularizers.l2(0.02),
                           input_shape=(28, 28, 1)),
    tf.keras.layers.MaxPooling2D(),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dropout(0.1),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.BatchNormalization(),
    tf.keras.layers.Dense(10, activation='softmax')
])

# Model is the full model w/o custom layers
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(train_data, epochs=NUM_EPOCHS)
loss, acc = model.evaluate(test_data)
print("Loss {:0.4f}, Accuracy {:0.4f}".format(loss, acc))
Run Code Online (Sandbox Code Playgroud)

我还可以假设 keras 在使用功能性 api 进行训练时会自动处理这个问题吗?这是相同的模型,使用函数 api 重写:

inputs = tf.keras.Input(shape=((28,28,1)), name="input_image")
hid = tf.keras.layers.Conv2D(32, 3, activation='relu',
                           kernel_regularizer=tf.keras.regularizers.l2(0.02),
                           input_shape=(28, 28, …
Run Code Online (Sandbox Code Playgroud)

python keras tensorflow tf.keras tensorflow2.0

5
推荐指数
2
解决办法
3531
查看次数

Conda 软件包安装 [Errno 13] 安装 conda-forge::protobuf-3.8.0 时权限被拒绝

我有一个带有 Python 3.6 的 conda 环境,但我的 Pytorch 安装出了问题,所以我尝试再次安装它。在安装即将结束时,我收到此错误:

ERROR conda.core.link:_execute(700): An error occurred while installing package 'conda-forge::protobuf-3.8.0-py36h6de7cb9_1'.
Rolling back transaction: done

[Errno 13] Permission denied: '/Users/myusername/anaconda3/envs/torch/lib/python3.6/site-packages/google/protobuf/__init__.py'
()
Run Code Online (Sandbox Code Playgroud)

此外,它还说“环境不一致”,这可能表明某些地方已经出了问题。

完整详细信息:

$ conda install pytorch torchvision -c pytorch
Collecting package metadata (current_repodata.json): done
Solving environment: - 
The environment is inconsistent, please check the package plan carefully
The following packages are causing the inconsistency:

  - conda-forge/osx-64::tensorboard==1.14.0=py36_0
  - conda-forge/noarch::tensorboardx==1.9=py_0
done

## Package Plan ##

  environment location: /Users/myusername/anaconda3/envs/torch

  added / updated specs:
    - pytorch
    - …
Run Code Online (Sandbox Code Playgroud)

python permissions installation conda pytorch

5
推荐指数
2
解决办法
2万
查看次数

使用 Tensorflow 2.0 模型子分类访问层的输入/输出

在大学练习中,我使用了 TF2.0 的模型子分类 API。这是我的代码(它是 Alexnet 架构,如果你想知道的话......):

class MyModel(Model):
    def __init__(self):
        super(MyModel, self).__init__()
        # OPS
        self.relu = Activation('relu', name='ReLU')
        self.maxpool = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='valid', name='MaxPool')
        self.softmax = Activation('softmax', name='Softmax')

        # Conv layers
        self.conv1 = Conv2D(filters=96, input_shape=(224, 224, 3), kernel_size=(11, 11), strides=(4, 4), padding='same',
                            name='conv1')
        self.conv2a = Conv2D(filters=128, kernel_size=(5, 5), strides=(1, 1), padding='same', name='conv2a')
        self.conv2b = Conv2D(filters=128, kernel_size=(5, 5), strides=(1, 1), padding='same', name='conv2b')
        self.conv3 = Conv2D(filters=384, kernel_size=(3, 3), strides=(1, 1), padding='same', name='conv3')
        self.conv4a = Conv2D(filters=192, kernel_size=(3, 3), strides=(1, 1), padding='same', …
Run Code Online (Sandbox Code Playgroud)

python conv-neural-network keras tensorflow tensorflow2.0

5
推荐指数
1
解决办法
1992
查看次数

如何在 AWS Lambda 上使用 Tensorflow Lite

我正在尝试在 AWS Lambda 上托管一个我编译为 .tflite 的小模型。使用 tensorflow 网站上提供的 python 3.6 或 python 3.7 tflite 轮文件,我压缩了我的包/代码,然后上传到 S3 并链接到 lambda 并留出空间。但是,当我测试我的函数时,它在尝试加载 tflite 时崩溃了。最初,它无法加载共享对象文件。这是错误

[ERROR] Runtime.ImportModuleError: Unable to import module 'lambda_predict': No module named '_interpreter_wrapper')
Run Code Online (Sandbox Code Playgroud)

我找到了这个共享对象文件并将其移动到本地目录中,然后又出现了另一个错误

Unable to import module 'lambda_predict': /lib64/libm.so.6: version `GLIBC_2.27' not found (required by /var/task/_interpreter_wrapper.so)
Run Code Online (Sandbox Code Playgroud)

我的基本系统是 Ubuntu (Bionic Beaver) 这两个错误都来自导入 tflite

python amazon-web-services aws-lambda tensorflow tensorflow-lite

4
推荐指数
2
解决办法
1971
查看次数

使用 to_pickle 在循环中保存多个数据帧

你好,我有 4 个 pandas 数据框:df1、df2、df3、df4。我喜欢做的是使用 迭代(使用 for 循环)此数据帧的保存to_pickle。我所做的是这样的:

out = 'mypath\\myfolder\\'

r = [ orders, adobe, mails , sells]
for i in r:
    i.to_pickle( out +   '\\i.pkl')
Run Code Online (Sandbox Code Playgroud)

该命令很好,但它不会用他的名字保存每个数据库,而是覆盖相同的数据库i.pkl(我认为因为我的代码不正确)似乎它不能用他的名字重命名每个数据库(例如,对于 for 循环订单内的订单与涉及的订单数据帧一起保存名称i.pkl等)我期望的是保存4个数据帧,并在对象r中插入插入的名称(例如:orders.pkl,adobe.pkl,mails.pkl,sells.pkl)

我怎样才能做到这一点?

python pickle dataframe python-3.x pandas

2
推荐指数
1
解决办法
4573
查看次数

TensorFlow 2.0“构建”功能

我正在阅读有关使用 TensorFlow 2.0 结合“GradientTape”API 创建神经网络的内容,并发现了以下代码:

model = tf.keras.Sequential((
tf.keras.layers.Reshape(target_shape=(28 * 28,), input_shape=(28, 28)),
tf.keras.layers.Dense(100, activation='relu'),
tf.keras.layers.Dense(100, activation='relu'),
tf.keras.layers.Dense(10)))

model.build()
optimizer = tf.keras.optimizers.Adam()
Run Code Online (Sandbox Code Playgroud)

在这段代码中,“model.build()”的用途/功能是什么?是编译设计好的神经网络吗?

其余的代码是:

compute_loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)

compute_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()


def train_one_step(model, optimizer, x, y):
  with tf.GradientTape() as tape:
    logits = model(x)
    loss = compute_loss(y, logits)

  grads = tape.gradient(loss, model.trainable_variables)
  optimizer.apply_gradients(zip(grads, model.trainable_variables))

  compute_accuracy(y, logits)
  return loss


@tf.function
def train(model, optimizer):
  train_ds = mnist_dataset()
  step = 0
  loss = 0.0
  accuracy = 0.0
  for x, y in train_ds:
    step += 1 …
Run Code Online (Sandbox Code Playgroud)

python-3.x deep-learning tensorflow tf.keras tensorflow2.0

2
推荐指数
1
解决办法
1416
查看次数