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)

np.array转list

x.tolist()

list转tensor

torch.FloatTensor(x)

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

x = torch.unsqueeze(torch.FloatTensor(x), di
  • 15
    点赞
  • 75
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
好的,我可以回答你的问题。首先,你需要导入 PyTorch 库和其他必要的库,例如 pandas 和 numpy。然后,你应该准备你的数据,这里假设你有一个名为 data.csv 的数据集,其中包含分类变量和目标变量。接下来,你可以使用 pandas 库读取 csv 文件并将数据分成输入特征和目标变量。然后,你需要将分类变量转换为数字标签。这可以通过使用 LabelEncoder 类来完成,该类将每个分类变量映射到一个唯一的数字标签。接下来,你需要将数据集分成训练集和测试集。这可以通过使用 train_test_split 函数来完成。最后,你可以使用 PyTorch搭建全连接神经网络。以下是一个示例代码: ```python import torch import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split # 读取数据集 data = pd.read_csv('data.csv') # 分离输入特征和目标变量 X = data.iloc[:, :-1].values y = data.iloc[:, -1].values # 将分类变量转换为数字标签 le = LabelEncoder() for i in range(X.shape[1]): if type(X[0][i]) == str: X[:, i] = le.fit_transform(X[:, i]) # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # 将 numpy 数组转换为 tensor X_train = torch.from_numpy(X_train).float() y_train = torch.from_numpy(y_train).long() X_test = torch.from_numpy(X_test).float() y_test = torch.from_numpy(y_test).long() # 定义全连接神经网络 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 = torch.relu(self.hidden(x)) # 激活函数 x = self.out(x) return x # 定义模型和优化器 net = Net(n_feature=X_train.shape[1], n_hidden=10, n_output=len(np.unique(y_train))) optimizer = torch.optim.SGD(net.parameters(), lr=0.01) loss_func = torch.nn.CrossEntropyLoss() # 训练模型 for epoch in range(100): out = net(X_train) loss = loss_func(out, y_train) optimizer.zero_grad() loss.backward() optimizer.step() # 输出训练误差 if epoch % 10 == 0: print('Epoch: %d | Loss: %.4f' % (epoch, loss.item())) # 测试模型 with torch.no_grad(): out = net(X_test) predictions = torch.argmax(out, axis=1) accuracy = (predictions == y_test).sum() / len(y_test) print('Accuracy:', accuracy) ``` 在这个示例中,我们使用了一个具有一个隐藏层的全连接神经网络。你可以根据你的数据集和需要调整输入特征的数量、隐藏层的大小和输出层的数量。训练模型时,我们使用了交叉熵损失函数和随机梯度下降优化器。测试模型时,我们计算了模型的准确度。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值