Python 图像聚类分析:修复 'ValueError: Number of rows must be a positive integer, not 2.0' 错误
Python 图像聚类分析:修复 'ValueError: Number of rows must be a positive integer, not 2.0' 错误
在使用 Python 进行图像聚类分析时,我们可能会遇到以下错误:
ValueError: Number of rows must be a positive integer, not 2.0
这个错误通常发生在使用 matplotlib 库绘制子图时,当我们计算子图网格的行数时,得到的结果是浮点数。例如,在以下代码中,当 n 不为 25 的倍数时,n_rows 会是浮点数:
def plot_ds(digits, title, labels):
n=digits.shape[0]
n_rows=n/25+1 # 这行代码会导致错误
n_cols=25
plt.figure(figsize=(n_cols * 0.9, n_rows * 1.3))
plt.subplots_adjust(wspace=0, hspace=0)
plt.suptitle(title)
for i in range(n):
plt.subplot(n_rows, n_cols, i + 1)
plot_d(digits[i,:], '%d' % labels[i])
为了修复这个问题,我们需要将 n_rows 转换为整数。可以使用 int() 函数实现:
def plot_ds(digits, title, labels):
n=digits.shape[0]
n_rows=int(n/25)+1 # 将 n_rows 转换为整数
n_cols=25
plt.figure(figsize=(n_cols * 0.9, n_rows * 1.3))
plt.subplots_adjust(wspace=0, hspace=0)
plt.suptitle(title)
for i in range(n):
plt.subplot(n_rows, n_cols, i + 1)
plot_d(digits[i,:], '%d' % labels[i])
现在,n_rows 将始终是一个正整数,从而避免 ValueError 错误。
示例代码
import matplotlib.pyplot as plt
import numpy as np
def plot_d(digit, label):
plt.axis('off')
plt.imshow(digit.reshape((28, 28)), cmap=plt.cm.gray)
plt.title(label)
def plot_ds(digits, title, labels):
n=digits.shape[0]
n_rows=int(n/25)+1
n_cols=25
plt.figure(figsize=(n_cols * 0.9, n_rows * 1.3))
plt.subplots_adjust(wspace=0, hspace=0)
plt.suptitle(title)
for i in range(n):
plt.subplot(n_rows, n_cols, i + 1)
plot_d(digits[i,:], '%d' % labels[i])
def plot_clusters(y_predict, y, stats, n_clusters):
#for i in range(n_clusters):
for i in range(2):
indices = np.where(y_predict == i)
title = 'Most freq item %d, cluster size %d, majority %d ' % (stats[i,2], stats[i,1], stats[i,0])
#打印该簇前25个图像
plot_ds(X_selected[indices][:25], title, y[indices])
print('Plotting the first 2 clusters')
plot_clusters(y_pred_kmeans, y_selected, stats, MAX_K)
通过以上修改,我们可以成功修复 ValueError: Number of rows must be a positive integer, not 2.0 错误,并在图像聚类分析中正常绘制子图。
原文地址: https://www.cveoy.top/t/topic/oqqG 著作权归作者所有。请勿转载和采集!