我的项目正在开发 google colab,但未开发 pycharm

My project is working on google colab but not working on pycharm

我的项目是一个手写数字分析器。它正在 Google Colab 上工作,但在 Pycharm 上显示错误。使其在 colab 中工作的语句是“%matplotlib inline”,此行在 pycharm.

中显示错误
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
import numpy as np
import matplotlib.pyplot as plt

%matplotlib inline

mnist = fetch_openml("mnist_784")

plt.figure(figsize=(20, 4))
    for index, (image, label) in enumerate(zip(mnist.data[:5], mnist.target[:5])):
    plt.subplot(1, 5, index + 1)
    plt.imshow(np.reshape(image, (28, 28)), cmap="gray")
    plt.title("Number: %s" % label)
X_train, X_test, y_train, y_test = train_test_split(mnist.data, mnist.target, test_size=0.2)
mdl = LogisticRegression(solver="lbfgs")
mdl.fit(X_train, y_train)
predictions = mdl.predict(X_test)
score = mdl.score(X_test, y_test)

index = 0
plt.imshow(np.reshape(X_test[index], (28, 28)))
print("Prediction: " + mdl.predict([X_test[index]])[0])

cm = metrics.confusion_matrix(y_test, predictions)
plt.figure(figsize=(9, 9))
plt.imshow(cm, cmap='Pastell')
plt.title('Confusion Matrix for MNIST Data')

plt.xticks(np.arange(10))
plt.yticks(np.arange(10))

plt.ylabel('Actual Label')
plt.xlabel('Predicted Label')

plt.colorbar()

width, height = cm.shape
for x in range(width):
    for y in range(height):
        plt.annotate(str(cm[x][y]), xy=(y, x), horizontalalignment='center', 
verticalalignment='center')

回溯(最后一次调用): 文件“C:\Users\Asus\PycharmProjects\pythonProject\Handwriting_Digit_Recognition\digit.py”,第 15 行,位于 plt.imshow(np.reshape(图片, (18, 18)), cmap="灰色") 文件“<array_function internals>”,第 5 行,重塑 文件“C:\Users\Asus\PycharmProjects\pythonProject\venv\lib\site-packages\numpy\core\fromnumeric.py”,第 299 行,重塑 return _wrapfunc(a, 'reshape', newshape, order=order) 文件“C:\Users\Asus\PycharmProjects\pythonProject\venv\lib\site-packages\numpy\core\fromnumeric.py”,第 55 行,在 _wrapfunc 中 return_wrapit(obj, 方法, *args, **kwds) _wrapit 中的文件“C:\Users\Asus\PycharmProjects\pythonProject\venv\lib\site-packages\numpy\core\fromnumeric.py”,第 44 行 结果 = getattr(asarray(obj), 方法)(*args, **kwds) ValueError:无法将大小为 1 的数组重塑为形状 (18,18)

%matplotlib inline 是给 Jupyter notebook 的消息,用于将图像渲染到 notebook 本身。如果您使用 Pycharm.

中的代码,则需要删除该行

在第 13 行的 for 循环之后,尝试缩进所有代码,直到 X_train, X_test, y_train, y_test = train_test_split(mnist.data, mnist.target, test_size=0.2) 行(但不要缩进该行)。该错误与 %matplotlib inline 无关,但我认为这是解决方案。如果有效,请尽快告诉我。不过,这是假设您的其余代码有效! 不要忘记 Python 与其他语言不同取决于缩进 !

是Pycharm使用GPU时冲突引起的问题。解决方法是在使用tensorflow时添加代码:

import tensorflow as tf
config = tf.compat.v1.ConfigProto()
config.gpu_options.allocator_type = 'BFC' #A "Best-fit with coalescing" algorithm, simplified from a version of dlmalloc.
config.gpu_options.per_process_gpu_memory_fraction = 0.3
config.gpu_options.allow_growth = True
tf.compat.v1.keras.backend.set_session(tf.compat.v1.Session(config=config))