只是想自己生成一个数据集,但它得到了错误。这让我很困惑。任何帮助将不胜感激!
这是代码:
import tensorflow as tf
import numpy as np
def simulation_linear_function(x, a, b): # y = ax+b
y = tf.matmul(a, x)+b
return y
# Generate data set
num_input = 3
num_dense_unit = 2
a = np.array([0.1,0.2,0.3,0.4]).reshape((2,2))
b = np.array([0.5,0.6]).reshape((2,1))
num_data = 300
inputs = np.random.random((num_data,2))
labels = np.zeros((num_data,2))
for n in range(num_data):
x = inputs[n]
y = simulation_linear_function(np.reshape(x, (2,1)), a, b)
labels[n] = np.reshape(y, (2,))
dataset = tf.data.Dataset.from_tensor_slices((inputs, labels))
linear_layer = tf.keras.layers.Dense(units=2, input_shape=(2,))
linear_model = tf.keras.Sequential([linear_layer])
linear_model.compile(loss='mean_squared_error', optimizer=tf.keras.optimizers.Adam(1))
history = linear_model.fit(dataset, epochs=100, verbose=True)
# history = linear_model.fit(inputs, labels, epochs=100, verbose=True)
错误是: Traceback(最近一次调用最后一次):..... ValueError:层顺序的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 2,但接收到形状为 (2, 1 )
但是如果你切换到最后一个注释行,模型就可以被正确训练。
谢谢,汤姆