import numpy as np
import matplotlib.pyplot as plt
import torch
from torch import nn # 'n'eural 'n'etworks <- PyTorch's building blocks for neural networks
torch.__version__
1. Preparing the dataset
torch.arange(0, 1, 0.02) # array of range
tensor([0.0000, 0.0200, 0.0400, 0.0600, 0.0800, 0.1000, 0.1200, 0.1400, 0.1600, 0.1800, 0.2000, 0.2200, 0.2400, 0.2600, 0.2800, 0.3000, 0.3200, 0.3400, 0.3600, 0.3800, 0.4000, 0.4200, 0.4400, 0.4600, 0.4800, 0.5000, 0.5200, 0.5400, 0.5600, 0.5800, 0.6000, 0.6200, 0.6400, 0.6600, 0.6800, 0.7000, 0.7200, 0.7400, 0.7600, 0.7800, 0.8000, 0.8200, 0.8400, 0.8600, 0.8800, 0.9000, 0.9200, 0.9400, 0.9600, 0.9800])
torch.arange(0, 1, 0.02).reshape(-1, 1) #.shape # 모양을 다시 바꾸다 (like numpy)
torch.arange(0, 1, 0.02).unsqueeze(dim=1) #.shape # index 번호 기준 1번 위치의 차원(2번째 차원)으로 1개 차원을 추가
torch.Size([50, 1])
X = torch.arange(0, 1, 0.02).reshape(-1, 1)
weight = 0.7 # <- 모델이 Gradient descent로 찾아낼 parameter
bias = 0.3 # <- 모델이 Gradient descent로 찾아낼 parameter
y = weight * X + bias
print(X[:5])
print(y[:5])
tensor([[0.0000], [0.0200], [0.0400], [0.0600], [0.0800]]) tensor([[0.3000], [0.3140], [0.3280], [0.3420], [0.3560]])
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,
y,
test_size=0.3,
random_state=42)
def scatter_predictions(X_train=X_train, y_train=y_train,
X_test=X_test, y_test=y_test,
y_predicted=None):
plt.figure(figsize=(10, 7), dpi=100) # figure size & dot per inch
# train data
plt.scatter(X_train, y_train, c="black", s=3, label="Train data") # 산점도 (Scatter plots)
# test data
plt.scatter(X_test, y_test, c="blue", s=10, label="Test data")
if y_predicted is not None:
plt.scatter(X_test, y_predicted, c="red", s=20, label="Predictions")
plt.legend(prop={"size": 14})
scatter_predictions(X_train, y_train, X_test, y_test)

2. Build the model (Linear Regression)