我正在做"虹膜数据集的模型验证"的作业。
我得到这个错误:"检查输入时出错:期望dense_input的形状为(135,),但得到的数组的形状为(4,)"。我如何克服这个问题?
我的密码是
from numpy.random import seed
seed(8)
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets, model_selection
from sklearn.model_selection import train_test_split
%matplotlib inline
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D
def read_in_and_split_data(iris_data):
data=iris_data["data"]
targets=iris_data["target"]
train_data, test_data, train_targets, test_targets= train_test_split(data,targets,test_size=0.1)
return(train_data, test_data, train_targets, test_targets)
iris_data = datasets.load_iris()
train_data, test_data, train_targets, test_targets = read_in_and_split_data(iris_data)
train_targets = tf.keras.utils.to_categorical(np.array(train_targets))
test_targets = tf.keras.utils.to_categorical(np.array(test_targets))
def get_model(input_shape):
model= Sequential ([
Dense(64, kernel_initializer='he_uniform',bias_initializer='ones', input_shape=(train_data.shape[0],)),
Dense(128, activation= "relu"),
Dense(128, activation= "relu"),
Dense(128, activation= "relu"),
Dense(128, activation= "relu"),
Dense(64, activation= "relu"),
Dense(64, activation= "relu"),
Dense(64, activation= "relu"),
Dense(64, activation= "relu"),
Dense(3, activation= 'softmax')
])
return model
model = get_model(train_data[0].shape)
def compile_model(model):
opt= tf.keras.optimizers.Adam(learning_rate=0.0001)
acc= tf.keras.metrics.SparseCategoricalAccuracy()
mae= tf.keras.metrics.MeanAbsoluteError()
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
compile_model(model)
def train_model(model, train_data, train_targets, epochs):
return model.fit(train_data, train_targets, epochs=epochs, validation_split= 0.15, batch_size=40)
一切都很正常直到我加载这个单元
history = train_model(model, train_data, train_targets, epochs=800)
这时会弹出错误框
ValueError Traceback (most recent call last)
<ipython-input-20-96db4320a1b9> in <module>
1 # Run your function to train the model
2
----> 3 history = train_model(model, train_data, train_targets, epochs=800)
<ipython-input-19-ce18af880dd7> in train_model(model, train_data, train_targets, epochs)
11 """
12
---> 13 return model.fit(train_data, train_targets, epochs=epochs, validation_split= 0.15,
batch_size=40)
14
15
/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training.py in fit(self,
x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle,
class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq,
max_queue_size, workers, use_multiprocessing, **kwargs)
726 max_queue_size=max_queue_size,
727 workers=workers,
--> 728 use_multiprocessing=use_multiprocessing)
729
730 def evaluate(self,
/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_v2.py in
fit(self, model, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data,
shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps,
validation_freq, **kwargs)
222 validation_data=validation_data,
223 validation_steps=validation_steps,
--> 224 distribution_strategy=strategy)
225
226 total_samples = _get_total_number_of_samples(training_data_adapter)
/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_v2.py in _
process_training_inputs(model, x, y, batch_size, epochs, sample_weights, class_weights,
steps_per_epoch, validation_split, validation_data, validation_steps, shuffle,
distribution_strategy, max_queue_size, workers, use_multiprocessing)
514 batch_size=batch_size,
515 check_steps=False,
--> 516 steps=steps_per_epoch)
517 (x, y, sample_weights,
518 val_x, val_y,
/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training.py in _
standardize_user_data(self, x, y, sample_weight, class_weight, batch_size, check_steps, steps_name,
steps, validation_split, shuffle, extract_tensors_from_dataset)
2470 feed_input_shapes,
2471 check_batch_axis=False, # Don't enforce the batch size.
-> 2472 exception_prefix='input')
2473
2474 # Get typespecs for the input data and sanitize it if necessary.
/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_utils.py in
standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
572 ': expected ' + names[i] + ' to have shape ' +
573 str(shape) + ' but got array with shape ' +
--> 574 str(data_shape))
575 return data
576
ValueError: Error when checking input: expected dense_input to have shape (135,) but got array with
shape (4,)
1条答案
按热度按时间6vl6ewon1#
此错误表明您的输入数据形状与模型的输入形状不兼容。您需要检查train_data形状:
查看形状是否与模型input_shape兼容。我的猜测是,您还没有调用函数read_in_and_split_data,train_data来自另一个单元格