TensorFlow 基础

TensorFlow 模型建立与训练 中的代码

import tensorflow as tf

x = tf.constant ([1.0, 2.0, 3.0], [4.0, 5.0, 6.0])
y = tf.constant ([10.0], [20.0])

class Linear (tf.keras.Model):
def init(self):
super ().init()
self.dense = tf.keras.layers.Dense (
units=1,
activation=None,
kernel_initializer=tf.zeros_initializer (),
bias_initializer=tf.zeros_initializer ()
)

def call (self, input):
    output = self.dense (input)
    return output

model = Linear ()
optimizer = tf.keras.optimizers.SGD (learning_rate=0.01)
for i in range (100):
with tf.GradientTape () as tape:
y_pred = model (x)
loss = tf.reduce_mean (tf.square (y_pred - y))
grads = tape.gradient (loss, model.variables)
optimizer.apply_gradients (grads_and_vars=zip (grads, model.variables))
print (model.variables)

错误信息:
D:\ProgramData\Anaconda3\python.exe E:/develop/python/tensorflow/pyqt.py
Traceback (most recent call last):
File “D:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\framework\constant_op.py”, line 92, in convert_to_eager_tensor
dtype = dtype.as_datatype_enum
AttributeError: ‘list’ object has no attribute ‘as_datatype_enum’

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File “E:/develop/python/tensorflow/pyqt.py”, line 3, in
x = tf.constant ([1.0, 2.0, 3.0], [4.0, 5.0, 6.0])
File “D:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\framework\constant_op.py”, line 258, in constant
allow_broadcast=True)
File “D:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\framework\constant_op.py”, line 266, in _constant_impl
t = convert_to_eager_tensor (value, ctx, dtype)
File “D:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\framework\constant_op.py”, line 94, in convert_to_eager_tensor
dtype = dtypes.as_dtype (dtype).as_datatype_enum
File “D:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\framework\dtypes.py”, line 720, in as_dtype
return _ANY_TO_TF [type_value]
TypeError: unhashable type: ‘list’