小编Mar*_*ani的帖子

ValueError:层顺序_20 需要 1 个输入,但它收到 2 个输入张量

我正在尝试使用来自 Tensorflow 的 KMNIST 数据集和我正在使用的教科书中的一些示例代码构建一个简单的自动编码器,但是当我尝试拟合模型时,我不断收到错误消息。

错误说 ValueError: Layer sequential_20 expects 1 inputs, but it received 2 input tensors.

我对 TensorFlow 真的很陌生,我对这个错误的所有研究都让我感到困惑,因为它似乎涉及我的代码中没有的东西。 这个线程没有帮助,因为我只使用顺序层。

完整代码:

import numpy as np
import tensorflow as tf
from tensorflow import keras
import tensorflow_datasets as tfds
import pandas as pd
import matplotlib.pyplot as plt

#data = tfds.load(name = 'kmnist')

(img_train, label_train), (img_test, label_test) = tfds.as_numpy(tfds.load(
    name = 'kmnist',
    split=['train', 'test'],
    batch_size=-1,
    as_supervised=True,
))

img_train = img_train.squeeze()
img_test = img_test.squeeze()

## From Hands on Machine Learning Textbook, …
Run Code Online (Sandbox Code Playgroud)

python machine-learning deep-learning keras tensorflow

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

Tensorflow:logits 和标签必须具有相同的第一维

我是 tensoflow 的新手,我想用我自己的数据(40x40 的图像)调整 MNIST 教程https://www.tensorflow.org/tutorials/layers。这是我的模型函数:

def cnn_model_fn(features, labels, mode):
        # Input Layer
        input_layer = tf.reshape(features, [-1, 40, 40, 1])

        # Convolutional Layer #1
        conv1 = tf.layers.conv2d(
                inputs=input_layer,
                filters=32,
                kernel_size=[5, 5],
                #  To specify that the output tensor should have the same width and height values as the input tensor
                # value can be "same" ou "valid"
                padding="same",
                activation=tf.nn.relu)

        # Pooling Layer #1
        pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)

        # Convolutional Layer #2 and Pooling Layer #2
        conv2 …
Run Code Online (Sandbox Code Playgroud)

python keras tensorflow tensorflow-datasets tensorflow-estimator

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

从 Python 中调用 Google Cloud Function

我正在尝试使用以下命令从 Python 中调用 Google Cloud 函数:

import requests
url = "MY_CLOUD_FUNCTON_URL"
data = {'name': 'example'}
response = requests.post(url, data = data)
Run Code Online (Sandbox Code Playgroud)

但我得到了错误:Your client does not have permission to get URL MY_CLOUD_FUNCTON from this server

有谁知道我怎样才能避免这个错误?我假设我应该以某种方式将凭据作为请求的一部分传递?

另请注意,如果我尝试从命令行通过 gcloud 调用该函数(如下所示),那么它可以工作,但我想在 python 中执行此操作

gcloud functions call MY_CLOUD_FUNCTON --data '{"name": "example"}' 
Run Code Online (Sandbox Code Playgroud)

任何帮助将非常感激!

python python-requests google-cloud-platform google-cloud-functions

14
推荐指数
2
解决办法
9937
查看次数

如何将注意力层添加到 Bi-LSTM

我正在开发一个 Bi-LSTM 模型并想为其添加一个注意力层。但我不知道如何添加它。

我当前的模型代码是

model = Sequential()
model.add(Embedding(max_words, 1152, input_length=max_len, weights=[embeddings]))
model.add(BatchNormalization())
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Bidirectional(LSTM(32)))
model.add(BatchNormalization())
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.summary()
Run Code Online (Sandbox Code Playgroud)

模型摘要是

Model: "sequential_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
embedding_1 (Embedding)      (None, 1152, 1152)        278396928 
_________________________________________________________________
batch_normalization_1 (Batch (None, 1152, 1152)        4608      
_________________________________________________________________
activation_1 (Activation)    (None, 1152, 1152)        0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 1152, 1152)        0         
_________________________________________________________________
bidirectional_1 (Bidirection (None, 64)                303360    
_________________________________________________________________
batch_normalization_2 (Batch (None, 64)                256       
_________________________________________________________________
activation_2 (Activation)    (None, 64)                0         
_________________________________________________________________
dropout_2 (Dropout) …
Run Code Online (Sandbox Code Playgroud)

nlp machine-learning python-3.x keras tensorflow

14
推荐指数
1
解决办法
4521
查看次数

GradientTape 中的简单 Keras 网络:LookupError:没有为操作“IteratorGetNext”定义梯度(操作类型:IteratorGetNext)

我构建了一个非常简单的带有单个密集层的 TensorFlow Keras 模型。它在块外工作得很好GradientTape,但在GradientTape块内它会引发LookupError: No gradient defined for operation 'IteratorGetNext' (op type: IteratorGetNext)

重现代码:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import tensorflow as tf
import numpy as np

print(tf.__version__)

model = Sequential()
model.add(Dense(1, input_shape=(16,)))

fake_data = np.random.random((1, 16))

print(model.predict(fake_data).shape) # works
with tf.GradientTape() as tape:
    print(model.predict(fake_data).shape) # LookupError: No gradient defined for operation 'IteratorGetNext' (op type: IteratorGetNext)
Run Code Online (Sandbox Code Playgroud)

这似乎在 TensorFlow 2.0.0 中有效,但在 TensorFlow 2.1.0 和 2.2.0 中失败

是一个重现该问题的笔记本。

python machine-learning keras tensorflow tensorflow2.0

11
推荐指数
1
解决办法
6095
查看次数

多类分类问题中的不平衡类

我正在尝试使用 TensorFlow 的 DNNClassifier 来解决我的 4 个不同类的多类(softmax)分类问题。我有一个具有以下分布的不平衡数据集:

  • 0 级:14.8%
  • 第一类:35.2%
  • 2 类:27.8%
  • 第 3 类:22.2%

如何weight_column为每个类的 DNNClassifier 分配权重?我知道如何对此进行编码,但我想知道我应该为每个类提供什么值。

machine-learning neural-network deep-learning keras tensorflow

10
推荐指数
2
解决办法
636
查看次数

使用 nn.Identity 进行残差学习背后的想法是什么?

所以,我已经阅读了大约一半的原始 ResNet 论文,并且正在尝试找出如何为表格数据制作我的版本。

我读过一些关于 PyTorch 如何工作的博客文章,并且我看到大量使用nn.Identity(). 现在,论文还经常使用恒等映射这个术语。然而,它只是指以元素方式将一堆层的输入添加到同一堆栈的输出。如果输入和输出维度不同,那么本文讨论了用零填充输入或使用矩阵W_s将输入投影到不同的维度。

这是我在博客文章中找到的残差块的抽象:


class ResidualBlock(nn.Module):
    def __init__(self, in_channels, out_channels, activation='relu'):
        super().__init__()
        self.in_channels, self.out_channels, self.activation = in_channels, out_channels, activation
        self.blocks = nn.Identity()
        self.shortcut = nn.Identity()   
    
    def forward(self, x):
        residual = x
        if self.should_apply_shortcut: residual = self.shortcut(x)
        x = self.blocks(x)
        x += residual
        return x
    
    @property
    def should_apply_shortcut(self):
        return self.in_channels != self.out_channels
    
block1 = ResidualBlock(4, 4)
Run Code Online (Sandbox Code Playgroud)

以及我自己对虚拟张量的应用:

x = tensor([1, 1, 2, 2])
block1 = ResidualBlock(4, 4)
block2 = ResidualBlock(4, 6) …
Run Code Online (Sandbox Code Playgroud)

python neural-network deep-residual-networks pytorch

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

获取 ValueError: y 使用 scikit learn 的 LabelEncoder 时包含新标签

我有一个系列,如:

df['ID'] = ['ABC123', 'IDF345', ...]
Run Code Online (Sandbox Code Playgroud)

我正在使用 scikitLabelEncoder将其转换为要输入到RandomForestClassifier.

在培训期间,我的做法如下:

le_id = LabelEncoder()
df['ID'] = le_id.fit_transform(df.ID) 
Run Code Online (Sandbox Code Playgroud)

但是,现在为了测试/预测,当我传入新数据时,我想根据le_id即从该数据转换“ID” ,如果存在相同的值,则根据上述标签编码器对其进行转换,否则分配一个新的数字价值。

在测试文件中,我的操作如下:

new_df['ID'] = le_dpid.transform(new_df.ID)
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误: ValueError: y contains new labels

我该如何解决??谢谢!

更新:

所以我的任务是使用以下(例如)作为训练数据并预测'High', 'Mod', 'Low'新 BankNum、ID 组合的值。模型应该学习从训练数据集中给出“高”和“低”的特征。例如,当存在多个具有相同 BankNum 和不同 ID 的条目时,会在“High”下方给出。

df = 

BankNum   | ID    | Labels

0098-7772 | AB123 | High
0098-7772 | ED245 | High
0098-7772 | ED343 | High
0870-7771 | ED200 | Mod
0870-7771 | ED100 | Mod
0098-2123 | …
Run Code Online (Sandbox Code Playgroud)

python encoding machine-learning scikit-learn categorical-data

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

如何在 Tensorflow 2.x Keras 自定义层中使用多个输入?

我正在尝试在 Tensorflow-Keras 的自定义层中使用多个输入。用法可以是任何东西,现在它被定义为将蒙版与图像相乘。我已经搜索过,我能找到的唯一答案是 TF 1.x,所以它没有任何好处。

class mul(layers.Layer):
def __init__(self, **kwargs):
    super().__init__(**kwargs)
    # I've added pass because this is the simplest form I can come up with.
    pass

def call(self, inputs):
    # magic happens here and multiplications occur
    return(Z)
Run Code Online (Sandbox Code Playgroud)

python layer keras tensorflow

9
推荐指数
1
解决办法
4296
查看次数

断言错误:无法计算输出张量

我正在尝试使用功能性 API 构建一个接受多个输入和多个输出的模型。我按照这个来创建代码。

def create_model_multiple():
    input1 = tf.keras.Input(shape=(13,), name = 'I1')
    input2 = tf.keras.Input(shape=(6,), name = 'I2')
    hidden1 = tf.keras.layers.Dense(units = 4, activation='relu')(input1)
    hidden2 = tf.keras.layers.Dense(units = 4, activation='relu')(input2)
    merge = tf.keras.layers.concatenate([hidden1, hidden2])
    hidden3 = tf.keras.layers.Dense(units = 3, activation='relu')(merge)
    output1 = tf.keras.layers.Dense(units = 2, activation='softmax', name ='O1')(hidden3)
    output2 = tf.keras.layers.Dense(units = 2, activation='softmax', name = 'O2')(hidden3)
    model = tf.keras.models.Model(inputs = [input1,input2], outputs = [output1,output2])
    model.compile(optimizer='adam',
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])
    return model
Run Code Online (Sandbox Code Playgroud)

我的 model.fit 命令如下所示:

history = model.fit({'I1':train_data, 'I2':new_train_data},
                    {'O1':train_labels, 'O2': …
Run Code Online (Sandbox Code Playgroud)

python machine-learning deep-learning keras tensorflow

9
推荐指数
1
解决办法
8658
查看次数