[Tensorflow]以“线性回归”为例讲解Tensorflow api底层细节

本文通过线性回归模型深入解析TensorFlow的底层API和高级API。首先使用底层API手动搭建模型,设置损失函数和优化器,进行训练并评估。随后,通过高级API简化流程,创建LinearRegressor,利用预设的输入函数进行训练和评估,展示两种方法的实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

- 前言
以“线性回归”理解tensorflow api底层细节。分为两部分讲解。

1. 底层API

import tensorflow as tf
from tqdm import tqdm

#模型参数
W = tf.Variable([0.3],dtype=tf.float32)
b = tf.Variable([-0.3],dtype=tf.float32)
#模型输入和输出
x = tf.placeholder(tf.float32)
linear_model = W*x+b
y = tf.placeholder(tf.float32)

#损失函数及优化器
loss = tf.reduce_sum(tf.square(linear_model-y))
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)

#训练数据
x_train = [1,2,3,4]
y_train = [0,-1,-2,-3]

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

for i in tqdm(range(1000)):
    sess.run(train,{x:x_train, y:y_train})

#评估训练的正确率
curr_W, curr_b, curr_loss = sess.run([W, b, loss ], {x:x_train, y:y_train})
print("W: %s b: %s loss: %s"% (curr_W, curr_b, curr_loss))
  • 高层API
import tensorflow as tf
import numpy as np

feature_columns = [tf.feature_column.numeric_column("x",shape=[1])]
estimator = tf.estimator.LinearRegressor(feature_columns=feature_columns)
x_train = np.array([1,2,3,4])
y_train = np.array([0,-1,-2,-3])
x_eval = np.array([2,5,8,1])
y_eval = np.array([-1.01,-4.1,-7,0])

input_fn = tf.estimator.inputs.numpy_input_fn(
    {"x":x_train},y_train,batch_size=4, num_epochs=None, shuffle=True)
train_input_fn = tf.estimator.inputs.numpy_input_fn(
    {"x":x_train},y_train,batch_size=4, num_epochs=1000, shuffle=False)
eval_input_fn = tf.estimator.inputs.numpy_input_fn(
    {"x":x_eval},y_eval,batch_size=4, num_epochs=1000, shuffle=False)
    
estimator.train(input_fn=input_fn,steps = 1000)
train_metrics = estimator.evaluate(input_fn=train_input_fn)
eval_metrics = estimator.evaluate(input_fn=eval_input_fn)

print("train metrics: %r"% train_metrics)
print("eval metrics: %r"% eval_metrics)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值