关于平均值,我写了这个代码,但错误是(形状(2,1),(3,)不匹配),那么我该怎么办


# GRADED FUNCTION: DO NOT EDIT THIS LINE
def mean_naive(X):
"Compute the mean for a dataset X nby iterating over the data points"
# X is of size (D,N) where D is the dimensionality and N the number of data points
D, N = X.shape
mean = np.zeros((D,1))
### Edit the code; iterate over the dataset and compute the mean vector.
# Update the mean vector
for n in range(N):
# Update the mean vector
for i in range(D):
mean[i] += X[i][n]
mean /= N
mean = (np.sum(X,axis=1)/N).reshape(D,1)

return mean

当我在Python 3.9.12版本上运行您的代码时,我不会收到错误。

下面的代码输出与您的代码相同的东西:

def mean_naive(X):

# Create an empty list to hold the mean vector - i'm calling it mean
# For each row in X, find the mean of that row
# Append to the empty list created at the beginning
# Reshape mean to be in the shape of a vector

mean = []

for row in X:
mean.append(np.sum(row)/len(row))

return np.reshape(mean,(len(mean),1))

下面的代码和上面的代码是一样的,

def mean_naive(X):

# Except this time, we don't need to create an empty list
# Mean values are automatically appended

mean = [np.sum(row)/len(row) for row in X]
return np.reshape(mean,(len(mean),1))

最新更新