【问题标题】:ImportError: Failed to import any qt binding, Python - TensorflowImportError:无法导入任何 qt 绑定,Python - Tensorflow
【发布时间】:2019-02-20 02:38:23
【问题描述】:

我正在使用 Tensorflow 开始我的冒险。我想我已经正确安装了所有东西,但是在运行这段代码时,PyCharm 会返回错误:

Traceback (most recent call last):
  File "C:/Users/tymot/Desktop/myenv3/env/Tensorflow/all_good.py", line 15, in <module>
    import matplotlib.pyplot as plt
  File "C:\Users\tymot\Anaconda1\lib\site-packages\matplotlib\pyplot.py", line 115, in <module>
    _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
  File "C:\Users\tymot\Anaconda1\lib\site-packages\matplotlib\backends\__init__.py", line 62, in pylab_setup
    [backend_name], 0)
  File "C:\Users\tymot\Anaconda1\lib\site-packages\matplotlib\backends\backend_qt5agg.py", line 15, in <module>
    from .backend_qt5 import (
  File "C:\Users\tymot\Anaconda1\lib\site-packages\matplotlib\backends\backend_qt5.py", line 19, in <module>
    import matplotlib.backends.qt_editor.figureoptions as figureoptions
  File "C:\Users\tymot\Anaconda1\lib\site-packages\matplotlib\backends\qt_editor\figureoptions.py", line 20, in <module>
    import matplotlib.backends.qt_editor.formlayout as formlayout
  File "C:\Users\tymot\Anaconda1\lib\site-packages\matplotlib\backends\qt_editor\formlayout.py", line 54, in <module>
    from matplotlib.backends.qt_compat import QtGui, QtWidgets, QtCore
  File "C:\Users\tymot\Anaconda1\lib\site-packages\matplotlib\backends\qt_compat.py", line 158, in <module>
    raise ImportError("Failed to import any qt binding")
ImportError: Failed to import any qt binding

我正在尝试运行的代码:

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

num_features = 2
num_iter = 10000
display_step = int(num_iter / 10)
learning_rate = 0.01

num_input = 2          # units in the input layer 28x28 images
num_hidden1 = 2        # units in the first hidden layer
num_output = 1         # units in the output, only one output 0 or 1

#%% mlp function

def multi_layer_perceptron_xor(x, weights, biases):

    hidden_layer1 = tf.add(tf.matmul(x, weights['w_h1']), biases['b_h1'])
    hidden_layer1 = tf.nn.sigmoid(hidden_layer1)

    out_layer = tf.add(tf.matmul(hidden_layer1, weights['w_out']), biases['b_out'])

    return out_layer

#%%
x = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], np.float32)  # 4x2, input
y = np.array([0, 1, 1, 0], np.float32)                      # 4, correct output, AND operation
y = np.reshape(y, [4,1])                                    # convert to 4x1

# trainum_inputg data and labels
X = tf.placeholder('float', [None, num_input])     # training data
Y = tf.placeholder('float', [None, num_output])    # labels

# weights and biases
weights = {
    'w_h1' : tf.Variable(tf.random_normal([num_input, num_hidden1])), # w1, from input layer to hidden layer 1
    'w_out': tf.Variable(tf.random_normal([num_hidden1, num_output])) # w2, from hidden layer 1 to output layer
}
biases = {
    'b_h1' : tf.Variable(tf.zeros([num_hidden1])),
    'b_out': tf.Variable(tf.zeros([num_output]))
}

model = multi_layer_perceptron_xor(X, weights, biases)

'''
- cost function and optimization
- sigmoid cross entropy -- single output
- softmax cross entropy -- multiple output, normalized
'''
loss_func = tf.reduce_sum(tf.nn.sigmoid_cross_entropy_with_logits(logits=model, labels=Y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(loss_func)

sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)

for k in range(num_iter):
    tmp_cost, _ = sess.run([loss_func, optimizer], feed_dict={X: x, Y: y})
    if k % display_step == 0:
        #print('output: ', sess.run(model, feed_dict={X:x}))
        print('loss= ' + "{:.5f}".format(tmp_cost))

# separates the input space
W = np.squeeze(sess.run(weights['w_h1']))   # 2x2
b = np.squeeze(sess.run(biases['b_h1']))    # 2,

sess.close()

#%%
# Now plot the fitted line. We need only two points to plot the line
plot_x = np.array([np.min(x[:, 0] - 0.2), np.max(x[:, 1]+0.2)])
plot_y =  -1 / W[1, 0] * (W[0, 0] * plot_x + b[0])
plot_y = np.reshape(plot_y, [2, -1])
plot_y = np.squeeze(plot_y)

plot_y2 = -1 / W[1, 1] * (W[0, 1] * plot_x + b[1])
plot_y2 = np.reshape(plot_y2, [2, -1])
plot_y2 = np.squeeze(plot_y2)

plt.scatter(x[:, 0], x[:, 1], c=y, s=100, cmap='viridis')
plt.plot(plot_x, plot_y, color='k', linewidth=2)    # line 1
plt.plot(plot_x, plot_y2, color='k', linewidth=2)   # line 2
plt.xlim([-0.2, 1.2]); plt.ylim([-0.2, 1.25]);
#plt.text(0.425, 1.05, 'XOR', fontsize=14)
plt.xticks([0.0, 0.5, 1.0]); plt.yticks([0.0, 0.5, 1.0])
plt.show()

#%%

我认为它遵循另一个版本的 python。我怎样才能不出错地运行代码。 我安装了 qt-binding 并将 tensorflow 添加到我的 PyCharm。

任何帮助将不胜感激。

【问题讨论】:

  • matplotlib Github 网站上有一个 issue 可以解决您的错误。

标签: python tensorflow


【解决方案1】:

确保您已安装 PyQt5。您可以打开一个 python shell 并尝试:

import PyQt5

如果失败,您可以通过以下方式安装它:

pip install PyQt5

如果您使用的是 macOS 或 Linux,请注意您可能需要运行

pip3 install PyQt5

【讨论】:

  • Collecting PyQt5 Downloading https://files.pythonhosted.org/packages/3a/fb/eb51731f2dc7c22d8e1a63ba88fb702727b324c6352183a32f27f73b8116/PyQt5-5.14.1.tar.gz (3.2MB) |████████████████████████████████| 3.2MB 843kB/s Installing build dependencies ... done Getting requirements to build wheel ... done Preparing wheel metadata ... error ERROR: Command errored out with exit status 1:
  • 我无法在 conda 环境中使用 matplotlib。一旦我点击语句 plt.show(),python 就会退出,因为当我直接安装 python 时它可以完美运行
【解决方案2】:

它解决了我的问题。

pip uninstall matplotlib
python -m pip install --upgrade pip
pip install matplotlib

【讨论】:

    【解决方案3】:

    我在使用%matplotlib qt 时遇到了相同的ImportError。 按照 Foad 的回答解决了我的问题。

    我用的是 Archlinux 所以我试过了

    sudo pacman -S python-pyqt5 
    

    它成功了。

    【讨论】:

      【解决方案4】:

      在执行以下魔术命令后,我在 windows-VScode 上遇到了该错误:

      %matplotlib qt
      

      通过完成以下步骤解决了这个错误:

      • 卸载 Anaconda
      • 重新安装 Anaconda
      • 重启,打开 Anaconda,从那里启动 VScode。

      【讨论】:

        猜你喜欢
        • 2021-05-31
        • 2021-08-27
        • 2022-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-12
        • 2016-10-02
        • 2014-09-27
        相关资源
        最近更新 更多