如何在Google Colab中无换行打印MNIST图像的二维数组
解决Colab中打印MNIST二维数组换行问题
方法一:调整NumPy打印参数
Colab里NumPy默认的打印行宽限制会导致28x28数组每行自动换行,你可以通过修改np.set_printoptions()的linewidth参数,让一行能容纳整行的数字:
from sklearn.datasets import fetch_openml import numpy as np mnist = fetch_openml("mnist_784", parser="pandas") img_array = mnist['data'].iloc[0].values.reshape(28, 28) # 设置足够大的行宽,避免每行换行 np.set_printoptions(linewidth=1000) print(img_array)
方法二:直接用Matplotlib显示图像(更推荐)
打印数字数组本身可读性差,不如直接用Matplotlib绘制图像,既不会有换行问题,还能直观看到手写数字:
from sklearn.datasets import fetch_openml import numpy as np import matplotlib.pyplot as plt mnist = fetch_openml("mnist_784", parser="pandas") img_array = mnist['data'].iloc[0].values.reshape(28, 28) plt.imshow(img_array, cmap='gray') plt.axis('off') # 隐藏坐标轴 plt.show()
内容的提问来源于stack exchange,提问作者Phạm Huy Cường Thịnh
相关产品推荐
相关产品推荐

