tensorflow

tensorflow笔记2

示例:有一堆x1\x2数据以及对应的标签y(01),若在给给出一个x1\x2数据,请你预测出y的值
将x1和x2分别作为横纵坐标八数据可视化成数据点,标签为1的点标为红色,为0的点为蓝色,让神经网络画出一条线区分红色点和蓝色点。
思路: 新用神经网络拟合出输入特征x和输出标签y的函数关系,然后生成网格覆盖这些点,把网格的交点(横纵坐标)作为输入送入训练好的神经网络模型中,
神经网络会为每一个坐标生成一个预测值,区分输出偏向1还是0,把输出预测值为0.5的线标出颜色,这条线就是区分01的线了。
# 导入所需模块
import tensorflow as tf
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
 
# 读入数据/标签 生成x_train y_train
df = pd.read_csv('dot.csv')    #读入文件
x_data = np.array(df[['x1', 'x2']])
y_data = np.array(df['y_c'])
 
x_train = x_data.reshape(-1,2)
y_train = y_data.reshape(-1, 1)
 
Y_c = [['red' if y else 'blue'] for y in y_train]
 
# 转换x的数据类型,否则后面矩阵相乘时会因数据类型问题报错
x_train = tf.cast(x_train, tf.float32)
y_train = tf.cast(y_train, tf.float32)
#打包成数据集
# from_tensor_slices函数切分传入的张量的第一个维度,生成相应的数据集,使输入特征和标签值一一对应
train_db = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(32)
# 生成神经网络的参数,输入层为2个神经元,隐藏层为11个神经元(随便定义的),1层隐藏层,输出层为1个神经元
# 用tf.Variable()保证参数可训练
w1 = tf.Variable(tf.random.normal([2, 11]), dtype=tf.float32)        #输入2,输出11
b1 = tf.Variable(tf.constant(0.01, shape=[11]))
 
w2 = tf.Variable(tf.random.normal([11, 1]), dtype=tf.float32)         #输入11,输出1(标签为0/1)
b2 = tf.Variable(tf.constant(0.01, shape=[1]))
 
lr = 0.005  # 学习率为
epoch = 800  # 循环轮数
 
# 训练部分
for epoch in range(epoch):
    for step, (x_train, y_train) in enumerate(train_db):
        with tf.GradientTape() as tape:        # 记录梯度信息,with结构实现前向传播 计算y
 
            h1 = tf.matmul(x_train, w1) + b1       # 记录神经网络乘加运算
            h1 = tf.nn.relu(h1)
            y = tf.matmul(h1, w2) + b2
 
            # 采用均方误差损失函数mse = mean(sum(y-out)^2)
            loss_mse = tf.reduce_mean(tf.square(y_train - y))
            # 添加l2正则化
            loss_regularization = []
            # tf.nn.l2_loss(w)=sum(w ** 2) / 2
            loss_regularization.append(tf.nn.l2_loss(w1))
            loss_regularization.append(tf.nn.l2_loss(w2))
           
            loss_regularization = tf.reduce_sum(loss_regularization)
            loss = loss_mse + 0.03 * loss_regularization  # REGULARIZER = 0.03
 
        # 计算loss对各个参数的梯度        反向传播求梯度
        variables = [w1, b1, w2, b2]
        grads = tape.gradient(loss, variables)
 
        # 实现梯度更新
        # w1 = w1 - lr * w1_grad
        w1.assign_sub(lr * grads[0])
        b1.assign_sub(lr * grads[1])
        w2.assign_sub(lr * grads[2])
        b2.assign_sub(lr * grads[3])
    # 每200个epoch,打印loss信息
    if epoch % 20 == 0:
        print('epoch:', epoch, 'loss:', float(loss))
 
# 预测部分
print("*******predict*******")
# xx在-3到3之间以步长为0.01,yy在-3到3之间以步长0.01,生成间隔数值点
xx, yy = np.mgrid[-3:3:.1, -3:3:0.1]
# 将xx, yy拉直,并合并配对为二维张量,生成二维坐标点
grid = np.c_[xx.ravel(), yy.ravel()]
grid = tf.cast(grid, tf.float32)
# 将网格坐标点喂入神经网络,进行预测,probs为输出
probs = []
for x_predict in grid:
    # 使用训练好的参数进行预测
    h1 = tf.matmul([x_predict], w1) + b1
    h1 = tf.nn.relu(h1)
    y = tf.matmul(h1, w2) + b2  # y为预测结果
    probs.append(y)
 
# 取第0列给x1,取第1列给x2
x1 = x_data[:, 0]
x2 = x_data[:, 1]
# probs的shape调整成xx的样子
probs = np.array(probs).reshape(xx.shape)
plt.scatter(x1, x2, color=np.squeeze(Y_c))           # squeeze去掉纬度是1的纬度,相当于去掉[['red'],[''blue]],内层括号变为['red','blue']
# 把坐标xx yy和对应的值probs放入contour函数,给probs值为0.5的所有点上色  plt.show()后 显示的是红蓝点的分界线
plt.contour(xx, yy, probs, levels=[.5])
plt.show()
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
用6步法实现鸢尾花分类	
import tensorflow as tf
from sklearn import datasets
import numpy as np
x_train = datasets.load_iris().data            # .data返回iris数据集所有输入特征
y_train = datasets.load_iris().target          # .target返回iris数据集所有标签 
np.random.seed(116)         #数据集的乱序
np.random.shuffle(x_train)
np.random.seed(116)
np.random.shuffle(y_train)
tf.random.set_seed(116)
   #搭建神经网络    一个全连接层
model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(3, activation='softmax', kernel_regularizer=tf.keras.regularizers.l2())
])
   #配置训练方法      神经网络末端使用了sofxmax函数,输出是概率分布,所以是false
model.compile(optimizer=tf.keras.optimizers.SGD(lr=0.1),
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
              metrics=['sparse_categorical_accu

#执行训练过程           每次迭代20次训练集要在测试集中验证一次准确率
model.fit(x_train, y_train, batch_size=32, epochs=500, validation_split=0.2, validation_freq=20)
   每次训练送入神经网络的样本数    数据集迭代循环500次   从训练集选择20%的数据作为测试集
model.summary()
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
Sequential可以搭建出上层输出就是下层输入的顺序网络结构,针对非顺序、跳连的网络结构,我们选择用class类封装一个网络结构。
init函数准备出搭建神经网络所需要的各种积木,call函数调用搭建好的积木,实现前向传播。
class类实现鸢尾花分类
import tensorflow as tf
from tensorflow.keras.layers import Dense
from tensorflow.keras import Model
from sklearn import datasets
import numpy as np
x_train = datasets.load_iris().data
y_train = datasets.load_iris().target 
np.random.seed(116)
np.random.shuffle(x_train)
np.random.seed(116)
np.random.shuffle(y_train)
tf.random.set_seed(116)
 
class IrisModel(Model):
    def __init__(self):
        super(IrisModel, self).__init__()
        self.d1 = Dense(3, activation='softmax', kernel_regularizer=tf.keras.regularizers.l2())
    def call(self, x):
        y = self.d1(x)
        return y 
model = IrisModel()
 
model.compile(optimizer=tf.keras.optimizers.SGD(lr=0.1),
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
              metrics=['sparse_categorical_accuracy'])
model.fit(x_train, y_train, batch_size=32, epochs=500, validation_split=0.2, validation_freq=20)
model.summary()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值