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()
相关推荐
DevOpenClub1 天前
用 Agent 搭建网页内容采集与结构化处理流水线
人工智能
56AI1 天前
2026 企业级AI智能体开发平台推荐:聚焦底层安全与准确率的智能体平台
人工智能·安全·智能体
沫儿笙1 天前
库卡弧焊机器人白车身焊接节气装置
人工智能·机器人
AI智图坊1 天前
多件装组合SKU图的批量生产效率分析:从PS手工到AI自动化的工作流改造
大数据·运维·人工智能·gpt·ai作画·自动化·aigc
threelab1 天前
Three.js 物理模拟着色器 | 三维可视化 / AI 提示词
开发语言·前端·javascript·人工智能·3d·着色器
RSTJ_16251 天前
PYTHON+AI LLM DAY SEVENTY-ONE
人工智能
圣殿骑士-Khtangc1 天前
单智能体落地实战:从 ReAct 到 Production-Ready AI Agent 全链路解析
人工智能·react.js
云烟成雨TD1 天前
Spring AI 1.x 系列【56】用大模型评判大模型:递归顾问实现自动化评估方案
人工智能·spring·自动化
AI客栈1 天前
K8s 自定义控制器中 WorkQueue 队列优化实践:基于 IPVS 转发原理的状态变化处理
人工智能
0xR3lativ1ty1 天前
每周AI工具新动态
人工智能