tensorflow1.1/構建神經網路分類
阿新 • • 發佈:2019-02-20
環境:tensorflow1.1,matplotlib2.02,python3
#coding:utf-8
"""
tensorflow 1.1
python 3
matplotlib 2.02
"""
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(100) #隨機種子
tf.set_random_seed(100) #設定隨機種子
a = np.ones((500,2))
noise = np.random.normal(4,1,(500,2))
x0 = np.random.normal(2 *a,1)+noise #正態分佈,標磚差為1
x1 = np.random.normal(7*a,1)+noise
x = np.vstack((x0,x1)) #垂直合併 (200,2)
y0 = np.zeros(500)
y1 = np.ones(500)
y = np.hstack((y0,y1)) #水平合併
xs = tf.placeholder(tf.float32,x.shape) #輸入形狀(200,2)
ys = tf.placeholder(tf.int32,y.shape) #輸出形狀(200,)
#構建神經網路
l1 = tf.layers.dense(xs,50,tf.nn.relu)
output = tf.layers.dense(l1,2 )
#定義損失函式
loss = tf.losses.sparse_softmax_cross_entropy(labels=ys,logits=output)
#定義計算準確度函式
#tf.metrics.accuracy計算精度,返回accuracy和update_operation
accuracy = tf.metrics.accuracy(labels=ys,predictions=tf.argmax(output,axis=1))[1]
#梯度下降
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.05).minimize(loss)
with tf.Session() as sess:
#初始化
init = tf.group(tf.global_variables_initializer(),tf.local_variables_initializer())
sess.run(init)
#開啟互動模式
plt.ion()
for step in range(1000):
_,acc,pred = sess.run([optimizer,accuracy,output],feed_dict={xs:x,ys:y})
if step % 50 == 0:
plt.clf() #清空當前影象
plt.scatter(x[:,0],x[:,1],c = pred.argmax(1),s=100,marker='*',cmap='RdYlGn') #cmap是畫布
plt.text(2,12,'accuracy=%.2f' %acc,fontdict={'size':15,'color':'red'})
plt.pause(0.1) #暫停
plt.ioff() #關閉互動模式
plt.show()
結果
隨著分類準確率的提高,隨機生成的點明顯被分為兩類