栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

✨Pytorch 基础 4 -- Linear Regression

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

✨Pytorch 基础 4 -- Linear Regression

目录

code

写在最后


code
import torch
import torch.nn as nn
from sklearn import datasets
import matplotlib.pyplot as plt

# 0) prepare data
x_numpy, y_numpy = datasets.make_regression(n_samples = 100, n_features = 1, noise =20, randome_state =1)
X = torch.from_numpy(X_numpy.astype(np.float32))
y = torch.from_numpy(y_numpy.astype(np.float32))
y = y.view(y.shape[0], 1) # reshape data into a column vector

n_samples, n_features = X.shape

# 1) model
input_size = n_features
output_size = 1
model = nn.Linear(input_size, output_size)

# 2) loss and optimizer 
learning_rate = 0.01
criterion = nn.MSE()
optimizer = torch.optim.SGD(criterion.parameters(), lr = learning_rate)

# 3) training loop
num_epochs = 100
for epoch in range(num_epochs):
	# forward pass and loss calculation
	y_pre = model(X)
	loss = criterion(y_pre, y)
	# backward pass, this step will sum up accumulated weights
	loss.backward()
	# update
	optimizer.step()
	optimizer.zero_grad()
	
	if (epoch + 1) % 10 == 0:
		print(f"epoch: {epoch +1}, loss = {loss.item():.4f}")

# now this model is the final mode
	
predicted = model(X).detach().numpy()  # generate a new tensor and gradient configuration is faulse
plt.plot(x_numpy, y_numpy, "ro")
plt.plot(x_numpy, predicted, "b")
plt.show()

写在最后

此系列为以下Youtube视频教程的课程笔记

https://www.youtube.com/watch?v=c36lUUr864M&t=12157shttps://www.youtube.com/watch?v=c36lUUr864M&t=12157s

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/350655.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号