如果你的pycharm会莫名其妙运行一个py文件然后才运行你选中的文件,

那是因为pycharm自动给你增加了一行from...import语句,

例如,你已经有了一个test.py文件,

 1 import tensorflow as tf
 2 from tensorflow.keras.callbacks import ModelCheckpoint
 3 import numpy as np
 4 
 5 import os
 6 file_name = os.path.basename(__file__)
 7 print("=======================")
 8 print(f"当前运行的文件名是: {file_name}")
 9 print("=======================")
10 # 自定义 preprocess_input 函数并使用 register_keras_serializable 注册
11 @tf.keras.saving.register_keras_serializable(name="my_preprocess_input")
12 def my_preprocess_input(x):
13     # 使用 VGG16 的预处理方法作为例子
14     return tf.keras.applications.vgg16.preprocess_input(x)
15 
16 # 构建一个简单的 CNN 模型,直接在模型中使用自定义的 preprocess_input 函数
17 inputs = tf.keras.Input(shape=(180, 180, 3))
18 x = my_preprocess_input(inputs)  # 直接调用已注册的 preprocess_input 函数
19 x = tf.keras.layers.Conv2D(32, (3, 3), activation='relu')(x)
20 x = tf.keras.layers.MaxPooling2D()(x)
21 x = tf.keras.layers.Conv2D(64, (3, 3), activation='relu')(x)
22 x = tf.keras.layers.MaxPooling2D()(x)
23 x = tf.keras.layers.Flatten()(x)
24 x = tf.keras.layers.Dense(256, activation='relu')(x)
25 x = tf.keras.layers.Dropout(0.5)(x)
26 outputs = tf.keras.layers.Dense(1, activation="sigmoid")(x)
27 model = tf.keras.Model(inputs, outputs)
28 
29 # 编译模型
30 model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
31 
32 # 创建一个回调函数来保存最好的模型
33 checkpoint_callback = ModelCheckpoint('best_model.h5', save_best_only=True, monitor='val_loss', mode='min')
34 
35 # 模拟一些数据进行训练(假设是二分类问题)
36 # 创建虚拟数据
37 x_train = np.random.rand(100, 180, 180, 3)  # 100 张 180x180 的 RGB 图片
38 y_train = np.random.randint(0, 2, 100)  # 100 个标签,0 或 1
39 x_val = np.random.rand(20, 180, 180, 3)  # 20 张验证数据
40 y_val = np.random.randint(0, 2, 20)
41 
42 # 训练模型并保存最佳模型
43 model.fit(x_train, y_train, epochs=5, validation_data=(x_val, y_val), callbacks=[checkpoint_callback])
44 
45 # 现在加载保存的最佳模型
46 loaded_model = tf.keras.models.load_model('best_model.h5', custom_objects={'my_preprocess_input': my_preprocess_input})
47 
48 # 使用加载的模型进行评估
49 loss, accuracy = loaded_model.evaluate(x_val, y_val)
50 print(f"Loaded model evaluation - Loss: {loss}, Accuracy: {accuracy}")

 

当前文件你写了个outputs,然后pycharm自作聪明给你在开头写了一行from test import outputs,

导致当前文件运行中会嵌套调用别的文件。

解决办法也很简单,可以尝试修改与自动导入相关的设置。

但我更倾向于检查一下文件开头的导入。