You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用函数返回值时遇ValueError:期望2D数组却得到1D数组

解决数组维度不匹配问题的方案

错误原因分析

错误提示明确说明:期望输入2D数组,实际传入的是1D的图片路径数组。这说明两个核心问题:

  1. feature_list变量存储的是图片路径列表,而非模型需要的2D特征数组(每行对应一张图片的特征向量);
  2. 单张图片提取的features是1D向量,不符合kneighbors方法对输入样本维度的要求。

具体修复步骤

1. 修正feature_list为2D特征数组

如果你的feature_list目前是图片路径列表,需要先批量提取所有图片的特征,转换为2D numpy数组:

import numpy as np

# 假设image_paths是你的图片路径列表
feature_list = []
for img_path in image_paths:
    # 调用你的特征提取函数
    img_feature = feature_extraction(img_path, model)
    feature_list.append(img_feature)
# 转换为2D numpy数组
feature_list = np.array(feature_list)

2. 调整单张图片特征的维度

在recommend函数中,将单张图片的1D特征向量转换为2D数组(形状为(1, 特征数)),替换原有的[features]写法:

def recommend(features, feature_list):
    neighbors = NearestNeighbors(n_neighbors=6, algorithm="brute", metric="euclidean")
    neighbors.fit(feature_list)

    # 将1D特征reshape为2D数组,适配kneighbors要求
    indices = neighbors.kneighbors(features.reshape(1, -1))

    return indices

额外验证

确保feature_extraction函数返回的是1D numpy数组(单张图片的特征向量),而非其他格式。如果返回的是列表,也可以用np.array(features).reshape(1, -1)做转换。

内容的提问来源于stack exchange,提问作者kayam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 12:33:18