Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么我的图形是一个疯狂的闪烁怪物?_Python_Macos_Matplotlib_Ipython_Spyder - Fatal编程技术网

Python 为什么我的图形是一个疯狂的闪烁怪物?

Python 为什么我的图形是一个疯狂的闪烁怪物?,python,macos,matplotlib,ipython,spyder,Python,Macos,Matplotlib,Ipython,Spyder,我试图创建一个图表,显示神经网络的小批量精度和验证精度之间的相关性。 但是,我有一个疯狂的图形,它以超高的频率闪烁,并且放大了图形的一小部分 这是我的密码: num_nodes=1024 batch_size = 128 beta = 0.01 def animate(i): graph_data = open('NeuralNetData.txt','r').read() lines = graph_data.split('\n') xs = [] ys =

我试图创建一个图表,显示神经网络的小批量精度和验证精度之间的相关性。 但是,我有一个疯狂的图形,它以超高的频率闪烁,并且放大了图形的一小部分

这是我的密码:

num_nodes=1024
batch_size = 128
beta = 0.01


def animate(i):
    graph_data = open('NeuralNetData.txt','r').read()
    lines = graph_data.split('\n')
    xs = []
    ys = []
    for line in lines:
        if len(line) > 1:
            x, y = line.split(',')
            xs.append(x)
            ys.append(y)
    ax1.clear()
    ax1.plot(xs, ys,label='validation accuracy')
    ax1.legend(loc='lower right')
    ax1.set_ylabel("Accuracy(%)", fontsize=15)
    ax1.set_xlabel("Images Seen", fontsize=15)
    ax1.set_title("Neural Network Accuracy Data\nStochastic Gradient Descent", fontsize=10)
    plt.show()

def animate2(i):
   graph_data = open('NeuralNetData2.txt','r').read()
   lines = graph_data.split('\n')
   xs = []
   ys = []
   for line in lines:
      if len(line) > 1:
          x, y = line.split(',')
          xs.append(x)
          ys.append(y)
   ax1.plot(xs, ys, label='mini-batch accuracy')
   ax1.legend(loc='lower right')
   plt.tight_layout()
   plt.show()

style.use('fivethirtyeight')

#Creating Graph
fig = plt.figure(figsize=(50,50))
ax1 = fig.add_subplot(1,1,1)

#1 hidden layer using RELUs and trying regularization techniques

with graph.as_default():

    # Input data. For the training data, we use a placeholder that will be fed
    # at run time with a training minibatch.
    tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size * image_size))
    tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))
    tf_valid_dataset = tf.constant(valid_dataset)
    tf_test_dataset = tf.constant(test_dataset)

    # Variables.
    weights_1 = tf.Variable(tf.truncated_normal([image_size * image_size, num_nodes]))
    biases_1 = tf.Variable(tf.zeros([num_nodes]))
    weights_2 = tf.Variable(tf.truncated_normal([num_nodes, num_labels]))
    biases_2 = tf.Variable(tf.zeros([num_labels]))

    # Training computation.
    logits_1 = tf.matmul(tf_train_dataset, weights_1) + biases_1
    relu_layer= tf.nn.relu(logits_1)
    logits_2 = tf.matmul(relu_layer, weights_2) + biases_2
    # Normal loss function
    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits_2, labels=tf_train_labels))
    # Loss function with L2 Regularization with beta=0.01
    regularizers = tf.nn.l2_loss(weights_1) + tf.nn.l2_loss(weights_2)
    loss = tf.reduce_mean(loss + beta * regularizers)

    # Optimizer.
    optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

    # Predictions for the training
    train_prediction = tf.nn.softmax(logits_2)

    # Predictions for validation 
    logits_1 = tf.matmul(tf_valid_dataset, weights_1) + biases_1
    relu_layer= tf.nn.relu(logits_1)
    logits_2 = tf.matmul(relu_layer, weights_2) + biases_2

    valid_prediction = tf.nn.softmax(logits_2)

    # Predictions for test
    logits_1 = tf.matmul(tf_test_dataset, weights_1) + biases_1
    relu_layer= tf.nn.relu(logits_1)
    logits_2 = tf.matmul(relu_layer, weights_2) + biases_2

    test_prediction =  tf.nn.softmax(logits_2)

num_steps = 3001

open("NeuralNetData.txt","w").close()
open("NeuralNetData.txt","a+")
open("NeuralNetData2.txt","w+").close()
open("NeuralNetData2.txt","a+")

with tf.Session(graph=graph) as session:
    tf.global_variables_initializer().run()
    print("Initialized")
    for step in range(num_steps):
        f= open("NeuralNetData.txt","a")
        t= open("NeuralNetData2.txt","a")
        # Pick an offset within the training data, which has been randomized.
        # Note: we could use better randomization across epochs.
        offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
        images_seen = step* batch_size
        # Generate a minibatch.
        batch_data = train_dataset[offset:(offset + batch_size), :]
        batch_labels = train_labels[offset:(offset + batch_size), :]
        # Prepare a dictionary telling the session where to feed the minibatch.
        # The key of the dictionary is the placeholder node of the graph to be fed,
        # and the value is the numpy array to feed to it.
        feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}
        _, l, predictions = session.run([optimizer, loss, train_prediction], feed_dict=feed_dict)
        if (images_seen % 1000 == 0):
            print("Minibatch loss at step {}: {}".format(step, l))
            print("Minibatch accuracy: {:.1f}".format(accuracy(predictions, batch_labels)))
            print("Validation accuracy: {:.1f}".format(accuracy(valid_prediction.eval(), valid_labels)))
            x=str(images_seen)
            y=str(accuracy(valid_prediction.eval(), valid_labels))
            f.write(x+','+y+'\n')
            f.close()
            r=str(accuracy(predictions, batch_labels))
            t.write(x+','+r+'\n')
            t.close()
            ani = animation.FuncAnimation(fig, animate, interval=1000)
            ani2 = animation.FuncAnimation(fig, animate2, interval=1000)
    print("Test accuracy: {:.1f}".format(accuracy(test_prediction.eval(), test_labels)))

首先,不要在由
FuncAnimation
调用的更新函数中调用
plt.show()。相反,它可能应该在脚本末尾恰好调用一次

其次,您似乎正在使用两个不同的
FuncAnimations
,它们在相同的轴上工作(
ax1
)。其中之一是清除该轴。因此,可能发生的情况是,绘图由一个函数更新,而由另一个函数清除-结果可能接近混乱


第三,您正在创建6002个动画,而不仅仅是一个或两个。它们将在相同的轴上运行。所以如果上面已经产生了混沌,这将产生6002倍的混沌

假设
FuncAnimation(图,animate,interval=1000)
是制作图形的部分,您是否知道
interval
变量代表什么,因为这可能是问题所在。使用两个图像对象来显示图形。后缓冲和前缓冲。向后绘制,显示前面。使用临时图像缓冲区前后交换,并重复整个过程。我仍然无法为这个问题创建一个稳定的图形。你会把plt.show()放在哪里?请给我看一份修改过的计划好吗?谢谢大家的帮助!!!不,我不能给你看修改过的程序,因为问题中的代码不是a,我可以修改和测试。