Python np可能存在问题。沿_轴应用_?
我正在处理时尚NMIST数据,并尝试使用np.apply_沿_轴。我想这是我的问题。我用一个玩具数据集(6-(1,2)个训练点和2-(2,2)个测试点)以及一个100点的时装Mnist数据子集(1个测试点)进行了测试,它似乎起了作用。所以,当我尝试使用超过2个数据点时,它不起作用。我已经在下面发布了我的代码和错误。如果有人能给我指点,我将不胜感激。我删除了错误代码中矩阵的内部部分,以缩短这篇文章的篇幅,以防有人怀疑,只留下第一行和最后几行 谢谢, 奥贝罗伊Python np可能存在问题。沿_轴应用_?,python,arrays,numpy,Python,Arrays,Numpy,我正在处理时尚NMIST数据,并尝试使用np.apply_沿_轴。我想这是我的问题。我用一个玩具数据集(6-(1,2)个训练点和2-(2,2)个测试点)以及一个100点的时装Mnist数据子集(1个测试点)进行了测试,它似乎起了作用。所以,当我尝试使用超过2个数据点时,它不起作用。我已经在下面发布了我的代码和错误。如果有人能给我指点,我将不胜感激。我删除了错误代码中矩阵的内部部分,以缩短这篇文章的篇幅,以防有人怀疑,只留下第一行和最后几行 谢谢, 奥贝罗伊 import tensorflow a
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.
将tensorflow导入为tf
从tensorflow进口keras
作为pd进口熊猫
将numpy作为np导入
将matplotlib.pyplot作为plt导入
从scipy导入io
从scipy.spatial导入距离
fashion\u mnist=keras.datasets.fashion\u mnist
从sklearn.metrics导入准确性\u分数
从sklearn.metrics导入分类报告
从sklearn.metrics导入混淆矩阵
从sklearn.neights导入近邻
(序列图像,序列标签),(测试图像,测试标签)=时尚列表加载数据()
X1=序列图像。展平()。重塑((60000784))
x1=测试图像。展平()。重塑((10000784))
#要与之合作的子集时尚MNIST
X=X1[0:100,:]
Y=列车标签[0:100]
x=x1[0:3,:]
y=测试标签[0:3]
def CLC(目标):
质心=[]
#通过标签查找k个最近邻
对于列表中的i(标签):
X_i=X[Y==i]
#打印(X_i)
Y_i=Y[Y==i]
nbrs_i=最近的邻居(n_邻居=1).fit(X_i)
距离,指数=nbrs_i.kneighbors(目标重塑(1,-1))
#最近邻的子集数据
xss=X_i[指数:]
yss=Y_i[指数]
#k个最近邻的质心
#打印(xss)
#印刷品(yss)
质心=np.平均值(xss,轴=1)
打印(质心)
质心。附加(质心)
#质心
#找到最近的局部质心
质心=np.挤压(质心)
clf=最近的质心()
clf.配合(质心、标签)
回报(clf.预测(目标))
y_pred=np。沿_轴应用_(CLC,轴=1,arr=x)
#acc=总和(y_pred==y)/len(y_pred)
#行政协调会
错误输出:
[[ 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回溯(最近一次调用上次)
在里面
26回报(clf.预测(目标))
27
--->28 y_pred=np。沿_轴应用(CLC,轴=1,arr=x)
29#acc=总和(y#u pred==y)/len(y#u pred)
30#acc
沿_轴应用_(*args,**kwargs)
沿轴应用中的~/opt/anaconda3/lib/python3.7/site-packages/numpy/lib/shape\u base.py(func1d、axis、arr、*args、**kwargs)
377除停止迭代外:
378 raise VALUERROR('当任何迭代维度为0'时,无法沿_轴应用_')
-->379 res=asanyarray(func1d(inar_视图[ind0],*args,**kwargs))
380
381#构建一个缓冲区,用于存储func1d的计算结果。
中英文对照(目标)
24 clf=最近的质心()
25 clf.配合(质心、标签)
--->26回报(clf.预测(目标))
27
28 y_pred=np。沿_轴应用(CLC,轴=1,arr=x)
预测中的~/opt/anaconda3/lib/python3.7/site-packages/sklearn/neights/nearest_centroid.py(self,X)
190检查是否已安装(自“质心”)
191
-->192 X=检查数组(X,接受
193返回自类〔成对距离〕(
194 X,自质心(公制=自公制).argmin(轴=1)]
检查数组中的~/opt/anaconda3/lib/python3.7/site-packages/sklearn/utils/validation.py(数组、接受稀疏、接受大稀疏、数据类型、顺序、复制、强制所有有限、确保2d、允许nd、确保最小样本、确保最小特征、警告数据类型、估算器)
519“使用数组重塑数据。如果需要重塑(-1,1)
520“您的数据只有一个特征或数组。重塑(1,-1)”
-->521“如果它包含单个样本。”。格式(数组))
522
523#在未来,灵活的数据类型将像对象数据类型一样处理
ValueError:应为2D数组,而应为1D数组:
数组=[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 0 0].
使用数组重塑数据。如果数据具有单个特征或数组,则重塑(-1,1)。如果数据包含单个样本,则重塑(1,-1)。
为什么要使用此应用…
?函数是否需要1d数组?这个错误意味着它不是。不要试图使用你不理解的函数。它不能提高性能。它应该是一个数组。我之所以使用该函数,是因为我有10000个数据点,我想对操作进行矢量化。通过选择轴,它将按行拉取数据。我已经对它进行了重塑,以确保它将是一个行向量。你对如何使它发挥作用有什么建议吗?或者你知道我可以矢量化操作的另一种方法吗?np.沿轴应用不会“矢量化”。首先,请确保CLC
与x
的行或列一起工作。