-
假设有如下数据集, 如何预测水果产量
假设水果产量与地区无关, 与只与温度, 降雨量, 湿度有关, 若用线性模型预测, 可以通过线性回归的方法, 预测产量。加入线性无关, 通过蓝色方框参数可以求解W1, W2, W3值。 -
根据线性模型, 加入喂入数据权重w, 与偏差值b, 建立线性方程。
yield_apple = w11 * temp + w12 * rainfall + w13 * humidity + b1
yield_orange = w21 * temp + w22 * rainfall + w23 * humidity + b2
降雨量, 温度与苹果参量的关系可能如下图:
通过梯度下降法, 不断喂入数据w, 可以求出理想的w值。
- 引入pytorch 和 numpy
import numpy as np
import torch
- 加入训练数据
# Input (temp, rainfall, humidity)
inputs = np.array([[73, 67, 43],
[91, 88, 64],
[87, 134, 58],
[102, 43, 37],
[69, 96, 70]], dtype='float32')
# Targets (apples, oranges)
targets = np.array([[56, 70],
[81, 101],
[119, 133],
[22, 37],
[103, 119]], dtype='float32')
- 转化 为tensor数据, 因为numpy提取csv文件, tensor训练数据
# Convert inputs and targets to tensors
inputs = torch.from_numpy(inputs)
targets = torch.from_numpy(targets)
print(inputs)
print(targets)
tensor([[ 73., 67., 43.], [ 91., 88., 64.], [ 87., 134., 58.], [102., 43., 37.], [ 69., 96., 70.]]) tensor([[ 56., 70.], [ 81., 101.], [119., 133.], [ 22., 37.], [103., 119.]])
- 建立线性模型:
# Weights and biases
w = torch.randn(2, 3, requires_grad=True)
b