欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

从零开始线性回归

时间:2023-08-18
从零开始线性回归

一、线性回归小结 一、线性回归

%matplotlib inlineimport randomimport tensorflow as tffrom d2l import tensorflow as d2l#######################生成数据集def synthetic_data(w, b, num_examples): #@save """生成y=Xw+b+噪声""" X = tf.zeros((num_examples, w.shape[0])) X += tf.random.normal(shape=X.shape) y = tf.matmul(X, tf.reshape(w, (-1, 1))) + b y += tf.random.normal(shape=y.shape, stddev=0.01) y = tf.reshape(y, (-1, 1)) return X, y ###############################生成规则true_w = tf.constant([2, -3.4])true_b = 4.2features, labels = synthetic_data(true_w, true_b, 1000)########################################## 画图,观察特征与label的线性关系d2l.set_figsize()d2l.plt.scatter(features[:, (1)].numpy(), labels.numpy(), 1);#################################################读取数据集def data_iter(batch_size, features, labels): num_examples = len(features) indices = list(range(num_examples)) # 这些样本是随机读取的,没有特定的顺序 random.shuffle(indices) for i in range(0, num_examples, batch_size): j = tf.constant(indices[i: min(i + batch_size, num_examples)]) yield tf.gather(features, j), tf.gather(labels, j)#############################################试读batch_size = 10for X, y in data_iter(batch_size, features, labels): print(X, 'n', y) break###########################初始化模型参数w = tf.Variable(tf.random.normal(shape=(2, 1), mean=0, stddev=0.01), trainable=True)b = tf.Variable(tf.zeros(1), trainable=True)###################################################def linreg(X, w, b): #@save """线性回归模型""" return tf.matmul(X, w) + b#######################################################def squared_loss(y_hat, y): #@save """均方损失""" return (y_hat - tf.reshape(y, y_hat.shape)) ** 2 / 2#############################################################def sgd(params, grads, lr, batch_size): #@save """小批量随机梯度下降""" for param, grad in zip(params, grads): param.assign_sub(lr*grad/batch_size)###############################################################超参数的设置lr = 0.03num_epochs = 3net = linregloss = squared_loss#进行训练for epoch in range(num_epochs): for X, y in data_iter(batch_size, features, labels): with tf.GradientTape() as g: l = loss(net(X, w, b), y) # X和y的小批量损失 # 计算l关于[w,b]的梯度 dw, db = g.gradient(l, [w, b]) # 使用参数的梯度更新参数 sgd([w, b], [dw, db], lr, batch_size) train_l = loss(net(features, w, b), labels) print(f'epoch {epoch + 1}, loss {float(tf.reduce_mean(train_l)):f}')

print(f'w的估计误差: {true_w - tf.reshape(w, true_w.shape)}')#两维度不一致print(f'b的估计误差: {true_b - b}')

小结

我们学习了深度网络是如何实现和优化的。在这一过程中只使用张量和自动微分,不需要定义层或复杂的优化器。这一节只触及到了表面知识。在下面的部分中,我们将基于刚刚介绍的概念描述其他模型,并学习如何更简洁地实现其他模型。

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。