AttributeError:模块“ tensorflow.python.ops.nn”没有属性“ softmax_cross_entropy_with_logits_v2”

时间:2019-07-13 10:56:49

标签: python-3.x

我正在尝试在tenserflow上运行一个简单的神经网络代码。但是,出现以下错误,我不知道问题出在哪里。我用谷歌搜索,找不到解决方案。

我在macOS Mojave 10.14.5上使用tenserflow versiob 1.4.0

任何帮助将不胜感激。

干杯, 阿亚拉

import tensorflow as tf
import numpy as np

# A neural network example
from tensorflow.python.keras.datasets import mnist 

(x_train, y_train), (x_test, y_test) = mnist.load_data(path='mnist.npz')
print(x_train.shape)
print(y_train.shape)
print(x_test.shape)
print(y_test.shape)

# extract the training data in batches of samples
def get_batch(x_data, y_data, batch_size):
    idxs=np.random.randint(0, len(y_data), batch_size)
    return x_data[:, :, idxs], y_data[idxs]

# python optimisation variables
learning_rate=0.5
epochs=10
batch_size=100

# declare the training data placeholders
x=tf.placeholder(tf.float32, [None, 28, 28])
# reshape input x - for 28 x 28 pixels = 784
x_rs=tf.reshape(x, [-1, 784])
# scale the input data (maximum is 255.0, minimum is 0.0)
x_sc=tf.div(x_rs, 255.0)
# now declare the output data placeholder - 10 digits
y=tf.placeholder(tf.int64, [None, 1])
# convert the y data to one hot values
y_one_hot=tf.reshape(tf.one_hot(y, 10), [-1, 10])

# now declare the weights connecting the input to the hidden layer
W1=tf.Variable(tf.random_normal([784, 300], stddev=0.03), name='W1')
b1=tf.Variable(tf.random_normal([300]), name='b1')
# and the weights connecting the hidden layer to the output layer
W2=tf.Variable(tf.random_normal([300, 10], stddev=0.03), name='W2')
b2=tf.Variable(tf.random_normal([10]), name='b2')

# calculate the output of the hidden layer
hidden_out = tf.add(tf.matmul(x_sc, W1), b1)
hidden_out = tf.nn.relu(hidden_out)

# now calculate the hidden layer output - no activation applied
logits = tf.add(tf.matmul(hidden_out, W2), b2)

# now let's define the cost function which we are going to train the model on
cross_entropy=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_one_hot,
                                                        logits=logits))
# add an optimiser
optimizer=tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cross_entropy)

# finally setup the initialisation operator
init_op = tf.global_variables_initializer()

# define an accuracy assessment operation
correct_prediction = tf.equal(tf.argmax(y_one_hot, 1), tf.argmax(logits, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# start the session
with tf.Session() as sess:
    # initialise the variables
    sess.run(init_op)
    total_batch = int(len(y_train) / batch_size)
    for epoch in range(epochs):
        avg_cost = 0
        for i in range(total_batch):
            batch_x, batch_y = get_batch(x_train, y_train, batch_size=batch_size)
            _, c = sess.run([optimizer, cross_entropy], feed_dict={x: batch_x, y:
                                                                   batch_y.reshape(-1, 1)})
            avg_cost += c / total_batch
        acc = sess.run(accuracy, feed_dict={x: x_test, y: y_test.reshape(-1, 1)}) 
        print("Epoch: {}, cost={:.3f}, test set accuracy={:.3f}%".format(epoch + 1, 
                                                                         avg_cost, acc*100))                                                                                                                                      
    print("\nTraining complete!")

这是我得到的错误

-------------------------------------------------------------------------
AttributeError                          Traceback (most recent call last)
<ipython-input-20-ea13f6382360> in <module>
     44 
     45 # now let's define the cost function which we are going to train the model on
---> 46 cross_entropy=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_one_hot,
     47                                                         logits=logits))
     48 # add an optimiser

AttributeError: module 'tensorflow.python.ops.nn' has no attribute 'softmax_cross_entropy_with_logits_v2'

通过Google搜索错误。

0 个答案:

没有答案