人工智能是指,让机器具有人的思惟和意识。人工智能主要有三个学派:html
上图给出了搭建与使用神经网络的流程示意图。具体地,python
1. 准备数据
数据量越大越好,要构成特征和标签对。web
2. 搭建网络
搭建神经网络的网络结构。网络
3. 优化参数
经过反向传播,优化连线的权重,直到模型的识别准确率达到要求,获得最优的连线权重,把这个模型保存起来。数据结构
4. 应用网络
用保存的模型,输入从未见过的新数据,它会经过前向传播,输出几率值,几率值最大的一个,就是分类或预测的结果。app
人们经过经验总结出了规律:经过测量花的花萼长、花萼宽、花瓣长、花瓣宽,能够得出鸢尾花的类别。好比,若某鸢尾花知足:花萼长>花萼宽且花瓣长/花瓣宽>2,则为1杂色鸢尾。dom
鸢尾花数据集:提供了150组鸢尾花数据,每组数据包含鸢尾花花萼长、花萼宽、花瓣长、花瓣宽及对应的类别。其中前4个属性做为输入特征,类别做为标签,0表明狗尾草鸢尾,1表明杂色鸢尾,2表明弗吉尼亚鸢尾。svg
网络结构
函数
搭建网络,初始化参数
学习
喂入数据,前向传播
损失函数
损失函数(loss function):预测值(y)与标准答案(y_)的差距。
损失函数能够定量判断W、b的优劣,当损失函数输出最小时,参数W、b会出现最优值。
目的:想找到一组参数w和b,使得损失函数最小。
梯度降低,反向传播
学习率(learning rate,lr):当学习率设置的太小时,收敛过程将变得十分缓慢。而当学习率设置的过大时,梯度可能会在最小值附近来回震荡,甚至可能没法收敛。
导入所需模块:
import tensorflow as tf from sklearn import datasets from matplotlib import pyplot as plt import numpy as np
1.1 读入数据集
from sklearn.datasetsimport load_iris x_data= datasets.load_iris().data # 返回iris数据集全部输入特征 y_data= datasets.load_iris().target # 返回iris数据集全部标签
pd.read_csv('文件名',header=第几行做为表头,sep='分割符号')
open('文件名','r')
df = pd.read_csv('iris.txt',header = None,sep=',') #读取本地文件 data = df.values # 去掉索引并取值 x_data = [lines[0:4] for lines in data] # 取输入特征 x_data = np.array(x_data,float) # 转换为numpy格式 y_data = [lines[4] for lines in data] # 取标签 for i in range(len(y_data)): if y_data[i] == 'Iris-setosa': y_data[i] = 0 elif y_data[i] == 'Iris-versicolor': y_data[i] = 1 …… y_data = np.array(y_data)
f = open('iris.txt','r') # 取本地文件 contents = f.readlines() # 按行读取 i=0 for content in contents: temp = content.split(',') # 按逗号分隔 x_data[i] = np.array([temp[0:4]],dtype=float) # 取输入特征 if temp[4] == 'Iris-setosa\n': # 判断标签并赋值 y_data[i] = 0 elif temp[4] == 'Iris-versicolor\n': y_data[i] = 1 …… i = i + 1
1.2 数据集乱序
np.random.seed(116) np.random.shuffle(x_data) np.random.seed(116) np.random.shuffle(y_data) tf.random.set_seed(116)
1.3 数据集分割成永不相见的训练集和测试集
x_train = x_data[:-30] y_train = y_data[:-30] x_test = x_data[-30:] y_test = y_data[-30:]
x_train = tf.cast(x_train, tf.float32) x_test = tf.cast(x_test, tf.float32)
1.4 配成[输入特征,标签]对,每次喂入一小撮(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)
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 # 学习率为0.1 train_loss_results = [] # 将每轮的loss记录在此列表中,为后续画loss曲线提供数据 test_acc = [] # 将每轮的acc记录在此列表中,为后续画acc曲线提供数据 epoch = 500 # 循环500轮 loss_all = 0 # 每轮分4个step,loss_all记录四个step生成的4个loss的和
优化可训练的参数
for epoch in range(epoch): #数据集级别的循环,每一个epoch循环一次数据集 for step, (x_train, y_train) in enumerate(train_db): #batch级别的循环 ,每一个step循环一个batch with tf.GradientTape() as tape: # with结构记录梯度信息 # 前向传播过程计算y y = tf.matmul(x_train, w1) + b1 # 神经网络乘加运算 y = tf.nn.softmax(y) # 使输出y符合几率分布(此操做后与独热码同量级,可相减求loss) y_ = tf.one_hot(y_train, depth=3) # 将标签值转换为独热码格式,方便计算loss和accuracy # 计算总loss loss = tf.reduce_mean(tf.square(y_ - y)) # 采用均方偏差损失函数 loss_all += loss.numpy() # 将每一个step计算出的loss累加,为后续求loss平均值提供数据,这样计算的loss更准确 # 计算loss对各个参数的梯度 grads = tape.gradient(loss, [w1, b1]) # 实现梯度更新 w1 = w1 - lr * w1_grad b = b - lr * b_grad w1.assign_sub(lr * grads[0]) # 参数w1自更新 b1.assign_sub(lr * grads[1]) # 参数b自更新 # 每一个epoch,打印loss信息 print("Epoch {}, loss: {}".format(epoch, loss_all/4)) train_loss_results.append(loss_all / 4) # 将4个step的loss求平均记录在此变量中 loss_all = 0 # loss_all归零,为记录下一个epoch的loss作准备
当前参数前向传播后的准确率
为了查看效果,程序中能够加入每遍历一次数据集显示当前参数前向传播后的准确率
# 测试部分(每一个epoch下均进行一次计算) # total_correct为预测对的样本个数, total_number为测试的总样本数,将这两个变量都初始化为0 total_correct, total_number = 0, 0 for x_test, y_test in test_db: # 使用更新后的参数进行预测 y = tf.matmul(x_test, w1) + b1 y = tf.nn.softmax(y) pred = tf.argmax(y, axis=1) # 返回y中最大值的索引,即预测的分类 # 将pred转换为y_test的数据类型 pred = tf.cast(pred, dtype=y_test.dtype) # 若分类正确,则correct=1,不然为0,将bool型的结果转换为int型 correct = tf.cast(tf.equal(pred, y_test), dtype=tf.int32) # 将每一个batch的correct数加起来 correct = tf.reduce_sum(correct) # 将全部batch中的correct数加起来 total_correct += int(correct) # total_number为测试的总样本数,也就是x_test的行数,shape[0]返回变量的行数 total_number += x_test.shape[0] # 总的准确率等于total_correct/total_number 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$") # 逐点画出trian_loss_results值并连线,连线图标是Loss plt.legend() # 画出曲线图标 plt.show() # 画出图像 # 绘制 Accuracy 曲线 plt.title('Acc Curve') # 图片标题 plt.xlabel('Epoch') # x轴变量名称 plt.ylabel('Acc') # y轴变量名称 plt.plot(test_acc, label="$Accuracy$") # 逐点画出test_acc值并连线,连线图标是Accuracy plt.legend() plt.show()