机器学习(二)——鸢尾花案例

鸢尾花数据加载

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结果符合概率分布 与独热码求loss
            y_ = tf.one_hot(y_train, depth = 3)#将标签转为独热码,方便计算loss
            y_ = 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_grad
        w1.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,为下一次做准备
###测试效果
# 计算当前参数向后传播的准确率,显示当前的acc
    total_correct, total_number = 0, 0
    for x_test, y_test in test_db:
        x_test = tf.cast(x_test, dtype=w1.dtype)

        #使用训练得到的参数进行预测
        y = tf.matmul(x_test, w1) + b1
        y = 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)#如果分类正确则+1
        total_correct += int(correct)#累加,方便后面求正确率
        total_number += x_test.shape[0]#测试总样本数
    acc = total_correct / total_number
    test_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()#画出图像

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值