TensorFlow与Pytorch的转换——1简单线性回归

python 复制代码
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 * x_train + b
        loss = tf.reduce_mean(tf.square(y - y_train))
    gradients = tape.gradient(loss, [W, b])
    optimizer.apply_gradients(zip(gradients, [W, b]))

    if (i+1) % 50 == 0:
        print("Epoch [{}/{}], loss: {:.3f}, W: {:.3f}, b: {:.3f}".format(i+1, 1000, loss.numpy(), W.numpy()[0], b.numpy()[0]))

# 预测新数据
x_test = np.array([0.1, 0.2, 0.3], dtype=np.float32)
y_pred = W * x_test + b
print("Predictions:", y_pred.numpy())
import matplotlib.pyplot as plt

# 绘制结果
plt.scatter(x_train, y_train)
plt.plot(x_train, W * x_train + b, c='r')
plt.show()

Pytorch

python 复制代码
import torch
import numpy as np
import matplotlib.pyplot as plt

# 生成随机数据
x_train = torch.from_numpy(np.random.rand(100000).astype(np.float32))
y_train = 0.5 * x_train + 2

# 定义模型参数
W = torch.randn(1, requires_grad=True)
b = torch.zeros(1, requires_grad=True)

# 定义损失函数
loss_fn = torch.nn.MSELoss()

# 定义优化器
optimizer = torch.optim.SGD([W, b], lr=0.5)

# 训练模型
for i in range(100):
    y = W * x_train + b
    loss = loss_fn(y, y_train)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    if (i + 1) % 50 == 0:
        print(f"Epoch [{i + 1}/{100}], loss: {loss.item():.3f}, W: {W.item():.3f}, b: {b.item():.3f}")

# 预测新数据
x_test = torch.tensor([0.1, 0.2, 0.3], dtype=torch.float32)
y_pred = W * x_test + b
print("Predictions:", y_pred.detach().numpy())

# 绘制结果
plt.scatter(x_train.numpy(), y_train.numpy())
plt.plot(x_train.numpy(), (W * x_train + b).detach().numpy(), c='r')
plt.show()
相关推荐
梨子串桃子_28 分钟前
数据挖掘学习笔记:朴素贝叶斯 | Python复现
人工智能·笔记·学习·数学建模·数据挖掘
speedoooo1 小时前
用AI构建小程序需要多久?效果如何?
前端·人工智能·小程序·前端框架
_.Switch1 小时前
深度学习中的迁移学习:预训练模型微调与实践
人工智能·python·深度学习·神经网络·机器学习·迁移学习
OCR_wintone4213 小时前
易泊:精准与高效的车牌识别解决方案
人工智能·深度学习·数码相机·ocr
ACALJJ323 小时前
CUDA:Sobel算子处理
人工智能·opencv·计算机视觉
说私域4 小时前
基于场景的营销:开源AI智能名片S2B2C商城小程序的机遇与挑战
人工智能·小程序
whaosoft-1434 小时前
51c自动驾驶~合集2
人工智能
学步_技术4 小时前
自动驾驶系统研发系列—如何选择适合自动驾驶的激光雷达?从基础到高端全解读
人工智能·机器学习·自动驾驶·激光雷达·lidar
橙意满满的西瓜大侠4 小时前
pytorch导入数据集
人工智能·pytorch·python