# handmail/pytorch-464a3

2 years ago

PyTorch进阶之路（二）：如何实现线性回归

https://new.qq.com/omn/20190315/20190315A093SV.html

yield_apple = w11 * temp + w12 * rainfall + w13 * humidity + b1

yield_orange = w21 * temp + w22 * rainfall + w23 * humidity + b2

In [2]:
``````import torch
import numpy as np``````
In [20]:
``````#input (temp温度 , rainfall降雨量,  humidity湿度 )
inputs = np.array([[73, 67, 43],[91, 88, 64],[87, 134, 58],[102, 43, 37], [69, 96, 70]], dtype='float32')
inputs
``````
Out[20]:
``````array([[ 73.,  67.,  43.],
[ 91.,  88.,  64.],
[ 87., 134.,  58.],
[102.,  43.,  37.],
[ 69.,  96.,  70.]], dtype=float32)``````
In [22]:
``````#target(apples, oranges)
targets = np.array([[56,70],
[81,101],
[119, 133],
[22, 37],
[103, 119]], dtype='float32')
targets
``````
Out[22]:
``````array([[ 56.,  70.],
[ 81., 101.],
[119., 133.],
[ 22.,  37.],
[103., 119.]], dtype=float32)``````

In [26]:
``````# 转为 tensor
inputs_t = torch.from_numpy(inputs)
targets_t = torch.from_numpy(targets)
print(inputs_t)
print(targets_t)
``````
```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.]]) ```

In [28]:
``````# weights and biases
In [29]:
``````print(w)
print(b)
``````
```tensor([[ 1.9030, 2.2653, -1.5373], [ 1.3533, -1.3740, 0.1822]], requires_grad=True) tensor([-1.1660, 0.6701], requires_grad=True) ```

torch.randn 会创建一个给定形状的张量，其中的元素随机选取自一个均值为 0 且标准差为 1 的正态分布。

x * w(转置) + b

In [38]:
``````def model(x):
return np.dot(x, w.t()) + b # @ 表示 PyTorch 中的矩阵乘法，.t 方法会返回一个张量的转置。``````
In [39]:
``````# Generate predictions 产生预测
preds = model(inputs)
``````
```--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-39-15c71d28351e> in <module> 1 # Generate predictions 产生预测 ----> 2 preds = model(inputs) <ipython-input-38-2cd9b022d660> in model(x) 1 def model(x): ----> 2 return np.dot(x, w.t()) + b # @ 表示 PyTorch 中的矩阵乘法，.t 方法会返回一个张量的转置。 /export/apps/anaconda3/lib/python3.7/site-packages/torch/tensor.py in __array__(self, dtype) 456 def __array__(self, dtype=None): 457 if dtype is None: --> 458 return self.numpy() 459 else: 460 return self.numpy().astype(dtype, copy=False) RuntimeError: Can't call numpy() on Variable that requires grad. Use var.detach().numpy() instead.```
In [ ]:
``````import jovian #[ˈdʒəʊvɪən] 木星
jovian.commit()
``````
```[jovian] Saving notebook.. ```
In [ ]:
`` ``