Msy20070905 2024-07-16 23:44 采纳率: 21.2%
浏览 13

setting an array element with a sequence.


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 = ['none', 'paper', 'rock', 'scissors']
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_imgs_path[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)
 
# 将数据加载器转换为NumPy数组
x_train_np = np.array([x for x, _ in x_train])
y_train_np = np.array([y for _, y in x_train])
x_test_np = np.array([x for x, _ in x_test])
y_test_np = np.array([y for _, y in x_test])
 
# 调整数据形状
x_train_np = x_train_np.reshape(-1, 224, 224, 3)
x_test_np = x_test_np.reshape(-1, 224, 224, 3)
 
# 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(x_train_np, y_train_np, batch_size=32, epochs=10, validation_data=(x_test_np, y_test_np), 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()

报一下错误,该怎么解决啊

FutureWarning: The input object of type 'Tensor' is an array-like implementing one of the corresponding protocols (`__array__`, `__array_interface__` or `__array_struct__`); but not a sequence (or 0-D). In the future, this object will be coerced as if it was first converted using `np.array(obj)`. To retain the old behaviour, you have to either modify the type 'Tensor', or assign to an empty array created with `np.empty(correct_shape, dtype=object)`.
  x_train_np = np.array([x for x, _ in x_train])
Traceback (most recent call last):
 line 101, in <module>
    x_train_np = np.array([x for x, _ in x_train])
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (400,) + inhomogeneous part.
  • 写回答

4条回答 默认 最新

  • 阿里嘎多学长 2024-07-16 23:44
    关注

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


    在您提供的代码中,错误提示表明您尝试将一个序列赋值给NumPy数组的元素,但是序列的形状是不均匀的,这导致了ValueError。这个问题通常发生在尝试将具有不同长度或形状的序列赋值给一个期望均匀形状的数组时。

    错误发生在以下代码段:

    x_train_np = np.array([x for x, _ in x_train])
    

    这里的问题可能是x_train中的元素(即图像张量)具有不同的形状,而NumPy数组要求所有元素的形状必须一致。

    解决方法:

    1. 确保所有元素具有相同的形状:在使用np.array()之前,确保所有元素都具有相同的形状。如果它们是图像张量,您可能需要对它们进行预处理以确保它们具有相同的尺寸。

    2. 使用np.array的正确方式:如果x_train中的元素已经是NumPy数组或可以转换为NumPy数组,您应该直接将它们转换为数组,而不是使用列表推导式。

    3. 检查MyDatasetpro类中的__getitem__方法:确保这个方法返回的是具有统一形状的张量。

    4. 使用tf.data.Dataset:在TensorFlow中,推荐使用tf.data.Dataset来处理数据,因为它可以更有效地处理张量数据集。

    代码示例:

    # 假设x_train是一个包含图像张量的data.Dataset对象
    # 我们首先需要确保所有图像张量具有相同的形状
    
    # 定义一个函数来标准化图像张量的形状
    def standardize_image_shape(image_tensor):
        # 这里添加代码来调整图像张量的形状,例如使用tf.image.resize等
        return image_tensor
    
    # 标准化x_train中的所有图像张量
    x_train_standardized = x_train.map(standardize_image_shape)
    
    # 将标准化后的图像张量转换为NumPy数组
    x_train_np = np.array([x.numpy() for x, _ in x_train_standardized])
    

    请注意,这里的standardize_image_shape函数需要您根据实际情况来实现,以确保所有图像张量具有相同的形状。

    TensorFlow中的序列赋值:

    在TensorFlow中,通常不需要手动设置数组元素为序列,因为TensorFlow的张量操作会自动处理这些情况。但是,如果您需要在NumPy数组中进行这样的操作,您应该确保所有序列具有相同的形状,或者使用np.arraydtype=object参数来存储不同的对象。

    希望这些信息能帮助您解决问题。如果您需要更具体的帮助,请提供更多的上下文信息。

    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 7月16日

悬赏问题

  • ¥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局部变量对蓝图不可见