我尝试执行下面的代码,但出现错误: NameError:名称“scipy”未定义 我已经安装了 scipy 并导入了它, python 版本 = 3.9 ,tensorflow 版本 = 2.15.0, 它在模型编译之前运行良好,但在训练模型时出现错误
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import scipy
# set random seed
tf.random.set_seed(99)
# preprocess data (get all of the pixel values between 0 & 1 also called scaling or normalization)
train_data_gen = ImageDataGenerator(rescale=1.0/255)
test_data_gen = ImageDataGenerator(rescale=1.0/255)
# Setup path for data directories
train_data_path = 'pizza_steak/train/'
test_data_path = 'pizza_steak/test/'
# It creates data and labels automatically for us
train_data = train_data_gen.flow_from_directory(
directory = train_data_path,
batch_size = 32, # batch_size=32 means that there are 32 training instances in each batch.
target_size = (224,224), # # resize to this size
class_mode = 'binary',
seed = 42
)
test_data = test_data_gen.flow_from_directory(
directory = test_data_path ,
batch_size = 32,
target_size = (224,224),
class_mode = 'binary',
seed = 42
)
# Buiding a CNN model
model_1 = tf.keras.Sequential([
tf.keras.layers.Conv2D(filters=10,
kernel_size = 3,
activation = 'relu',
input_shape = (224,224,3)), # input shape from train_generator as we are resizing to 224,224
tf.keras.layers.Conv2D(10, 3, activation='relu'),
tf.keras.layers.MaxPool2D(pool_size=2,
padding = 'valid'),
tf.keras.layers.Conv2D(10, 3, activation='relu'),
tf.keras.layers.Conv2D(10,3, activation='relu'),
tf.keras.layers.MaxPool2D(2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(1, activation = 'sigmoid')
])
# compile our CNN
model_1.compile(
loss = "binary_crossentropy",
optimizer = tf.keras.optimizers.Adam(),
metrics = ["accuracy"]
)
# fit the model
model_1.fit(train_data,
epochs=5,
steps_per_epoch = len(train_data),
validation_data = test_data,
validation_steps = len(test_data))
# we dont have to pass X,y here as flow_from_directory does it for us automatically
它可以工作,安装后我必须重新启动我的内核。