1. 程式人生 > >tensorflow構建一個簡單神經網絡

tensorflow構建一個簡單神經網絡

優化方法 clas show CA noise urn sil ini hold

使用Tensorflow實現一個簡單的神經網絡

輸入數據:

  • 輸入數據的形狀是[300, 1], 也就是每個元素有一個特征,所以輸入神經元是一個。

隱藏層:

  • 輸出神經元10個。輸出數據會成為[300, 10]的形狀。也就是300個元素,每個元素的特征變成了10個。
  • 激活函數使用Relu

輸出層:

  • 輸出數據是[300, 1]
  • 不使用激活函數

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

# 添加層(輸入層,隱藏層,輸出層)
# inputs,輸入數據
# insize,輸入神經數,out_size,輸出神經數
# activation_function,激活函數,None就是不作處理 def add_layer(inputs, in_size, out_size, activation_function=None): # (1,10) 正態分布隨機數 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 # np.newaxis, 增加一維,[300, 1] x_data = np.linspace(-1, 1, 300, dtype=np.float32)[:, np.newaxis] # 躁點 noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32) y_data
= np.square(x_data) - 0.5 + noise # 占位符 # [None,1], 任意行,1列 xs = tf.placeholder(tf.float32, [None, 1]) ys = tf.placeholder(tf.float32, [None, 1]) # 隱藏層 # 激活函數使用Relu,非線性化函數 # 為什麽使用激活函數參考 # https://www.cnblogs.com/silence-tommy/p/7113405.html l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu) # 輸出層 prediction = add_layer(l1, 10, 1, activation_function=None) # 損失函數 # reduct_sum, axis=【1】,將整行的所有列相加 loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), axis=[1])) # 優化,梯度下降,減少損失函數的值 # 得到使損失函數最低的W,也就是最優解 train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for i in range(1000): sess.run(train_step, feed_dict={xs: x_data, ys: y_data}) if i % 50 == 0: print(sess.run(loss, feed_dict={xs: x_data, ys: y_data})) fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.scatter(x_data, y_data) plt.show()

相關方法

tf:

  • tf.random_normal,取正態分布分布的隨機值,得到一個列表
  • tf.Variable,tf中定義變量需要用這個方法,不能直接聲明
  • tf.zeros,類似於np.zeros
  • tf.matmul, 矩陣點積
  • tf.placeholder,占位符
  • tf.reduce_mean, tf.reduce_sum, tf.square,和numpy類似
  • tf.train.GradientDescentOptimizer,優化方法使用梯度下降方法

np:

  • np.linspace,做等分,得到一個一維的array
  • [:, np.newaxis], array後面接這個,表示增加一個維度。例如作用在一維數組上(100,),會得到 [ 100,1 ]
  • np.random.normal,正態分布隨機數
  • astype,拷貝一份制定類型的數組

Reference:

https://www.cnblogs.com/silence-tommy/p/7113405.html

https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/

tensorflow構建一個簡單神經網絡