当前位置:   article > 正文

pytorch入门:读取CSV文件并自己搭建一个回归神经网络_pytorch读取csv

pytorch读取csv

原始数据

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)
  • 1

np.array转list

x.tolist()
  • 1

list转tensor

torch.FloatTensor(x)
  • 1

注意这个时候如果输出x.shape的话,结果为torch.Size([97])
我们要把它转化为97x1的数据:

x = torch.unsqueeze(torch.FloatTensor(x), dim=1)
  • 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])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

搭建神经网络(来源:B站莫烦)

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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/103766?site
推荐阅读
相关标签
  

闽ICP备14008679号