import numpy as np
# 生成随机数据
# 生成随机数据
x_train = np.random.rand(100000).astype(np.float32)
y_train = 0.5 * x_train + 2
import tensorflow as tf
# 定义模型
W = tf.Variable(tf.random.normal([1]))
b = tf.Variable(tf.zeros([1]))
y = W * x_train + b
# 定义损失函数
loss = tf.reduce_mean(tf.square(y - y_train))
# 定义优化器
optimizer = tf.optimizers.SGD(0.5)
# 训练模型
for i in range(100):
with tf.GradientTape() as tape:
y = W *
TensorFlow与Pytorch的转换——1简单线性回归
于 2024-10-04 17:47:44 首次发布