溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何通過python的matplotlib包將Tensorflow數(shù)據(jù)進(jìn)行可視化

發(fā)布時(shí)間:2021-07-24 09:18:36 來源:億速云 閱讀:107 作者:小新 欄目:開發(fā)技術(shù)

這篇文章給大家分享的是有關(guān)如何通過python的matplotlib包將Tensorflow數(shù)據(jù)進(jìn)行可視化的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。

使用matplotlib中的一些函數(shù)將tensorflow中的數(shù)據(jù)可視化,更加便于分析

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

def add_layer(inputs, in_size, out_size, activation_function=None):
  Weights = tf.Variable(tf.random_normal([in_size, out_size]))
  biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
  Wx_plus_b = tf.matmul(inputs, Weights) + biases
  if activation_function is None:
    outputs = Wx_plus_b
  else:
    outputs = activation_function(Wx_plus_b)
  return outputs

# Make up some real data
x_data = np.linspace(-1, 1, 300)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise


# define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 1])
ys = tf.placeholder(tf.float32, [None, 1])
# add hidden layer
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
# add output layer
prediction = add_layer(l1, 10, 1, activation_function=None)

# the error between prediction and real data
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
# important step

#initialize_all_variables已被棄用,使用tf.global_variables_initializer代替。 
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

# plot the real data
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(x_data, y_data)
plt.ion() #使plt不會(huì)在show之后停止而是繼續(xù)運(yùn)行
plt.show()


for i in range(1000):
  # training
  sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
  if i % 50 == 0:
    # to visualize the result and improvement
    try:
      ax.lines.remove(lines[0]) #在每一次繪圖之前先講上一次繪圖刪除,使得畫面更加清晰
    except Exception:
      pass
    prediction_value = sess.run(prediction, feed_dict={xs: x_data})
    # plot the prediction
    lines = ax.plot(x_data, prediction_value, 'r-', lw=5) #'r-'指繪制一個(gè)紅色的線
    plt.pause(1) #指等待一秒鐘

運(yùn)行結(jié)果如下:(實(shí)際效果應(yīng)該是動(dòng)態(tài)的,應(yīng)當(dāng)使用ipython運(yùn)行,使用jupyter運(yùn)行則圖片不是動(dòng)態(tài)的)

如何通過python的matplotlib包將Tensorflow數(shù)據(jù)進(jìn)行可視化

注意:initialize_all_variables已被棄用,使用tf.global_variables_initializer代替。

感謝各位的閱讀!關(guān)于“如何通過python的matplotlib包將Tensorflow數(shù)據(jù)進(jìn)行可視化”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI