np.zeros()思考

本文通过实例展示了如何使用NumPy创建二维数组,并进行基本的数组操作与矩阵运算,包括选取特定行或列的数据、矩阵乘法及转置运算等。文章还探讨了矩阵与零向量相乘时的维度匹配原则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

U = np.array([[1,2,3,4],[3,4,5,6]],dtype=np.int32)
#第一列的值
print U[:,0]
#第一行的值
print U[0,:]
#第一行中的第一个的值
print U[0,0:1]
O = np.zeros(4)
print O
D = U.dot(O)#U的shape是(2,4),O的shape是(4,),O与U的列保持一致
print D   #D.shape是(2,)
M = U[:,0]+D
print M #M的shape是(2,)
print U.transpose().dot(M) #U.transpose()的shape是(4,2)
[1 3]
[1 2 3 4]
[1]
[ 0.  0.  0.  0.]
[ 0.  0.]
[ 1.  3.]
[ 10.  14.  18.  22.]

思考:矩阵与np.zeros(常数)相乘时,常数要与矩阵的列保持一致。一维数组也相当于列向量。

import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import mean_squared_error class GreyModel: def __init__(self): self.a = None self.b = None def preprocess(self, series): # 异常值处理,这里使用Z-score方法,Z-score大于3认为是异常值 z_scores = np.abs((series - series.mean()) / series.std()) series = series[z_scores < 3] # 累加生成(AGO) series = np.cumsum(series) # 数据标准化(可选) # series = (series - series.min()) / (series.max() - series.min()) return series def fit(self, series): # 数据预处理 series = self.preprocess(series) # 构造数据矩阵B和数据向量Y B = np.zeros((len(series)-1, 2)) Y = np.zeros(len(series)-1) for i in range(len(series)-1): B[i, 0] = -0.5 * (series[i] + series[i+1]) B[i, 1] = 1 Y[i] = series[i+1] # 加权最小二乘法求解参数 weights = np.exp(-np.arange(len(Y)) / len(Y)) # 使用指数衰减加权 W = np.diag(weights) # 加权最小二乘法 BTB = np.dot(B.T, np.dot(W, B)) BTY = np.dot(B.T, np.dot(W, Y)) theta = np.linalg.solve(BTB, BTY) self.a = theta[0] self.b = theta[1] def predict(self, steps): if self.a is None or self.b is None: raise ValueError("Model not fitted yet!") # 预测累加序列 cum_pred = np.zeros(steps) cum_pred[0] = self.b / self.a for i in range(1, steps): cum_pred[i] = (cum_pred[0] - self.b/self.a) * np.exp(-self.a * i) + self.b/self.a # 还原原始序列 pred = np.zeros(steps) pred[0] = cum_pred[0] for i in range(1, steps): pred[i] = cum_pred[i] - cum_pred[i-1] return pred 优化代码,提高精度,并生成完整代码
04-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值