Msy20070905 2024-07-19 08:49 采纳率: 21.2%
浏览 3

pycharm运行正常,festurize报错


import tensorflow as tf
from matplotlib import pyplot as plt
import os
import numpy as np
import glob
from torch.utils import data
from PIL import Image
from torchvision import transforms

# 数据集内图片的验证
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
dataset_path = "rps_data_sample"

labels = []
for i in os.listdir(dataset_path):
    if os.path.isdir(os.path.join(dataset_path, i)):
        labels.append(i)

NUM_EXAMPLES = 5

for label in labels:
    label_dir = os.path.join(dataset_path, label)
    example_filenames = os.listdir(label_dir)[:NUM_EXAMPLES]
    fig, axs = plt.subplots(1, 5, figsize=(10, 2))
    for i in range(NUM_EXAMPLES):
        axs[i].imshow(plt.imread(os.path.join(label_dir, example_filenames[i])))
        axs[i].get_xaxis().set_visible(False)
        axs[i].get_yaxis().set_visible(False)
    fig.suptitle(f'Showing {NUM_EXAMPLES} examples for {label}')


# 创建data.Dataset子类Mydataset
class Mydataset(data.Dataset):
    def __init__(self, root):
        self.imgs_path = root

    def __getitem__(self, index):
        img_path = self.imgs_path[index]
        return img_path

    def __len__(self):
        return len(self.imgs_path)


# glob遍历数据路径
all_imgs_path = glob.glob('rps_data_sample\\*\\*.jpg')
for var in all_imgs_path:
    print(var)

# 建立gesture_data
gesture_dataset = Mydataset(all_imgs_path)
print(len(gesture_dataset))

# path迭代
species = ['bad','good','normal']
species_to_id = dict((c, i) for i, c in enumerate(species))
id_to_species = dict((v, k) for k, v in species_to_id.items())
all_labels = []
for img in all_imgs_path:
    for i, c in enumerate(species):
        if c in img:
            all_labels.append(i)

transform = transforms.Compose([
    transforms.Resize((224, 224)),  # 统一图像尺寸
    transforms.ToTensor()
])
index = np.random.permutation(len(all_imgs_path))

all_imgs_path = np.array(all_imgs_path)[index]
all_labels = np.array(all_labels)[index]

p = int(len(all_imgs_path) * 0.8)
x_train_ = all_imgs_path[:p]
y_train_ = all_labels[:p]
x_test_ = all_imgs_path[p:]
y_test_ = all_labels[p:]


class MyDatasetpro(data.Dataset):
    def __init__(self, img_paths, labels, transform):
        self.imgs = img_paths
        self.labels = labels
        self.transforms = transform

    def __getitem__(self, index):
        img = self.imgs[index]
        label = self.labels[index]
        pil_img = Image.open(img).convert('RGB')  # 确保图像为RGB格式
        data = self.transforms(pil_img)
        return data, label

    def __len__(self):
        return len(self.imgs)


x_train = MyDatasetpro(x_train_, y_train_, transform)
x_test = MyDatasetpro(x_test_, y_test_, transform)


# 使用TensorFlow的数据处理功能
def tf_dataset(dataset, batch_size):
    def generator():
        for img, label in dataset:
            img = img.permute(1, 2, 0).numpy()  # 调整通道顺序
            yield img, label

    ds = tf.data.Dataset.from_generator(generator, output_types=(tf.float32, tf.int32),
                                        output_shapes=((224, 224, 3), ()))
    ds = ds.batch(batch_size)
    return ds


batch_size = 32
train_ds = tf_dataset(x_train, batch_size)
test_ds = tf_dataset(x_test, batch_size)

# tensorflow训练
model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(filters=32, kernel_size=(5, 5), padding='same', input_shape=(224, 224, 3)),
    tf.keras.layers.BatchNormalization(),
    tf.keras.layers.Conv2D(filters=96, kernel_size=(5, 5), padding='same'),
    tf.keras.layers.BatchNormalization(),
    tf.keras.layers.Activation('relu'),
    tf.keras.layers.AveragePooling2D(pool_size=(3, 3), padding='valid'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(256, activation='relu', kernel_regularizer=tf.keras.regularizers.l1()),
    tf.keras.layers.Dense(64, activation='relu', kernel_regularizer=tf.keras.regularizers.l1()),
    tf.keras.layers.Dense(5, activation='softmax', kernel_regularizer=tf.keras.regularizers.l1())
])
model.compile(optimizer='nadam', loss="sparse_categorical_crossentropy", metrics=["sparse_categorical_accuracy"])

history = model.fit(train_ds, batch_size=32,epochs=10000, validation_data=test_ds, validation_freq=1)
model.summary()

file = open('/weights.txt', 'w')
for v in model.trainable_variables:
    file.write(str(v.name) + '\n')
    file.write(str(v.shape) + '\n')
    file.write(str(v.numpy()) + '\n')
file.close()

# 可视化
acc = history.history['sparse_categorical_accuracy']
val_acc = history.history['val_sparse_categorical_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']

plt.subplot(1, 2, 1)
plt.plot(acc, label='Training Accuracy')
plt.plot(val_acc, label="Validation Accuracy")
plt.title('Training and Validation Accuracy')
plt.legend()

plt.subplot(1, 2, 2)
plt.plot(loss, label='Training Loss')
plt.plot(val_loss, label="Validation Loss")
plt.title('Training and Validation Loss')
plt.legend()

plt.show()

这段代码在pycharm中不报错,可以正常运行,但在festurize中运行就会报ValueError: Unexpected result of train_function (Empty logs). This could be due to issues in input pipeline that resulted in an empty dataset. Otherwise, please use Model.compile(..., run_eagerly=True), or tf.config.run_functions_eagerly(True) for more information of where went wrong, or file a issue/bug to tf.keras.该怎么弄啊

  • 写回答

4条回答 默认 最新

  • 阿里嘎多学长 2024-07-19 08:49
    关注

    以下内容由AIGC及阿里嘎多学长共同生成、有用望采纳:


    在 PyCharm 中运行正常但在 festurize 中运行时遇到 ValueError: Unexpected result of train_function (Empty logs) 的错误,通常是由于数据集处理或 TensorFlow 数据管道的问题。以下是一些可能的解决方案:

    1. 确保数据集路径正确

      • 确认 dataset_path 变量是否指向正确的文件夹。
      • 检查文件夹内是否有子文件夹和图片文件。
    2. 检查数据集加载逻辑

      • 确保 glob.glob 正确获取所有图片路径。你可以通过打印 all_imgs_path 来验证路径是否正确获取。
    3. 检查 MyDatasetpro

      • 确保 __getitem__ 方法正确返回图像和标签。可以通过打印 x_train[0]x_test[0] 来验证。
    4. 调整 TensorFlow 配置

      • 尝试在模型编译时添加 run_eagerly=True 来调试模型编译过程:
        model.compile(optimizer='nadam', loss="sparse_categorical_crossentropy", metrics=["sparse_categorical_accuracy"], run_eagerly=True)
        
      • 或者添加 tf.config.run_functions_eagerly(True) 来调试整个 TensorFlow 执行过程:
        tf.config.run_functions_eagerly(True)
        
    5. 逐步调试代码

      • 使用 PyCharm 或其他 IDE 的调试功能,逐步执行代码,检查每一步的输出,特别是数据加载和处理部分。
    6. 检查 festurize 环境

      • 确保 festurize 环境中安装了所有必要的库和依赖,特别是 TensorFlow。
    7. 查看 festurize 日志

      • 检查 festurize 的日志输出,查找可能的错误信息或警告。
    8. 检查数据集分割问题

      • 确保训练集和测试集的分割逻辑正确,避免数据集为空。可以通过打印 x_train_x_test_ 来验证。
    9. 检查图像处理逻辑

      • 确保图像处理和转换逻辑正确,特别是在 transforms.Compose 中的转换。
    10. 检查数据集标签

      • 确保 all_labels 正确生成,可以通过打印 all_labels 来验证。

    以下是一些代码示例,帮助你进行调试:

    # 打印所有图片路径
    print("All image paths:")
    print(all_imgs_path)
    
    # 打印训练集和测试集的第一条数据
    print("First item in train set:")
    print(x_train[0])
    print("First item in test set:")
    print(x_test[0])
    
    # 打印标签列表
    print("All labels:")
    print(all_labels)
    
    # 打印训练集和测试集的长度
    print("Length of train set:", len(x_train))
    print("Length of test set:", len(x_test))
    

    通过这些步骤和代码示例,你可以逐步定位并解决在 festurize 中运行时遇到的问题。希望这些建议能帮助你解决问题!

    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 7月19日

悬赏问题

  • ¥15 35114 SVAC视频验签的问题
  • ¥15 impedancepy
  • ¥15 在虚拟机环境下完成以下,要求截图!
  • ¥15 求往届大挑得奖作品(ppt…)
  • ¥15 如何在vue.config.js中读取到public文件夹下window.APP_CONFIG.API_BASE_URL的值
  • ¥50 浦育平台scratch图形化编程
  • ¥20 求这个的原理图 只要原理图
  • ¥15 vue2项目中,如何配置环境,可以在打完包之后修改请求的服务器地址
  • ¥20 微信的店铺小程序如何修改背景图
  • ¥15 UE5.1局部变量对蓝图不可见