[Python] Problem possibly with np.apply_along_axis?

Discussão em 'Python' iniciado por Stack, Agosto 14, 2025.

  1. Stack

    Stack Membro Participativo

    I am working with the Fashion MNIST data and I am trying to use np.apply_along_axis. I think this is were my issue is. I have tried it with a toy data set of 6-(1,2) points for training and 2-(,2) test points and a 100 point subset of fashion MNIST data with 1 test point and it appears to work. So when I tried it with the more than 2 data points it does not work. I have posted my code and the error below. If anyone could give me any pointers I would greatly appreciate it. I deleted the inside part of the matrices in the error code to make this post shorter, in case anyone is wondering, just left the first and last few lines.

    import tensorflow as tf
    from tensorflow import keras

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    from scipy import io

    from scipy.spatial import distance

    fashion_mnist = keras.datasets.fashion_mnist

    from sklearn.metrics import accuracy_score
    from sklearn.metrics import classification_report
    from sklearn.metrics import confusion_matrix

    from sklearn.neighbors import NearestNeighbors

    (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

    X1=train_images.flatten().reshape((60000,784))
    x1=test_images.flatten().reshape((10000,784))

    # Subsetting fashion MNIST to work with

    X=X1[0:100,:]
    Y=train_labels[0:100]
    x=x1[0:3,:]
    y=test_labels[0:3]

    def CLC(target):
    centroids=[]
    # Find k nearest neighbors by label
    for i in list(labels):
    X_i = X[Y==i]
    # print(X_i)
    Y_i = Y[Y==i]
    nbrs_i = NearestNeighbors(n_neighbors=1).fit(X_i)
    distances, indices = nbrs_i.kneighbors(target.reshape(1,-1))

    # Subsetting data for nearest neighbors
    xss=X_i[indices,:]
    yss=Y_i[indices]
    # Centroid of k nearest neighbors by label
    # print(xss)
    # print(yss)
    centroid = np.mean(xss, axis=1)
    print(centroid)
    centroids.append(centroid)
    #centroids
    # find closest local centroid
    centroids=np.squeeze(centroids)
    clf = NearestCentroid()
    clf.fit(centroids, labels)
    return(clf.predict(target))

    y_pred=np.apply_along_axis(CLC, axis=1, arr=x)
    #acc=sum(y_pred==y)/len(y_pred)
    #acc


    Error Output:

    [[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 122. 101. 73. 59.
    39. 108. 89. 91. 83. 0. 0. 0. 0. 0. 0. 0. 0. 0.
    0. 0. 0. 0. 0. 0. 0. 0. 0. 3. 215. 232. 236. 223.


    0. 0. 0. 61. 81. 91. 56. 12. 99. 75. 78. 75. 99. 70.
    61. 70. 77. 77. 61. 58. 89. 7. 55. 188. 97. 78. 0. 0.
    0. 0. 0. 9. 28. 23. 4. 0. 0. 0. 0. 0. 0. 0.
    0. 0. 0. 0. 0. 0. 0. 0. 1. 66. 33. 11. 0. 0.]]
    ---------------------------------------------------------------------------
    ValueError Traceback (most recent call last)
    <ipython-input-569-bda921e18e4e> in <module>
    26 return(clf.predict(target))
    27
    ---> 28 y_pred=np.apply_along_axis(CLC, axis=1, arr=x)
    29 #acc=sum(y_pred==y)/len(y_pred)
    30 #acc

    <__array_function__ internals> in apply_along_axis(*args, **kwargs)

    ~/opt/anaconda3/lib/python3.7/site-packages/numpy/lib/shape_base.py in apply_along_axis(func1d, axis, arr, *args, **kwargs)
    377 except StopIteration:
    378 raise ValueError('Cannot apply_along_axis when any iteration dimensions are 0')
    --> 379 res = asanyarray(func1d(inarr_view[ind0], *args, **kwargs))
    380
    381 # build a buffer for storing evaluations of func1d.

    <ipython-input-569-bda921e18e4e> in CLC(target)
    24 clf = NearestCentroid()
    25 clf.fit(centroids, labels)
    ---> 26 return(clf.predict(target))
    27
    28 y_pred=np.apply_along_axis(CLC, axis=1, arr=x)

    ~/opt/anaconda3/lib/python3.7/site-packages/sklearn/neighbors/nearest_centroid.py in predict(self, X)
    190 check_is_fitted(self, 'centroids_')
    191
    --> 192 X = check_array(X, accept_sparse='csr')
    193 return self.classes_[pairwise_distances(
    194 X, self.centroids_, metric=self.metric).argmin(axis=1)]

    ~/opt/anaconda3/lib/python3.7/site-packages/sklearn/utils/validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
    519 "Reshape your data either using array.reshape(-1, 1) if "
    520 "your data has a single feature or array.reshape(1, -1) "
    --> 521 "if it contains a single sample.".format(array))
    522
    523 # in the future np.flexible dtypes will be handled like object dtypes

    ValueError: Expected 2D array, got 1D array instead:
    array=[ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0].
    Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

    Continue reading...

Compartilhe esta Página