Numpy的使用(超详细,有代码示例)


一个在Python中做科学计算的基础库,重在数值计算,也是大部分PYTHON科学计算库的基础库,多用于在大型、多维数组上执行数值运算

import numpy as np

一、创建ndarray数组

  • NumPy最重要的一个特点就是其N维数组对象(即ndarray),该对象是一个快速而灵活的大数据集容器。你可以利用这种数组整块数据执行一些数学运算,其语法跟标量元素之间的运算一样。
  • 创建ndarray数组函数:
    在这里插入图片描述
  • 创建代码:
import numpy as np;

print ('使用列表生成一维数组')
data = [1,2,3,4,5,6]
x = np.array(data)
print (x) #打印数组
print(x.dtype)  # 打印数组元素的类型

print('使用列表生成二维数组')
data = [[1,2],[3,4],[5,6]]
x = np.array(data)
print(x)  # 打印数组
print(x.ndim)  # 打印数组的维度
print(x.shape)  # 打印数组各个维度的长度。shape是一个元组

print('使用zero/ones/empty创建数组:根据shape来创建')
x = np.zeros(6) #创建一维长度为6的,元素都是0一维数组
print(x)
x = np.zeros((2,3)) #创建一维长度为2,二维长度为3的二维0数组
print(x)
x = np.ones((2,3)) #创建一维长度为2,二维长度为3的二维1数组
print(x)
x = np.empty((3,3)) #创建一维长度为2,二维长度为3,未初始化的二维数组
print(x)

print('使用arrange生成连续元素')
print(np.arange(6))  # [0,1,2,3,4,5,] 开区间
print(np.arange(0, 6, 2))  # [0, 2,4]

二、指定ndarray数组元素的类型

  1. Numpy数据类型
    在这里插入图片描述
    numpy 的数值类型实际上是 dtype 对象的实例,并对应唯一的字符,包括 np.bool_,np.int32,np.float32,等等。
  2. 代码展示:
import numpy as np;

print('生成指定元素类型的数组:设置dtype属性')
x = np.array([1,2.6,3],dtype = np.int64)
print(x)  # 元素类型为int64
print(x.dtype)
x = np.array([1,2,3],dtype = np.float64)
print(x)  # 元素类型为float64
print(x.dtype)

print('使用astype复制数组,并转换类型')
x = np.array([1,2.6,3],dtype = np.float64)
y = x.astype(np.int32)
print(y)  # [1 2 3]
print(x)  # [ 1.   2.6  3. ]
z = y.astype(np.float64)
print(z)  # [ 1.  2.  3.]

print('将字符串元素转换为数值元素')
x = np.array(['1','2','3'],dtype = np.string_)
y = x.astype(np.int32)
print(x)  # ['1' '2' '3']
print(y)  # [1 2 3] 若转换失败会抛出异常

print('使用其他数组的数据类型作为参数')
x = np.array([ 1., 2.6,3. ],dtype = np.float32);
y = np.arange(3,dtype=np.int32);
print(y)  # [0 1 2]
print(y.astype(x.dtype))  # [ 0.  1.  2.]

三、ndarray运算:

  1. 元素级运算
a = np.array([1,2,3,4])
b = np.arange(4)
print(a, b)   # [1 2 3 4] [0 1 2 3]
print(a - b)  # [1 1 1 1]
print(a * b)  #[ 0  2  6 12]
print(a ** 2) #[ 1  4  9 16]
print(2 * np.sin(a))  #[ 1.68294197  1.81859485  0.28224002 -1.51360499]
print(a > 2)  #[False False  True  True]
print(np.exp(a))  # (指数)[ 2.71828183  7.3890561  20.08553692 54.59815003]
  1. 矩阵运算(二维数组)
a = np.array([[1,2],[3,4]]) # 2行2列
b = np.arange(6).reshape((2,3)) # 2行3列
print(a, b)
print(a.dot(b))  # 2行3列

四、ndarray数组的基本索引和切片:

一维数组的索引:与Python的列表索引功能相似
多维数组的索引:

  • arr[r1:r2, c1:c2]
  • arr[1,1] 等价 arr[1][1]
  • [:] 代表某个维度的数据

代码展示:

print('ndarray的基本索引')
x = np.array([[1, 2], [3, 4], [5, 6]])
print(x[0])  # [1,2]
print(x[0][1])  # 2,普通python数组的索引
print(x[0, 1])  # 同x[0][1],ndarray数组的索引
x = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(x[0])  # [[1 2],[3 4]]
y = x[0].copy()  # 生成一个副本
z = x[0]  # 未生成一个副本
print(y)  # [[1 2],[3 4]]
print(y[0, 0])  # 1
y[0, 0] = 0
z[0, 0] = -1
print(y)  # [[0 2],[3 4]]
print(x[0])  # [[-1 2],[3 4]]
print(z)  # [[-1 2],[3 4]]

print('ndarray的切片')
x = np.array([1, 2, 3, 4, 5])
print(x[1:3])  # [2,3] 右边开区间
print(x[:3])  # [1,2,3] 左边默认为 0
print(x[1:])  # [2,3,4,5] 右边默认为元素个数
print(x[0:4:2])  # [1,3] 下标递增2
x = np.array([[1, 2], [3, 4], [5, 6]])
print(x[:2])  # [[1 2],[3 4]]
print(x[:2, :1])  # [[1],[3]]
x[:2, :1] = 0  # 用标量赋值
print(x)  # [[0,2],[0,4],[5,6]]
x[:2, :1] = [[8], [6]]  # 用数组赋值
print(x)  # [[8,2],[6,4],[5,6]]

五、ndarray数组的布尔索引和花式索引

布尔索引:使用布尔数组作为索引。arr[condition],condition为一个条件/多个条件组成的布尔数组。
代码演示:

print('ndarray的布尔型索引')
x = np.array([3, 2, 3, 1, 3, 0])
# 布尔型数组的长度必须跟被索引的轴长度一致
y = np.array([True, False, True, False, True, False])
print(x[y])  # [3,3,3]
print(x[y == False])  # [2,1,0]
print(x >= 3)  # [ True False  True False  True  False]
print(x[~(x >= 3)])  # [2,1,0]
print((x == 2) | (x == 1))  # [False  True False  True False False]
print(x[(x == 2) | (x == 1)])  # [2 1]
x[(x == 2) | (x == 1)] = 0
print(x)  # [3 0 3 0 3 0]

花式索引:使用整型数组作为索引
代码演示:

print('ndarray的花式索引:使用整型数组作为索引')
x = np.array([1, 2, 3, 4, 5, 6])
print(x[[0, 1, 2]])  # [1 2 3]
print(x[[-1, -2, -3]])  # [6,5,4]
x = np.array([[1, 2], [3, 4], [5, 6]])
print(x[[0, 1]])  # [[1,2],[3,4]]
print(x[[0, 1], [0, 1]])  # [1,4] 打印x[0][0]和x[1][1]
print(x[[0, 1]][:, [0, 1]])  # 打印01行的01列 [[1,2],[3,4]]
# 使用np.ix_()函数增强可读性
print(x[np.ix_([0, 1], [0, 1])])  # 同上 打印01行的01列 [[1,2],[3,4]]
x[[0, 1], [0, 1]] = [0, 0]
print(x)  # [[0,2],[3,0],[5,6]]

六、ndarray数组的转置和轴对换

数组的转置/轴对换只会返回源数据的一个视图,不会对源数据进行修改。

代码示例:

print('ndarray数组的转置和轴对换')
k = np.arange(9)  # [0,1,....8]
m = k.reshape((3, 3))  # 改变数组的shape复制生成2维的,每个维度长度为3的数组
print(k)  # [0 1 2 3 4 5 6 7 8]
print(m)  # [[0 1 2] [3 4 5] [6 7 8]]
# 转置(矩阵)数组:T属性 : mT[x][y] = m[y][x]
print(m.T)  # [[0 3 6] [1 4 7] [2 5 8]]
# 计算矩阵的内积 xTx
print(np.dot(m, m.T))  # np.dot点乘
# 高维数组的轴对象
k = np.arange(8).reshape(2, 2, 2)
print(k)  # [[[0 1],[2 3]],[[4 5],[6 7]]]
print(k[1][0][0])
# 轴变换 transpose 参数:由轴编号组成的元组
m = k.transpose((1, 0, 2))  # m[y][x][z] = k[x][y][z]
print(m)  # [[[0 1],[4 5]],[[2 3],[6 7]]]
print(m[0][1][0])
# 轴交换 swapaxes (axes:轴),参数:一对轴编号
m = k.swapaxes(0, 1)  # 将第一个轴和第二个轴交换 m[y][x][z] = k[x][y][z]
print(m)  # [[[0 1],[4 5]],[[2 3],[6 7]]]
print(m[0][1][0])
# 使用轴交换进行数组矩阵转置
m = np.arange(9).reshape((3, 3))
print(m)  # [[0 1 2] [3 4 5] [6 7 8]]
print(m.swapaxes(1, 0))  # [[0 3 6] [1 4 7] [2 5 8]]

七、ndarray通用函数

7.1一元ufunc:

在这里插入图片描述
一元ufunc代码示例:

print('一元ufunc示例')
x = np.arange(6)
print(x)  # [0 1 2 3 4 5]
print(np.square(x))  # [ 0  1  4  9 16 25]
x = np.array([1.5, 1.6, 1.7, 1.8])
y, z = np.modf(x)  #将数组的小数和整数部分以两个独立数组的形式返回
print(y)  # [ 0.5  0.6  0.7  0.8]
print(z)  # [ 1.  1.  1.  1.]

7.2二元ufunc:

在这里插入图片描述二元ufunc代码示例:

print('二元ufunc示例')
x = np.array([[1, 4], [6, 7]])
y = np.array([[2, 3], [5, 8]])
print(np.maximum(x, y))  # [[2,4],[6,8]]
print(np.minimum(x, y))  # [[1,3],[5,7]]

7.3NumPy的where函数使用:

np.where(condition, x, y),第一个参数为一个布尔数组,第二个参数和第三个参数可以是标量也可以是数组。
即 :满足条件(condition),输出x,不满足输出y。
代码演示:

print('where函数的使用')
cond = np.array([True, False, True, False])
x = np.where(cond, -2, 2)
print(x)  # [-2  2 -2  2]
cond = np.array([1, 2, 3, 4])
x = np.where(cond > 2, -2, 2)
print(x)  # [ 2  2 -2 -2]
y1 = np.array([-1, -2, -3, -4])
y2 = np.array([1, 2, 3, 4])
x = np.where(cond > 2, y1, y2)  # 长度须匹配
print(x)  # [1,2,-3,-4]

print('where函数的嵌套使用')
y1 = np.array([-1, -2, -3, -4, -5, -6])
y2 = np.array([1, 2, 3, 4, 5, 6])
y3 = np.zeros(6)
cond = np.array([1, 2, 3, 4, 5, 6])
x = np.where(cond > 5, y3, np.where(cond > 2, y1, y2))
print(x)  # [ 1.  2. -3. -4. -5.  0.]

八、ndarray常用的统计方法

  • 可以通过这些基本统计方法对整个数组/某个轴的数据进行统计计算。
    在这里插入图片描述
    代码示例:
print('np的基本统计方法')
x = np.array([[1, 2], [3, 3], [1, 2]])  # 同一维度上的数组长度须一致
print(x.mean())  # 2
print(x.mean(axis=1))  # 对每一行的元素求平均
print(x.mean(axis=0))  # 对每一列的元素求平均
print(x.sum())  # 同理 12
print(x.sum(axis=1))  # [3 6 3]
print(x.max())  # 3
print(x.max(axis=1))  # [2 3 2]
print(x.cumsum())  # [ 1  3  6  9 10 12]
print(x.cumprod())  # [ 1  2  6 18 18 36]

用于布尔数组的统计方法:

  • sum : 统计数组/数组某一维度中的True的个数
  • any: 统计数组/数组某一维度中是否存在一个/多个True
  • all:统计数组/数组某一维度中是否都是True
    代码示例:
print('用于布尔数组的统计方法')
x = np.array([[True, False], [True, False]])
print(x.sum())  # 2
print(x.sum(axis=1))  # [1,1]
print(x.any(axis=0))  # [True,False]
print(x.all(axis=1))  # [False,False]

使用sort对数组/数组某一维度进行就地排序(会修改数组本身)。

代码示例:

print('.sort的就地排序')
x = np.array([[1, 6, 2], [6, 1, 3], [1, 5, 2]])
x.sort(axis=1)
print(x)  # [[1 2 6] [1 3 6] [1 2 5]]
# 非就地排序:np.sort()可产生数组的副本

九、ndarray数组的去重以及集合运算

在这里插入图片描述代码示例:(方法返回类型为一维数组(1d))

print('ndarray的唯一化和集合运算')
x = np.array([[1, 6, 2], [6, 1, 3], [1, 5, 2]])
print(np.unique(x))  # [1,2,3,5,6]
y = np.array([1, 6, 5])
print(np.in1d(x, y))  # [ True  True False  True  True False  True  True False]
print(np.setdiff1d(x, y))  # [2 3]
print(np.intersect1d(x, y))  # [1 5 6]

十、numpy中的线性代数

import numpy.linalg   #线性代数(linear algebra)

常用的numpy.linalg模块函数:
在这里插入图片描述
代码示例:

print('线性代数')
import numpy.linalg as nla

print('矩阵点乘')
x = np.array([[1, 2], [3, 4]])
y = np.array([[1, 3], [2, 4]])
print(x.dot(y))  # [[ 5 11][11 25]]
print(np.dot(x, y))  # # [[ 5 11][11 25]]
print('矩阵求逆')
x = np.array([[1, 1], [1, 2]])
y = nla.inv(x)  # 矩阵求逆(若矩阵的逆存在)
print(x.dot(y))  # 单位矩阵 [[ 1.  0.][ 0.  1.]]
print(nla.det(x))  # 求行列式

十一、numpy中的随机数生成

在这里插入图片描述
代码示例:

import numpy as np
a=np.random.randint(0,10,100)#范围内的整数
print(a)
b=np.random.rand(40)#0到1的均匀分布
print(b)
c=np.random.randn(10)#标准正态分布
print(c)
d=np.random.normal(0,1,100)#生成指定正态分布
print(d)
e=np.random.random(20)#0到1的均匀分布
print(e)
f=np.random.ranf(20)#0到1的均匀分布
print(f)
g=np.random.uniform(-1,1,100)#指定均匀分布
print(g)

十二、ndarray数组重塑

代码示例:

print('ndarray数组重塑')
x = np.arange(0, 6)  # [0 1 2 3 4]
print(x)  # [0 1 2 3 4]
print(x.reshape((2, 3)))  # [[0 1 2][3 4 5]]
print(x)  # [0 1 2 3 4]
print(x.reshape((2, 3)).reshape((3, 2)))  # [[0 1][2 3][4 5]]
y = np.array([[1, 1, 1], [1, 1, 1]])
x = x.reshape(y.shape)
print(x)  # [[0 1 2][3 4 5]]
print(x.flatten())  # [0 1 2 3 4 5]
x.flatten()[0] = -1  # flatten返回的是拷贝
print(x)  # [[0 1 2][3 4 5]]
print(x.ravel())  # [0 1 2 3 4 5]
x.ravel()[0] = -1  # ravel返回的是视图(引用) 
print(x)  # [[-1 1 2][3 4 5]]
print("维度大小自动推导")
arr = np.arange(15)
print(arr.reshape((5, -1)))  # 15 / 5 = 3

十三、ndarray数组的拆分与合并

在这里插入图片描述
代码示例:

print('数组的合并与拆分')
x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.array([[7, 8, 9], [10, 11, 12]])
print(np.concatenate([x, y], axis=0))
# 竖直组合 [[ 1  2  3][ 4  5  6][ 7  8  9][10 11 12]]
print(np.concatenate([x, y], axis=1))
# 水平组合 [[ 1  2  3  7  8  9][ 4  5  6 10 11 12]]
print('垂直stack与水平stack')
print(np.vstack((x, y)))  # 垂直堆叠:相对于垂直组合
print(np.hstack((x, y)))  # 水平堆叠:相对于水平组合
# dstack:按深度堆叠
print(np.split(x, 2, axis=0))
# 按行分割 [array([[1, 2, 3]]), array([[4, 5, 6]])]
print(np.split(x, 3, axis=1))
# 按列分割 [array([[1],[4]]), array([[2],[5]]), array([[3],[6]])]

# 堆叠辅助类

arr = np.arange(6)
arr1 = arr.reshape((3, 2))
arr2 = np.random.randn(3, 2)
print('r_用于按行堆叠')
print(np.r_[arr1, arr2])
'''
[[ 0.          1.        ]
 [ 2.          3.        ]
 [ 4.          5.        ]
 [ 0.22621904  0.39719794]
 [-1.2201912  -0.23623549]
 [-0.83229114 -0.72678578]]
'''
print('c_用于按列堆叠')
print(np.c_[np.r_[arr1, arr2], arr])
'''
[[ 0.          1.          0.        ]
 [ 2.          3.          1.        ]
 [ 4.          5.          2.        ]
 [ 0.22621904  0.39719794  3.        ]
 [-1.2201912  -0.23623549  4.        ]
 [-0.83229114 -0.72678578  5.        ]]
'''
print('切片直接转为数组')
print(np.c_[1:6, -10:-5])
'''
[[  1 -10]
 [  2  -9]
 [  3  -8]
 [  4  -7]
 [  5  -6]]
'''

十四、数组的元素重复操作

代码示例:

print('数组的元素重复操作')
x = np.array([[1, 2], [3, 4]])
print(x.repeat(2))  # 按元素重复 [1 1 2 2 3 3 4 4]
print(x.repeat(2, axis=0))  # 按行重复 [[1 2][1 2][3 4][3 4]]
print(x.repeat(2, axis=1))  # 按列重复 [[1 1 2 2][3 3 4 4]]
x = np.array([1, 2])
print(np.tile(x, 2))  # tile瓦片:[1 2 1 2]
print(np.tile(x, (2, 2)))  # 指定从低维到高维依次复制的次数。
# [[1 2 1 2][1 2 1 2]]

参考文档:

一.
https://blog.csdn.net/cxmscb/article/details/54583415?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task
二.
https://blog.csdn.net/erchouchou/article/details/102657061?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522158364520319195162560022%2522%252C%2522scm%2522%253A%252220140713.130056874…%2522%257D&request_id=158364520319195162560022&biz_id=0&utm_source=distribute.pc_search_result.none-task

https://blog.csdn.net/fu6543210/article/details/83240024?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

下面是使用麻雀搜索算法优化LSTM股票预测模型参数的示例代码: ```python import random import numpy as np import pandas as pd import torch import torch.nn as nn import torch.optim as optim from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error # 定义LSTM模型 class LSTM(nn.Module): def __init__(self, input_size, hidden_size, num_layers, output_size, dropout): super(LSTM, self).__init__() self.hidden_size = hidden_size self.num_layers = num_layers self.dropout = dropout self.lstm = nn.LSTM(input_size, hidden_size, num_layers, dropout=dropout) self.fc = nn.Linear(hidden_size, output_size) def forward(self, x): h0 = torch.zeros(self.num_layers, x.size(1), self.hidden_size).to(x.device) c0 = torch.zeros(self.num_layers, x.size(1), self.hidden_size).to(x.device) out, _ = self.lstm(x, (h0, c0)) out = self.fc(out[-1, :, :]) return out # 数据预处理 def prepare_data(data, seq_len): data = np.array(data) scaler = MinMaxScaler() data = scaler.fit_transform(data.reshape(-1, 1)).reshape(-1) x = [] y = [] for i in range(len(data) - seq_len): x.append(data[i:i+seq_len]) y.append(data[i+seq_len]) x = np.array(x).reshape(-1, seq_len, 1) y = np.array(y).reshape(-1, 1) return x, y, scaler # 训练模型 def train_model(x_train, y_train, x_val, y_val, params): input_size = 1 hidden_size = params['hidden_size'] num_layers = params['num_layers'] output_size = 1 dropout = params['dropout'] learning_rate = params['learning_rate'] batch_size = params['batch_size'] num_epochs = 100 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model = LSTM(input_size, hidden_size, num_layers, output_size, dropout).to(device) criterion = nn.MSELoss() optimizer = optim.Adam(model.parameters(), lr=learning_rate) train_loss = [] val_loss = [] for epoch in range(num_epochs): model.train() for i in range(0, len(x_train), batch_size): x_batch = torch.FloatTensor(x_train[i:i+batch_size]).to(device) y_batch = torch.FloatTensor(y_train[i:i+batch_size]).to(device) optimizer.zero_grad() output = model(x_batch) loss = criterion(output, y_batch) loss.backward() optimizer.step() train_loss.append(loss.item()) model.eval() with torch.no_grad(): x_val_batch = torch.FloatTensor(x_val).to(device) y_val_batch = torch.FloatTensor(y_val).to(device) val_output = model(x_val_batch) val_loss.append(criterion(val_output, y_val_batch).item()) return model, train_loss, val_loss # 预测并计算适应度 def predict_and_fitness(model, x_test, y_test, scaler): device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model.eval() with torch.no_grad(): x_test_batch = torch.FloatTensor(x_test).to(device) y_test_batch = torch.FloatTensor(y_test).to(device) output = model(x_test_batch) y_pred = scaler.inverse_transform(output.cpu().numpy()) y_true = scaler.inverse_transform(y_test_batch.cpu().numpy()) fitness = 1 / np.sqrt(mean_squared_error(y_true, y_pred)) return fitness # 麻雀搜索算法 def sparrow_search(data, seq_len): # 定义参数搜索空间 hidden_size_list = [16, 32, 64, 128] num_layers_list = [1, 2, 3] dropout_list = [0, 0.1, 0.2, 0.3] learning_rate_list = [0.001, 0.01, 0.1] batch_size_list = [32, 64, 128] # 定义搜索次数和停止条件 max_iter = 100 stop_fitness = 0.95 # 随机初始化参数组合 best_params = {} best_fitness = 0 for param in ['hidden_size', 'num_layers', 'dropout', 'learning_rate', 'batch_size']: best_params[param] = random.choice(eval(param+'_list')) # 开始搜索 for i in range(max_iter): # 划分训练集、验证集和测试集 train_size = int(len(data) * 0.7) val_size = int(len(data) * 0.2) test_size = len(data) - train_size - val_size train_data = data[:train_size] val_data = data[train_size:train_size+val_size] test_data = data[train_size+val_size:] # 数据预处理 x_train, y_train, scaler = prepare_data(train_data, seq_len) x_val, y_val, _ = prepare_data(val_data, seq_len) x_test, y_test, _ = prepare_data(test_data, seq_len) # 训练模型并计算适应度 model, train_loss, val_loss = train_model(x_train, y_train, x_val, y_val, best_params) fitness = predict_and_fitness(model, x_test, y_test, scaler) # 更新最优参数组合 if fitness > best_fitness: best_fitness = fitness print('Iteration %d, best fitness: %.4f' % (i+1, best_fitness)) best_model = model best_scaler = scaler # 判断是否达到停止条件 if best_fitness >= stop_fitness: print('Search stopped, best fitness: %.4f' % best_fitness) break # 随机选取一组参数组合,并更新搜索空间 new_params = {} for param in ['hidden_size', 'num_layers', 'dropout', 'learning_rate', 'batch_size']: new_params[param] = random.choice(eval(param+'_list')) if new_params[param] != best_params[param]: eval(param+'_list').append(best_params[param]) eval(param+'_list').remove(new_params[param]) best_params = new_params # 在测试集上输出预测结果和真实值 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') best_model.eval() with torch.no_grad(): x_test_batch = torch.FloatTensor(x_test).to(device) y_test_batch = torch.FloatTensor(y_test).to(device) output = best_model(x_test_batch) y_pred = best_scaler.inverse_transform(output.cpu().numpy()) y_true = best_scaler.inverse_transform(y_test_batch.cpu().numpy()) result = pd.DataFrame({'y_true': y_true.reshape(-1), 'y_pred': y_pred.reshape(-1)}) print(result) return best_model, best_scaler ``` 其中,`data`为股票价格序列,`seq_len`为序列长度。在`sparrow_search`函数中,先根据参数搜索空间定义初始的参数组合,然后不断使用麻雀搜索算法在搜索空间中随机采样一组参数组合,并训练LSTM模型。每次训练后,在测试集上计算适应度,并更新最优参数组合。如果达到停止条件,则停止搜索,返回最优的LSTM模型和数据归一化器。最后,在测试集上输出预测结果和真实值。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhangbw~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值