1. 程式人生 > >TensorFlow報錯的解決方案(持續更新)

TensorFlow報錯的解決方案(持續更新)

錯誤一

ValueError: Initializer for variable rnn/basic_rnn_cell/kernel/ is from inside a control-flow construct, such as a loop or conditional. When creating a variable inside a loop or conditional, use a lambda as the initializer.

X = np.random.randn(2, 2, 1)

# 第二個example長度為1
X[1,1:] = 0
X_lengths = [2
, 1] cell = tf.nn.rnn_cell.BasicRNNCell(num_units=64) Y = tf.placeholder(tf.int32, [2,2,1]) outputs, last_states = tf.nn.dynamic_rnn(cell=cell, dtype=tf.float64, sequence_length=X_lengths, inputs=Y) output = tf.reshape(outputs, [-1, 2]) result = tf.contrib.learn.run_n({"outputs": outputs, "last_states"
: last_states}, n=1, feed_dict={Y:X}) print(result[0])

Y = tf.placeholder(tf.int32, [2,2,1])行的型別需要跟tf.nn.dynamic_rnn中的型別統一,將int32改成float64,執行成功。
此外,tf.nn.dynamic_rnn函式似乎只允許float型別,將兩個型別統一成int32,仍然報這個錯(I don’t know why now)。

總結:

1)兩者型別需要保持一致
2)只支援float型別,float32、float64都可以

錯誤二

ValueError: setting an array element with a sequence.

from sklearn.decomposition import PCA
import numpy as np

x = np.array([[1.],  [0.9,  0.95],  [1.01,  1.03],  [2.,  2.],  [2.03,  2.06],  [1.98,  1.89],
       [3., 3.],  [3.03,  3.05],  [2.89,  3.1],  [4.,  4.],  [4.06,  4.02],  [3.97,  4.01]])
pca=PCA(n_components=1, copy=False)
print(pca.fit_transform(x))
print(x)

一般這種錯誤是array中陣列長度不統一,如第一個陣列[1.]維度出錯,與其它陣列維度不一致。

錯誤三

error destroying CUDA event in context 000001EAA2598510: CUDA_ERROR_LAUNCH_FAILED

 labels = tf.one_hot(tf.reshape(output_data, [-1]), depth=vocab_size + 1)
 loss = tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits)

程式碼在這個位置報錯,設定它們在cpu下執行即可解決。

  with tf.device('/cpu:0'):
       labels = tf.one_hot(tf.reshape(output_data, [-1]), depth=vocab_size + 1)
       loss = tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits)

錯誤四

ValueError: Shape (?, 1) must have rank at least 3

報錯行的tensor要求輸入3維的引數,但是shape(?,1)是兩維的。改成正確的資料格式即可。

錯誤五

當編寫Python指令碼時,中文註釋或者輸出時,會提示錯誤:SyntaxError:Non-ASCII character ‘\xe5’ in file

在Python原始檔的開始行加上:

# coding:UTF-8
或者
# -*- coding:UTF-8 -*-