data_x_float.append( list(map(float, i)))
时间: 2024-05-29 22:14:51 浏览: 143
这行代码是将一个列表中的元素转换为浮点数,然后将转换后的浮点数作为新的列表元素添加到另一个列表中。具体解释如下:
- `list(map(float, i))`:将列表 `i` 中的每个元素都转换为浮点数,并返回一个包含这些浮点数的列表。
- `data_x_float.append()`:将转换后的浮点数列表作为一个元素添加到列表 `data_x_float` 的末尾。
整个代码的作用是将一个包含多个列表的列表 `data_x` 中的每个列表中的元素都转换为浮点数,并将转换后的浮点数列表作为新的列表元素添加到另一个列表 `data_x_float` 中。
相关问题
import numpy import numpy as np import matplotlib.pyplot as plt import math import torch from torch import nn from torch.utils.data import DataLoader, Dataset import os os.environ['KMP_DUPLICATE_LIB_OK']='True' dataset = [] for data in np.arange(0, 3, .01): data = math.sin(data * math.pi) dataset.append(data) dataset = np.array(dataset) dataset = dataset.astype('float32') max_value = np.max(dataset) min_value = np.min(dataset) scalar = max_value - min_value print(scalar) dataset = list(map(lambda x: x / scalar, dataset)) def create_dataset(dataset, look_back=3): dataX, dataY = [], [] for i in range(len(dataset) - look_back): a = dataset[i:(i + look_back)] dataX.append(a) dataY.append(dataset[i + look_back]) return np.array(dataX), np.array(dataY) data_X, data_Y = create_dataset(dataset) train_X, train_Y = data_X[:int(0.8 * len(data_X))], data_Y[:int(0.8 * len(data_Y))] test_X, test_Y = data_Y[int(0.8 * len(data_X)):], data_Y[int(0.8 * len(data_Y)):] train_X = train_X.reshape(-1, 1, 3).astype('float32') train_Y = train_Y.reshape(-1, 1, 3).astype('float32') test_X = test_X.reshape(-1, 1, 3).astype('float32') train_X = torch.from_numpy(train_X) train_Y = torch.from_numpy(train_Y) test_X = torch.from_numpy(test_X) class RNN(nn.Module): def __init__(self, input_size, hidden_size, output_size=1, num_layer=2): super(RNN, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.output_size = output_size self.num_layer = num_layer self.rnn = nn.RNN(input_size, hidden_size, batch_first=True) self.linear = nn.Linear(hidden_size, output_size) def forward(self, x): out, h = self.rnn(x) out = self.linear(out[0]) return out net = RNN(3, 20) criterion = nn.MSELoss(reduction='mean') optimizer = torch.optim.Adam(net.parameters(), lr=1e-2) train_loss = [] test_loss = [] for e in range(1000): pred = net(train_X) loss = criterion(pred, train_Y) optimizer.zero_grad() # 反向传播 loss.backward() optimizer.step() if (e + 1) % 100 == 0: print('Epoch:{},loss:{:.10f}'.format(e + 1, loss.data.item())) train_loss.append(loss.item()) plt.plot(train_loss, label='train_loss') plt.legend() plt.show()请适当修改代码,并写出预测值和真实值的代码
以下是适当修改后的代码以及预测值和真实值的代码:
```
import numpy as np
import matplotlib.pyplot as plt
import math
import torch
from torch import nn
from torch.utils.data import DataLoader, Dataset
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
dataset = []
for data in np.arange(0, 3, .01):
data = math.sin(data * math.pi)
dataset.append(data)
dataset = np.array(dataset)
dataset = dataset.astype('float32')
max_value = np.max(dataset)
min_value = np.min(dataset)
scalar = max_value - min_value
print(scalar)
dataset = list(map(lambda x: x / scalar, dataset))
def create_dataset(dataset, look_back=3):
dataX, dataY = [], []
for i in range(len(dataset) - look_back):
a = dataset[i:(i + look_back)]
dataX.append(a)
dataY.append(dataset[i + look_back])
return np.array(dataX), np.array(dataY)
data_X, data_Y = create_dataset(dataset)
train_X, train_Y = data_X[:int(0.8 * len(data_X))], data_Y[:int(0.8 * len(data_Y))]
test_X, test_Y = data_Y[int(0.8 * len(data_X)):], data_Y[int(0.8 * len(data_Y)):]
train_X = train_X.reshape(-1, 1, 3).astype('float32')
train_Y = train_Y.reshape(-1, 1, 1).astype('float32')
test_X = test_X.reshape(-1, 1, 3).astype('float32')
train_X = torch.from_numpy(train_X)
train_Y = torch.from_numpy(train_Y)
test_X = torch.from_numpy(test_X)
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size=1, num_layer=2):
super(RNN, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_size
self.num_layer = num_layer
self.rnn = nn.RNN(input_size, hidden_size, batch_first=True)
self.linear = nn.Linear(hidden_size, output_size)
def forward(self, x):
out, h = self.rnn(x)
out = self.linear(out[:, -1, :])
return out
net = RNN(3, 20)
criterion = nn.MSELoss(reduction='mean')
optimizer = torch.optim.Adam(net.parameters(), lr=1e-2)
train_loss = []
test_loss = []
for e in range(1000):
pred = net(train_X)
loss = criterion(pred, train_Y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (e + 1) % 100 == 0:
print('Epoch:{},loss:{:.10f}'.format(e + 1, loss.data.item()))
train_loss.append(loss.item())
plt.plot(train_loss, label='train_loss')
plt.legend()
plt.show()
# 预测值和真实值的代码
net.eval()
pred_test = net(test_X)
pred_test = pred_test.detach().numpy() * scalar
test_Y = test_Y.reshape(-1, 1) * scalar
plt.plot(pred_test, label='predict')
plt.plot(test_Y, label='true')
plt.legend()
plt.show()
```
import numpy as np import matplotlib.pyplot as plt import math import torch from torch import nn import pdb from torch.autograd import Variable import os os.environ['KMP_DUPLICATE_LIB_OK']='True' dataset = [] for data in np.arange(0, 3, .01): data = math.sin(data * math.pi) dataset.append(data) dataset = np.array(dataset) dataset = dataset.astype('float32') max_value = np.max(dataset) min_value = np.min(dataset) scalar = max_value - min_value dataset = list(map(lambda x: x / scalar, dataset)) def create_dataset(dataset, look_back=3): dataX, dataY = [], [] for i in range(len(dataset) - look_back): a = dataset[i:(i + look_back)] dataX.append(a) dataY.append(dataset[i + look_back]) return np.array(dataX), np.array(dataY) data_X, data_Y = create_dataset(dataset) # 对训练集测试集划分,划分比例0.8 train_X, train_Y = data_X[:int(0.8 * len(data_X))], data_Y[:int(0.8 * len(data_Y))] test_X, test_Y = data_Y[int(0.8 * len(data_X)):], data_Y[int(0.8 * len(data_Y)):] train_X = train_X.reshape(-1, 1, 3).astype('float32') train_Y = train_Y.reshape(-1, 1, 3).astype('float32') test_X = test_X.reshape(-1, 1, 3).astype('float32') class RNN(nn.Module): def __init__(self, input_size, hidden_size, output_size=1, num_layer=2): super(RNN, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.output_size = output_size self.num_layer = num_layer self.rnn = nn.RNN(input_size, hidden_size, batch_first=True) self.linear = nn.Linear(hidden_size, output_size) def forward(self, x): # 补充forward函数 out, h = self.rnn(x) out = self.linear(out[0]) # print("output的形状", out.shape) return out net = RNN(3, 20) criterion = nn.MSELoss(reduction='mean') optimizer = torch.optim.Adam(net.parameters(), lr=1e-2) train_loss = [] test_loss = [] for e in range(1000): pred = net(train_X) loss = criterion(pred, train_Y) optimizer.zero_grad() # 反向传播 loss.backward() optimizer.step() if (e + 1) % 100 == 0: print('Epoch:{},loss:{:.10f}'.format(e + 1, loss.data.item())) train_loss.append(loss.item()) plt.plot(train_loss, label='train_loss') plt.legend() plt.show()画出预测值真实值图
抱歉,我作为一个语言模型,无法在这里画图。不过,你可以通过以下代码来画出预测值和真实值的图:
```
net.eval()
train_predict = net(data_X)
data_predict = train_predict.data.numpy()
dataY_plot = data_Y.reshape(-1)
data_predict_plot = data_predict.reshape(-1)
plt.plot(dataY_plot, label='real')
plt.plot(data_predict_plot, label='predict')
plt.legend()
plt.show()
```
阅读全文