1. 程式人生 > 實用技巧 >tensorflow2.0——實現波士頓房價資料集的分類問題

tensorflow2.0——實現波士頓房價資料集的分類問題

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

# 模擬資料
x = np.array(
    [137.97, 104.50, 100, 126.32, 79.20, 99.00, 124.0, 114.0, 106.69, 140.05, 53.75, 46.91, 68.0, 63.02, 81.26, 86.21])

x = x - np.mean(x)                  #   x全為正,需要減去平均數讓均值為0
y = np.array([1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0])

# 設定超參 iter = 20000 learn_rate = 0.000001 loss_list = [] acc_list = [] # 初始化訓練引數 w = tf.Variable(0.0001*np.random.randn()) b = tf.Variable(0.0001*np.random.randn()) print('初始w:{},b:{}'.format(w,b)) # 設計損失函式 for i in range(iter): with tf.GradientTape() as tape: y_p = 1 / (1 + tf.exp(-(w * x + b))) loss
= tf.reduce_mean(-(y * tf.math.log(y_p) + (1 - y) * tf.math.log(1 - y_p))) dloss_dw, dloss_db = tape.gradient(loss, [w, b]) # 獲得引數的偏導 accuary = tf.reduce_mean(tf.cast(tf.equal(tf.round(y_p), y), tf.float32)) loss_list.append(loss) acc_list.append(accuary) # 迭代更新引數
w.assign_sub(learn_rate * dloss_dw) b.assign_sub(learn_rate * dloss_db) if i % 100 == 0: print('y:',y) print('y_p:',y_p) print('tf.equal(tf.round(y_p),y):\n',tf.equal(tf.round(y_p),y)) print('第{}次迭代,loss:{},w:{},b:{},accuary:{}'.format(i,loss,w,b,accuary)) plt.subplot(221) plt.plot(loss_list) plt.subplot(223) plt.plot(acc_list) plt.show()