机器学习(二)——鸢尾花案例
生活随笔
收集整理的這篇文章主要介紹了
机器学习(二)——鸢尾花案例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
鳶尾花數據加載
from sklearn import datasets from pandas import DataFrame import pandas as pd from sklearn.datasets import load_iris x_data = datasets.load_iris().data##返回所有輸入特征 y_data = datasets.load_iris().target##返回數據集標簽 print(x_data) print(y_data)##添加列名 x_data = DataFrame(x_data, columns=['花萼長度','花萼寬度','花萼長度','花萼寬度']) pd.set_option('display.unicode.east_asian_width', True)#設置列名對齊 print("x_data add index:\n", x_data) x_data['類別'] = y_data #新加一列,列標簽為‘類別’,數據為y_data print("x_data add a colmun:\n", x_data)神經網絡實現鳶尾花分類
from sklearn import datasets import tensorflow as tf import numpy as np from matplotlib import pyplot as plt import pandas as pd #步驟 ###準備數據 # 數據讀入 x_data = datasets.load_iris().data##加載數據集所有特征 y_data = datasets.load_iris().target##加載數據集所有標簽 # 數據集亂序 np.random.seed(116)#使用相同的seed,使輸入特征/標簽一一對應 np.random.shuffle(x_data) np.random.seed(116) np.random.shuffle(y_data) tf.random.set_seed(116) # 生成訓練集和測試集 數據總量150,訓練:測試一般 4:1 x_train = x_data[:-30] y_train = y_data[:-30] x_test = x_data[-30:] y_test = y_data[-30:] # 配成(輸入特征,標簽)對,每次讀入一小批(batch) train_db = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(32) test_db = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32) ##tf.data.Dataset.from_tensor_slices()的作用是使輸入標簽配對打包###搭建神經網絡 # 定義神經網絡中的可訓練參數 #生成神經網絡參數,4個輸入特征,所以輸入層為4個輸入節點,因為是分成3類,所以輸出層為3個神經元 w1 = tf.Variable(tf.random.truncated_normal([4,3], stddev=0.1, seed=1)) b1 = tf.Variable(tf.random.truncated_normal([3], stddev=0.1, seed=1))lr = 0.1#學習率,不能太大或太小 train_loss_results = []#記錄每輪loss test_acc = []#將每輪的acc記錄下來 epoch = 500#循環次數 loss_all = 0#記錄每輪四個step的loss和 ###參數優化 # 嵌套循環迭代,with結構更新參數,顯示當前loss for epoch in range(epoch):for step, (x_train, y_train) in enumerate(train_db):with tf.GradientTape() as tape:x_train = tf.cast(x_train, dtype=w1.dtype)y = tf.matmul(x_train, w1) + b1#神經網絡乘加運算y = tf.nn.softmax(y)#使y結果符合概率分布 與獨熱碼求lossy_ = tf.one_hot(y_train, depth = 3)#將標簽轉為獨熱碼,方便計算lossy_ = tf.cast(y_, dtype=y.dtype)loss = tf.reduce_mean(tf.square(y_-y))#采用均方誤差損失函數loss_all += loss.numpy() #加loss累加,后面求均值grads = tape.gradient(loss, [w1, b1])#實現梯度更新 w1 = w1 - lr * w1_grad b = b1 - lr * b_gradw1.assign_sub(lr * grads[0])#參數w1自更新b1.assign_sub(lr * grads[1])#參數b自更新#每個epoech打印loss信息print("Epoch{},loss:{}".format(epoch, loss_all/4))train_loss_results.append(loss_all / 4)#記錄四個step的loss平均值loss_all = 0#歸0,為下一次做準備 ###測試效果 # 計算當前參數向后傳播的準確率,顯示當前的acctotal_correct, total_number = 0, 0for x_test, y_test in test_db:x_test = tf.cast(x_test, dtype=w1.dtype)#使用訓練得到的參數進行預測y = tf.matmul(x_test, w1) + b1y = tf.nn.softmax(y)pred = tf.argmax(y, axis=1)#返回最大值,即預測到的值#將pred轉換為y_test類型pred = tf.cast(pred, dtype=y_test.dtype)#將比較結果的布爾型轉換為int型correct = tf.cast(tf.equal(pred, y_test), dtype=tf.int32)correct = tf.reduce_sum(correct)#如果分類正確則+1total_correct += int(correct)#累加,方便后面求正確率total_number += x_test.shape[0]#測試總樣本數acc = total_correct / total_numbertest_acc.append(acc)print("Test_acc:",acc)print("----------------------------") ##繪制loss曲線方便觀察 plt.title("Loss Function Curve") plt.xlabel('Epoch')#x軸變量名 plt.ylabel('loss')#y軸變量名 plt.plot(train_loss_results, label="$Loss$") plt.legend()#畫出曲線圖標 plt.show()#畫出圖像##繪制acc曲線方便觀察 plt.title("Acc Curve") plt.xlabel('Epoch')#x軸變量名 plt.ylabel('Acc')#y軸變量名 plt.plot(test_acc, label="$Accuracy$") plt.legend()#畫出曲線圖標 plt.show()#畫出圖像總結
以上是生活随笔為你收集整理的机器学习(二)——鸢尾花案例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 机器学习(一)——熟悉tensorflo
- 下一篇: 机器学习(三)——预备知识(学习率与激活