所以我安装了所有东西来在 Visual Studio 代码中运行 jupyter 笔记本,并完全更新了 TensorFlow 和 Python。但是,当我运行其中一个内核时,我不断遇到错误。具体来说,
File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\keras\src\utils\traceback_utils.py:122, in filter_traceback.<locals>.error_handler(*args, **kwargs)
119 filtered_tb = _process_traceback_frames(e.__traceback__)
120 # To get the full stack trace, call:
121 # `keras.config.disable_traceback_filtering()`
--> 122 raise e.with_traceback(filtered_tb) from None
123 finally:
124 del filtered_tb
File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\keras\src\trainers\data_adapters\__init__.py:113, in get_data_adapter(x, y, sample_weight, batch_size, steps_per_epoch, shuffle, class_weight)
105 return GeneratorDataAdapter(x)
106 # TODO: should we warn or not?
107 # warnings.warn(
108 # "`shuffle=True` was passed, but will be ignored since the "
(...)
111 # )
112 else:
--> 113 raise ValueError(f"Unrecognized data type: x={x} (of type {type(x)})
最后显示 ValueError: 无法识别的数据类型 x=[10.0] (of type
有什么办法可以解决这个问题吗?
这是我当前的代码:
import tensorflow as tf
import numpy as np
from tensorflow import keras
model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])
model.compile(optimizer='sgd', loss='mean_squared_error')
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)
model.fit(xs, ys, epochs=500)
print(model.predict([10.0])) #This is where the error is
这就是值错误的地方
if array_data_adapter.can_convert_arrays((x, y, sample_weight)):
return ArrayDataAdapter(
x,
y,
sample_weight=sample_weight,
class_weight=class_weight,
shuffle=shuffle,
batch_size=batch_size,
steps=steps_per_epoch,
)
elif is_tf_dataset(x):
# Unsupported args: y, sample_weight, shuffle
if y is not None:
raise_unsupported_arg("y", "the targets", "tf.data.Dataset")
if sample_weight is not None:
raise_unsupported_arg(
"sample_weights", "the sample weights", "tf.data.Dataset"
)
return TFDatasetAdapter(
x, class_weight=class_weight, distribution=distribution
)
# TODO: should we warn or not?
# warnings.warn(
# "`shuffle=True` was passed, but will be ignored since the "
# "data `x` was provided as a tf.data.Dataset. The Dataset is "
# "expected to already be shuffled "
# "(via `.shuffle(tf.data.AUTOTUNE)`)"
# )
elif isinstance(x, py_dataset_adapter.PyDataset):
if y is not None:
raise_unsupported_arg("y", "the targets", "PyDataset")
if sample_weight is not None:
raise_unsupported_arg(
"sample_weights", "the sample weights", "PyDataset"
)
return PyDatasetAdapter(x, class_weight=class_weight, shuffle=shuffle)
elif is_torch_dataloader(x):
if y is not None:
raise_unsupported_arg("y", "the targets", "torch DataLoader")
if sample_weight is not None:
raise_unsupported_arg(
"sample_weights", "the sample weights", "torch DataLoader"
)
if class_weight is not None:
raise ValueError(
"Argument `class_weight` is not supported for torch "
f"DataLoader inputs. Received: class_weight={class_weight}"
)
return TorchDataLoaderAdapter(x)
# TODO: should we warn or not?
# warnings.warn(
# "`shuffle=True` was passed, but will be ignored since the "
# "data `x` was provided as a torch DataLoader. The DataLoader "
# "is expected to already be shuffled."
# )
elif isinstance(x, types.GeneratorType):
if y is not None:
raise_unsupported_arg("y", "the targets", "PyDataset")
if sample_weight is not None:
raise_unsupported_arg(
"sample_weights", "the sample weights", "PyDataset"
)
if class_weight is not None:
raise ValueError(
"Argument `class_weight` is not supported for Python "
f"generator inputs. Received: class_weight={class_weight}"
)
return GeneratorDataAdapter(x)
# TODO: should we warn or not?
# warnings.warn(
# "`shuffle=True` was passed, but will be ignored since the "
# "data `x` was provided as a generator. The generator "
# "is expected to yield already-shuffled data."
# )
else:
raise ValueError(f"Unrecognized data type: x={x} (of type {type(x)})")
这是突出显示的另一段代码
def filter_traceback(fn):
"""Filter out Keras-internal traceback frames in exceptions raised by fn."""
@wraps(fn)
def error_handler(*args, **kwargs):
if not is_traceback_filtering_enabled():
return fn(*args, **kwargs)
filtered_tb = None
try:
return fn(*args, **kwargs)
except Exception as e:
filtered_tb = _process_traceback_frames(e.__traceback__)
# To get the full stack trace, call:
# `keras.config.disable_traceback_filtering()`
raise e.with_traceback(filtered_tb) from None
finally:
del filtered_tb
您可以直接在 Tensorflow 中使用
list
对象。改变
print(model.predict([10.0]))
到
pred = np.array([10.0]).reshape(1, -1)
print(model.predict(pred))
或者更好
pred = tf.reshape(tf.convert_to_tensor([10.0]), (1, -1))
print(model.predict(pred))
将列表
[10.0]
转换为 numpy 数组(如 model.fit(..)
调用的数组),或直接转换为 Tensorflow 张量。如果只有一个样本要预测,则需要向形状添加批次维度 1,因为 Tensorflow 期望输入为形状(批次、特征),即使批次只有 1 个元素。