git: https://github.com/linyi0604/MachineLearning/tree/master/07_tensorflow/
1 import tensorflow as tf 2 from numpy.random import RandomState 3
4 '''
5 模擬一個回歸案例 6 自定義一個損失函數為: 7 當真實值y_更大的時候 loss = a(y_ - y) 8 當預測值y更大的時候 loss = b(y - y_) 9
10
11 loss_less = 10 12 loss_more = 1 13 loss = tf.reduce_sum( 14 tf.where( 15 tf.greater(y, y_), 16 (y - y_) * loss_more, 17 (y_ - y) * loss_less 18 )) 19
20 tf.reduce_sum() 求平均數 21 tf.where(condition, a, b) condition為真時返回a 否則返回b 22 tf.grater(a, b) a>b時候返回真 否則返回假 23
24 '''
25
26 # 一批運算的數據數量
27 batch_size = 8
28
29 # 輸入數據有兩列特征
30 x = tf.placeholder(tf.float32, shape=[None, 2], name="x-input") 31 # 輸入的真實值
32 y_ = tf.placeholder(tf.float32, shape=[None, 1], name="y-input") 33
34 # 定義一個單層神經網絡 前向傳播的過程
35 # 權重變量 2*1維度 方差為1 均值為0 種子變量使得每次運行生成同樣的隨機數
36 w1 = tf.Variable(tf.random_normal([2, 1], stddev=1, seed=1)) 37
38 # 計算過程
39 y = tf.matmul(x, w1) 40
41 # 自定義損失函數部分
42 loss_less = 10
43 loss_more = 1
44 loss = tf.reduce_sum( 45 tf.where( 46 tf.greater(y, y_), 47 (y - y_) * loss_more, 48 (y_ - y) * loss_less 49 )) 50
51 # 訓練內容 訓練速度0.001 讓loss最小
52 train_step = tf.train.AdamOptimizer(0.001).minimize(loss) 53
54
55 # 生成隨機數作為訓練數據
56 rdm = RandomState(1) 57 dataset_size = 128
58 X = rdm.rand(dataset_size, 2) 59 # 預測的正確至設置為兩個特征加和 加上一個噪音
60 # 不設置噪音 預測的意義就不大了
61 # 噪音設置為均值為0的極小量
62 Y = [[x1 + x2 + rdm.rand()/10.0-0.05] for (x1, x2) in X] 63
64 # 開啟會話訓練
65 with tf.Session() as sess: 66 init_op = tf.initialize_all_variables() 67 sess.run(init_op) 68 STEPS = 5000
69 for i in range(STEPS): 70 start = (i * batch_size) % dataset_size 71 end = min(start + batch_size, dataset_size) 72 sess.run( 73 train_step, 74 feed_dict={ 75 x: X[start: end], 76 y_: Y[start: end], 77 } 78 ) 79 print(sess.run(w1)) 80
81 '''
82 [[1.019347 ] 83 [1.0428089]] 84 '''
41 # 自定義損失函數部分 42 loss_less = 10 43 loss_more = 1 44 loss = tf.reduce_sum( 45 tf.where( 46 tf.greater(y, y_), 47 (y - y_) * loss_more, 48 (y_ - y) * loss_less 49 ))
這里自定義損失的時候,如果結果少了損失權重為10, 多了損失權重為1
預測結果 w1 為 [[1.02],[1.04]] , 所以結果預測偏向多於x1+x2, 因為多的話,損失少