赞
踩
In this part of this exercise, you will implement linear regression with one
variable to predict profits for a food truck. Suppose you are the CEO of a
restaurant franchise and are considering different cities for opening a new
outlet. The chain already has trucks in various cities and you have data for
profits and populations from the cities.
You would like to use this data to help you select which city to expand
to next.
The file ex1data1.txt contains the dataset for our linear regression prob-
lem. The first column is the population of a city and the second column is
the profit of a food truck in that city. A negative value for profit indicates a
loss.
截图看一下:
torch中默认的数据类型都是tensor,但读取CSV文件的时候读取的格式为dataframe(单列为series)
抽取第一列作为x(population),第二列作为y(profit),转化顺序为
series -> np.array -> list ->tensor
转化用到的函数:
series转np.array
np.array(x)
np.array转list
x.tolist()
list转tensor
torch.FloatTensor(x)
注意这个时候如果输出x.shape的话,结果为torch.Size([97])
我们要把它转化为97x1的数据:
x = torch.unsqueeze(torch.FloatTensor(x), dim=1)
完整代码如下:
import pandas as pd import torch import torch.nn.functional as F import numpy as np df = pd.read_csv(r'D:\Wu-Enda\code\ex1-linear regression\ex1data1.txt', names=['population', 'profit']) # 读取数据并赋予列名 print(type(df)) # <class 'pandas.core.frame.DataFrame'> x = df['population'] print(type(x)) # <class 'pandas.core.series.Series'> x = np.array(x) print(type(x)) # <class 'numpy.ndarray'> x = x.tolist() print(type(x)) # <class 'list'> x = torch.unsqueeze(torch.FloatTensor(x), dim=1) print(type(x)) # <class 'torch.Tensor'> print(x.shape) # torch.Size([97, 1]) y = df['profit'] y = np.array(y) y = torch.unsqueeze(torch.FloatTensor(y), dim=1) print(type(y)) # <class 'torch.Tensor'> print(y.shape) # torch.Size([97, 1])
class Net(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_output): super(Net, self).__init__() self.hidden = torch.nn.Linear(n_feature, n_hidden) self.out = torch.nn.Linear(n_hidden, n_output) def forward(self, x): x = F.relu(self.hidden(x)) x = self.out(x) return x net = Net(1, 10, 1) print(net) optimizer = torch.optim.Adam(net.parameters(), lr=0.5) loss_func = torch.nn.MSELoss() # 均方差 for t in range(100): prediction = net(x) loss = loss_func(prediction, y) # 一定要prediction在前, y在后 optimizer.zero_grad() # 梯度降零 loss.backward() optimizer.step() if t % 5 == 0: # plot and show learning process plt.cla() plt.scatter(x.data.numpy(), y.data.numpy()) plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5) plt.text(0.5, 0, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color': 'red'}) plt.pause(0.1) plt.ioff() plt.show()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。