import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
def add_layer(inputs, input_size, output_size, activation_function = none):
weights = tf.variable(tf.random_normal([input_size, output_size]))
biases = tf.variable(tf.zeros([1, output_size]) + 0.1) #biases初始化為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
#create_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(dtype=tf.float32,shape=[none, 1])
ys = tf.placeholder(dtype=tf.float32,shape=[none, 1])
#add hiden 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 predic and real data
loss = tf.reduce_mean(tf.reduce_sum(tf.square(prediction - ys), reduction_indices=[1])) #相當於轉化為橫向量
train_step = tf.train.gradientdescentoptimizer(0.2).minimize(loss)
#initialize all variable
init = tf.initialize_all_variables()
sess = tf.session()
sess.run(init)fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x_data, y_data)
plt.ion()
for i in range(1000):
#training
sess.run(train_step, feed_dict=)
if i%50 == 0:try:
ax.lines.remove(lines[0])
except exception:
pass
prediction_value = sess.run(prediction, feed_dict=)
lines = ax.plot(x_data, prediction_value, color = 'red')
plt.pause(0.5)
while(true):
plt.pause(1)
plt.ion進入互動模式,最後的while迴圈保證介面不會自動關閉
剛打算用qq截圖,發現開啟qq介面後,每隔一秒,該圖介面會彈出擋住qq介面,也就是說使用plt,ion(),該圖一直在重新整理
結果視覺化
1 import tensorflow as tf 2import numpy as np 3import matplotlib.pyplot as plt 4def add layer inputs,in size,out size,activation function none 5 weigh...
Tensorfow 之 結果視覺化
安裝 中輸出結果視覺化模組 matplotlib import matplotlib.pyplot as plt使用上篇部落格的例子,在裡面新增了視覺化的部分,就可以將這先乏味的資料通通影象更直觀的檢視了。首先需要的是構建圖形,用散點圖描述真實資料之間的關係。每隔50次訓練重新整理一次圖形,用紅色 ...
高維聚類結果視覺化
利用sklearn包裡的birch演算法,以iris資料集,聚類結果視覺化 如下 import numpy as np import matplotlib.pyplot as plt from sklearn.datasets.samples generator import make blobs ...