說明
在playground上有一些二維數據分類的例子,也比較好玩,本文就是來探討如何對最簡單的數據進行分類。
只有一個隱含層
1.生成隨機數據
x1 = np.random.rand(100,2)*6
x2 = np.random.rand(100,2)*-6
x_ = np.vstack((x1,x2))
y1 = np.ones((100,1))
y2 = np.zeros((100,1))
y_ = np.vstack((np.hstack((y1,y2)),np.hstack((y2,y1))))
這里我隨機生成了兩百個樣本數據,x_代表點的位置,y_是標簽數據。這里標簽數據的生成略顯復雜,其實本質上就是進行行列合并操作。
為了方便觀察這里將生成的數據在圖上繪制出來,這里使用matplotlib
for i in range(200):
a,b = x_[i]
if y_[i,0] == 0:
plt.scatter(a,b,c='blue',alpha=0.5)
else:
plt.scatter(a,b,c='yellow',alpha=0.5)
樣本數據圖
2.構建神經網絡
這里我們只有一個神經元,激活函數使用的是relu,這個跟playground是一樣的。簡單的分析一下這個網絡的結構,輸入是兩個,隱含層是一個,輸出是兩個。
y1=relu(W1*x+b1)
y2=softmax(W2*y1+b2)
上面的乘法是矩陣乘法,根據分析W1是一個[1,2]
的矩陣,b1是[1]
矩陣,W2是[1,2]
矩陣,b2也是[1,2]
矩陣。
b1 = tf.Variable(tf.zeros([1,1],dtype=np.float32))
W1 = tf.Variable(np.random.rand(2,1).astype(np.float32))
y1 = activefun(tf.matmul(x,W1)+b1)
b2 = tf.Variable(tf.zeros([1,2]),dtype=np.float32)
W2 = tf.Variable(np.random.rand(1,2).astype(np.float32))
y2 = tf.nn.softmax(tf.matmul(y1,W2)+b2)
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y2, labels=y))
#損失函數
train_step = tf.train.GradientDescentOptimizer(0.03).minimize(cross_entropy)
#優化算法
correct_prediction = tf.equal(tf.argmax(y2,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#精度
上面的代碼構建了這個網絡,這里要關注矩陣運算,很有可能出現問題。
3.運行和分析
運行的第一步是初始化變量,然后就是迭代。
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for i in range(n):
sess.run(train_step)
if i%10 == 0:
print(sess.run([cross_entropy,accuracy]),i)
把上面的代碼總結一下這里定義一個訓練函數和一個預測函數:
def model(x,y,n,activefun=tf.nn.relu):
b1 = tf.Variable(tf.zeros([1,1],dtype=np.float32))
W1 = tf.Variable(np.random.rand(2,1).astype(np.float32))
y1 = activefun(tf.matmul(x,W1)+b1)
b2 = tf.Variable(tf.zeros([1,2]),dtype=np.float32)
W2 = tf.Variable(np.random.rand(1,2).astype(np.float32))
y2 = tf.nn.softmax(tf.matmul(y1,W2)+b2)
# cross_entropy = -tf.reduce_sum(y*tf.log(y2))/200.
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y2, labels=y))
train_step = tf.train.GradientDescentOptimizer(0.03).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y2,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
sess.run(tf.global_variables_initializer())
for i in range(n):
sess.run(train_step)
if i%10 == 0:
print(sess.run([cross_entropy,accuracy]),i)
return sess.run([b1,W1,b2,W2])
def predict(x,b1,W1,b2,W2):
y1 = tf.nn.relu(tf.matmul(x,W1)+b1)
y2 = tf.nn.softmax(tf.matmul(y1,W2)+b2)
return y2
4.可視化
把結果計算之后,我們希望能看到這個分類邊界,其實想法很簡單,在坐標中等距離生成2500個點(50行50列),然后在預測函數中進行計算,根據計算結果繪制點的顏色。
bg = []
values = np.linspace(-6,6,num=50)
for i in range(50):
bg.append([[values[i], v] for v in values])
xx = np.array(bg).reshape(2500,2).astype(np.float32)
out = predict(xx,b1,W1,b2,W2)
yy = sess.run(tf.argmax(out,axis=1))
for i in range(2500):
a,b = xx[i]
if yy[i] == 0:
plt.scatter(a,b,c='blue',alpha=0.5)
else:
plt.scatter(a,b,c='yellow',alpha=0.5)