首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >尝试将不受支持类型(<class 'NoneType'>)的值(无)转换为张量

尝试将不受支持类型(<class 'NoneType'>)的值(无)转换为张量
EN

Stack Overflow用户
提问于 2021-12-28 13:31:56
回答 1查看 1.5K关注 0票数 0

我正面临着错误

代码语言:javascript
运行
复制
Attempt to convert a value (None) with an unsupported type (<class 'NoneType'>) to a Tensor

有一个非常琐碎的代码,不知道错误来自哪里。在木星笔记本上运行相同的代码是可行的。

代码语言:javascript
运行
复制
import tensorflow as tf
import numpy as np

# inherit from this base class
from tensorflow.keras.layers import Layer

class SimpleDense(Layer):

    def __init__(self, units=32):
        '''Initializes the instance attributes'''
        super(SimpleDense, self).__init__()
        self.units = units

    def build(self, input_shape):
        '''Create the state of the layer (weights)'''
        # initialize the weights
        w_init = tf.random_normal_initializer()
        self.w = tf.Variable(name="kernel",
            initial_value=w_init(shape=(input_shape[-1], self.units),
                                 dtype='float32'),
            trainable=True)

        # initialize the biases
        b_init = tf.zeros_initializer()
        self.b = tf.Variable(name="bias",
            initial_value=b_init(shape=(self.units,), dtype='float32'),
            trainable=True)

    def call(self, inputs):
        '''Defines the computation from inputs to outputs'''
        return tf.matmul(inputs, self.w) + self.b

# declare an instance of the class
my_dense = SimpleDense(units=1)

# define an input and feed into the layer
x = tf.ones((2, 1))
y = my_dense(x)

# parameters of the base Layer class like `variables` can be used
print(my_dense.variables)

# define the dataset
xs = np.array([-1.0,  0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float)


# use the Sequential API to build a model with our custom layer
my_layer = SimpleDense(units=1)
model = tf.keras.Sequential([my_layer])

# configure and train the model
model.compile(optimizer='sgd', loss='mean_squared_error')
model.fit(xs, ys, epochs=500,verbose=0)

# perform inference
print(model.predict([10.0]))

# see the updated state of the variables
print(my_layer.variables)

更新:包含反向跟踪的错误消息

代码语言:javascript
运行
复制
In user code:

    File "keras\engine\training.py", line 878, in train_function  *
        return step_function(self, iterator)
    File "keras\engine\training.py", line 867, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "keras\engine\training.py", line 860, in run_step  **
        outputs = model.train_step(data)
    File "keras\engine\training.py", line 808, in train_step
        y_pred = self(x, training=True)
    File "keras\utils\traceback_utils.py", line 67, in error_handler
        raise e.with_traceback(filtered_tb) from None
    File "Dense_Layer.py", line 19, in build
        initial_value=w_init(shape=(input_shape[-1], self.units),

    ValueError: Exception encountered when calling layer "sequential" (type Sequential).
    
    Attempt to convert a value (None) with an unsupported type (<class 'NoneType'>) to a Tensor.
    
    Call arguments received:
      • inputs=tf.Tensor(shape=(None,), dtype=float32)
      • training=True
      • mask=None
  File "Dense_Layer.py", line 19, in build
    initial_value=w_init(shape=(input_shape[-1], self.units),

During handling of the above exception, another exception occurred:

  File "Temp\__autograph_generated_filexvnq5chx.py", line 15, in tf__train_function
    retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)
  File "Dense_Layer.py", line 19, in build
    initial_value=w_init(shape=(input_shape[-1], self.units),

During handling of the above exception, another exception occurred:

  File "Dense_Layer.py", line 54, in <module>
    model.fit(xs, ys, epochs=500,verbose=0)

:Python3.9.5(tag/v3.9.5:0a7dcbd,2021年5月3日,17:27:52) MSC v.1928 64位(AMD64) on win32

CopyRight: Deeplearning.ai

EN

回答 1

Stack Overflow用户

发布于 2022-04-12 14:22:58

在顺序API中添加一个“输入层”将解决这个问题。

可能是不同的tensorflow版本的问题。这可能就是它在木星笔记本上工作的原因。

更改:

代码语言:javascript
运行
复制
# use the Sequential API to build a model with our custom layer
    input_layer = tf.keras.Input(shape=(1,)) # Added Newly
    my_layer = SimpleDense(units=1)
    model = tf.keras.Sequential([input_layer, my_layer]) # Added input_layer here.

完整法典:

代码语言:javascript
运行
复制
import tensorflow as tf
import numpy as np

# inherit from this base class
from tensorflow.keras.layers import Layer

class SimpleDense(Layer):

    def __init__(self, units=32):
        '''Initializes the instance attributes'''
        super(SimpleDense, self).__init__()
        self.units = units

    def build(self, input_shape):
        '''Create the state of the layer (weights)'''
        # initialize the weights
        w_init = tf.random_normal_initializer()
        self.w = tf.Variable(name="kernel",
            initial_value=w_init(shape=(input_shape[-1], self.units),
                                 dtype='float32'),
            trainable=True)

        # initialize the biases
        b_init = tf.zeros_initializer()
        self.b = tf.Variable(name="bias",
            initial_value=b_init(shape=(self.units,), dtype='float32'),
            trainable=True)

    def call(self, inputs):
        '''Defines the computation from inputs to outputs'''
        return tf.matmul(inputs, self.w) + self.b

# declare an instance of the class
my_dense = SimpleDense(units=1)

# define an input and feed into the layer
x = tf.ones((2, 1))
y = my_dense(x)

# parameters of the base Layer class like `variables` can be used
print(my_dense.variables)

# define the dataset
xs = np.array([-1.0,  0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float)


# use the Sequential API to build a model with our custom layer
input_layer = tf.keras.Input(shape=(1,)) # Added Newly
my_layer = SimpleDense(units=1)
model = tf.keras.Sequential([input_layer, my_layer]) # Added input_layer here.

# configure and train the model
model.compile(optimizer='sgd', loss='mean_squared_error')
model.fit(xs, ys, epochs=500,verbose=0)

# perform inference
print(model.predict([10.0]))

# see the updated state of the variables
print(my_layer.variables)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70507803

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档