Tensorflow 建立神經網路(二)視覺化

2022-06-23 19:27:16 字數 2567 閱讀 3556

將訓練過程視覺化出來

import

tensorflow as tf

import

numpy as np

import

matplotlib.pyplot as plt

#去掉警告

import

warnings

warnings.filterwarnings(

"ignore

",".*gui is implemented.*")

import

osos.environ[

'tf_cpp_min_log_level

'] = '2'

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) #

保證 biases 不為 0

wx_plus_b = tf.matmul(inputs, weights) +biases

if activation_function ==none:

outputs =wx_plus_b

else

: outputs =activation_function(wx_plus_b)

return

outputs

x_data = np.linspace(-1, 1, 300) #

(300,)

x_data = x_data.reshape(300,1) #

(300, 1)

noise = np.random.normal(0, 0.05, x_data.shape)

y_data = np.square(x_data) - 0.5 +noise

#為 batch 做準備

xs = tf.placeholder(tf.float32, [none, 1])

ys = tf.placeholder(tf.float32, [none, 1])

l1 = add_layer(xs, 1, 10, activation_function =tf.nn.relu)

prediction = add_layer(l1, 10, 1, activation_function =none)

loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), 1))

train_step = tf.train.gradientdescentoptimizer(0.1).minimize(loss)

init =tf.global_variables_initializer()#畫圖

fig =plt.figure()

ax = fig.add_subplot(1,1,1)

ax.scatter(x_data, y_data)

plt.ion()

with tf.session() as sess:

sess.run(init)

for step in range(1000):

sess.run(train_step, feed_dict =)

if step % 20 ==0:

#print('loss = ', sess.run(loss, feed_dict = ))

#try:

#ax.lines.remove(lines[0])

#except exception:

#pass

prediction_value = sess.run(prediction, feed_dict =)

#print(prediction_value)

lines = ax.plot(x_data, prediction_value,'

b-', lw = 3)

plt.pause(0.1)

ax.lines.remove(lines[0])

step += 1plt.show()

在訓練過程中遇到的問題即解決辦法:

1、顯示不出藍線

2、不能動態顯示

解決辦法:

1、在spyder中,將tools----preferences----ipython console----graphics----backend----改成automatic,最後需要再對spyder軟體進行重新啟動,沒有重啟則不能實現設定效果。這樣就可以顯示出單獨的視窗,並可以實現動態的figure顯示,

2、step += 1,我剛開始執行的時候沒有加這句,就會導致結果被剔除,就沒有紅線

可以看出最後會越接近給出的資料