尝试使用预测函数时出现TensorFlow形状不兼容错误



我有这样的代码:我想测试一下,但我收到了以下警告和错误

WARNING:tensorflow:Model was constructed with shape (None, 7) for input KerasTensor(type_spec=TensorSpec(shape=(None, 7), dtype=tf.float32, name='normalization_1_input'), name='normalization_1_input', description="created by layer 'normalization_1_input'"), but it was called on an input with incompatible shape (None, 1).

这个:

ValueError: Input 0 of layer dense is incompatible with the layer: expected axis -1 of input shape to have value 7 but received input with shape (None, 1)

CCD_ 1线路上出现的第一个错误

import pandas as pd
import numpy as np
# Make NumPy printouts easier to read.
np.set_printoptions(precision=3, suppress=True)
import tensorflow as tf
from tensorflow.keras import layers
data = [[45.975, 45.81, 45.715, 45.52, 45.62, 45.65, 44.62],
[55.67, 55.975, 55.97, 56.27, 56.23, 56.275, 56.28],
[86.87, 86.925, 86.85, 85.78, 86.165, 86.165, 86.83],
[64.3, 64.27, 64.285, 64.29, 64.325, 64.245, 64.31],
[35.655, 35.735, 35.66, 35.69, 35.665, 35.63, 35.66],
[35.655, 35.735, 35.66, 35.69, 35.665, 35.63, 35.64],
[35.655, 35.735, 35.66, 35.69, 35.665, 35.63, 35.67],
[35.655, 35.735, 35.66, 35.69, 35.665, 35.63, 35.645],
[35.655, 35.735, 35.66, 35.69, 35.665, 35.63, 35.669]
]
lables = [0, 1, 0, 1, 1, 0, 1, 0, 1]

def do():
d_1 = None
for l, d in zip(lables, data):
if d_1 is None:
d_1 = pd.DataFrame({'close_price': [d]})
else:
d_1 = d_1.append({'close_price': d}, ignore_index=True)
d_1['lable'] = lables
dataset = d_1.copy()
print(dataset.isna().sum())
dataset = dataset.dropna()
print(dataset.keys())
train_dataset = dataset.sample(frac=0.8, random_state=0)
test_dataset = dataset.drop(train_dataset.index)
print(train_dataset.describe().transpose())
train_features = train_dataset.copy()
test_features = test_dataset.copy()
train_labels = train_features.pop('lable')
test_labels = test_features.pop('lable')
print(train_dataset.describe().transpose()[['mean', 'std']])
train_features_1 = np.array(train_features['close_price'].to_list())
test_features_1 = np.array(test_features['close_price'].to_list())
print(train_features_1.shape)
print(test_features_1.shape)
normalizer = tf.keras.layers.Normalization(axis=-1)
ar = np.array(train_features_1)
normalizer.adapt(ar)
print(normalizer.mean.numpy())
first = np.array(train_features_1[:1])
with np.printoptions(precision=2, suppress=True):
print('First example:', first)
print()
print('Normalized:', normalizer(first).numpy())
diraction = np.array(train_features_1)
diraction_normalizer = layers.Normalization(input_shape=[7,], axis=None)
diraction_normalizer.adapt(diraction)
diraction_model = tf.keras.Sequential([
diraction_normalizer,
layers.Dense(units=1)
])
print(diraction_model.summary())
print(diraction_model.predict(diraction[:4]))
diraction_model.compile(
optimizer=tf.optimizers.Adam(learning_rate=0.1),
loss='mean_absolute_error')
# print(train_features_1['close_price'])
history = diraction_model.fit(
train_features_1,
train_labels,
epochs=100,
# Suppress logging.
verbose=0,
# Calculate validation results on 20% of the training data.
validation_split=0.2)
hist = pd.DataFrame(history.history)
hist['epoch'] = history.epoch
print(hist.tail())
test_results = {}
test_features = np.array(test_features['close_price'].to_list())
test_results['diraction_model'] = diraction_model.evaluate(
test_features_1,
test_labels, verbose=0)
x = tf.linspace(0.0, 250, 251)
y = diraction_model.predict(x)
print(y)
print("end")

def main():
do()

if __name__ == "__main__":
main()

问题是tf.linspace正在创建形状为(251,)的1D张量,这与模型的输入形状(batch_size, 7)不兼容。例如,您可以重塑张量以适应您的模型:

x = tf.linspace(0.0, 250, 252)
x = tf.reshape(x, (36, 7))

它应该起作用。

最新更新