y = np.arange(0, 3000, 0.001) K = lambda x: 3 / 4 * (1 - x**2) * (abs(x) <= 1) plt.figure(figsize=(5, 4.5))
时间: 2024-06-03 17:11:50 浏览: 17
这是一段 Python 代码,其中使用了 NumPy 和 Matplotlib 库。
1. `np.arange(0, 3000, 0.001)` 创建了一个一维的数组,从 0 开始,步长为 0.001,到 3000 结束。这个数组包含了 3000000 个元素。
2. `K = lambda x: 3 / 4 * (1 - x**2) * (abs(x) <= 1)` 定义了一个函数 `K`,使用了 Python 的 lambda 表达式。这个函数的输入是一个数字 `x`,输出是一个数字,根据输入的 `x` 的值计算出来。具体来说,如果 `x` 的绝对值小于等于 1,则输出 `3 / 4 * (1 - x**2)`,否则输出 0。
3. `plt.figure(figsize=(5, 4.5))` 创建了一个新的 Matplotlib 图片,并设置了图片的大小为 5 英寸宽,4.5 英寸高。这个函数返回一个 Figure 对象,可以在后续的操作中使用。
如果您有更多问题或需要解释,请告诉我。
相关问题
#外点法(能运行出来) import math import sympy import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D plt.ion() fig = plt.figure() ax = Axes3D(fig) def draw(x,index,M): # F = f + MM * alpha # FF = sympy.lambdify((x1, x2), F, 'numpy') Z = FF(*(X, Y,M)) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='rainbow',alpha=0.5) ax.scatter(x[0], x[1], FF(*(x[0],x[1],M)), c='r',s=80) ax.text(x[0], x[1], FF(*(x[0],x[1],M)), 'here:(%0.3f,%0.3f)' % (x[0], x[1])) ax.set_zlabel('F') # 坐标轴 ax.set_ylabel('X2') ax.set_xlabel('X1') plt.pause(0.1) # plt.show() # plt.savefig('./image/%03d' % index) plt.cla() C = 10 # 放大系数 M = 1 # 惩罚因子 epsilon = 1e-5 # 终止限 x1, x2 = sympy.symbols('x1:3') MM=sympy.symbols('MM') f = -x1 + x2 h = x1 + x2 - 1 # g=sympy.log(x2) if sympy.log(x2)<0 else 0 g = sympy.Piecewise((x2-1, x2 < 1), (0, x2 >= 1)) # u=lambda x: alpha = h ** 2 + g ** 2 F = f + MM * alpha # 梯度下降来最小化F def GD(x,M,n): # F = f + M * alpha # delta_x = 1e-11 # 数值求导 # t = 0.0001 # 步长 e = 0.001 # 极限 # my_print(e) np.array(x) for i in range(15): t = sympy.symbols('t') grad = np.asarray( [sympy.diff(F, x1).subs([(x1, x[0]), (x2, x[1]),(MM,M)]), sympy.diff(F, x2).subs([(x1, x[0]), (x2, x[1]),(MM,M)])]) # print('g',grad) # print((x-t*grad)) # print(F.subs([(x1,(x-t*grad)[0]),(x2,(x-t*grad)[1])])) t = sympy.solve(sympy.diff(F.subs([(x1, (x - t * grad)[0]), (x2, (x - t * grad)[1]),(MM,M)]), t), t) print('t',t) x = x - t * grad print('x', x) # print('mmm',M) draw(x,n*10+i,M) # my_print(np.linalg.norm(grad)) # print(type(grad)) if (abs(grad[0]) < e and abs(grad[1]) < e): # print(np.linalg.norm(grad)) print('g', grad) break return list(x) pass x = [-0.5, 0.2] X = np.arange(0, 4, 0.25) Y = np.arange(0, 4,
0.25) # 定义网格点坐标 X, Y = np.meshgrid(X, Y) # 生成网格点 FF = sympy.lambdify((x1, x2,MM), F, 'numpy') # 将表达式转化为可计算的函数 draw(x,0,M) # 绘制函数图像 for i in range(5): # 迭代次数为5次 x = GD(x,M,i) # 梯度下降求解极小值 M = C * M # 更新惩罚因子 print('M',M) # plt.savefig('./image/%03d' % index) plt.ioff() plt.show()
这是一个使用外点法求解带约束非线性规划问题的 Python 代码,其中 F 为目标函数,alpha 为罚函数,x1, x2 为自变量,MM 为惩罚因子。函数 GD 为梯度下降求解极小值。代码中还包含了绘制函数图像的 draw 函数。
arr0 = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]) arr1 = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]) arr3 = np.array(input("请输入连续24个月的配件销售数据,元素之间用空格隔开:").split(), dtype=float) data_array = np.vstack((arr1, arr3)) data_matrix = data_array.T data = pd.DataFrame(data_matrix, columns=['month', 'sales']) sales = data['sales'].values.astype(np.float32) sales_mean = sales.mean() sales_std = sales.std() sales = abs(sales - sales_mean) / sales_std train_data = sales[:-1] test_data = sales[-12:] def create_model(): model = tf.keras.Sequential() model.add(layers.Input(shape=(11, 1))) model.add(layers.Conv1D(filters=32, kernel_size=2, padding='causal', activation='relu')) model.add(layers.BatchNormalization()) model.add(layers.Conv1D(filters=64, kernel_size=2, padding='causal', activation='relu')) model.add(layers.BatchNormalization()) model.add(layers.Conv1D(filters=128, kernel_size=2, padding='causal', activation='relu')) model.add(layers.BatchNormalization()) model.add(layers.Conv1D(filters=256, kernel_size=2, padding='causal', activation='relu')) model.add(layers.BatchNormalization()) model.add(layers.Conv1D(filters=512, kernel_size=2, padding='causal', activation='relu')) model.add(layers.BatchNormalization()) model.add(layers.Dense(1, activation='linear')) return model model = create_model() BATCH_SIZE = 16 BUFFER_SIZE = 100 train_dataset = tf.data.Dataset.from_tensor_slices(train_data) train_dataset = train_dataset.window(11, shift=1, drop_remainder=True) train_dataset = train_dataset.flat_map(lambda window: window.batch(11)) train_dataset = train_dataset.map(lambda window: (window[:-1], window[-1:])) train_dataset = train_dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE).prefetch(1) model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), loss='mse') history = model.fit(train_dataset, epochs=100, verbose=0) test_input = test_data[:-1] test_input = np.reshape(test_input, (1, 11, 1)) predicted_sales = model.predict(test_input)[0][0] * sales_std + sales_mean test_prediction = model.predict(test_input) y_test=test_data[1:12] y_pred=test_prediction y_pred = test_prediction.ravel() print("预测下一个月的销量为:", predicted_sales),如何将以下代码稍作修改插入到上面的最后,def comput_acc(real,predict,level): num_error=0 for i in range(len(real)): if abs(real[i]-predict[i])/real[i]>level: num_error+=1 return 1-num_error/len(real) a=np.array(test_data[label]) real_y=a real_predict=test_predict print("置信水平:{},预测准确率:{}".format(0.2,round(comput_acc(real_y,real_predict,0.2)* 100,2)),"%")
你可以在最后添加如下代码实现 `comput_acc()` 函数的功能:
```
label = 0 # 定义标签
a = np.array(test_data[label]) # 获取测试数据的标签列
real_y = a[1:] # 实际销售数据
real_predict = y_pred[:-1] # 预测销售数据
print("置信水平:{},预测准确率:{}".format(0.2, round(comput_acc(real_y, real_predict, 0.2) * 100, 2)), "%")
```
这段代码的作用是,首先定义标签为 0,即选取测试数据中的第一列数据(即销售数据)。然后,使用 `np.array()` 函数将该列数据转换为 numpy 数组 `a`。接着,将 `a` 中的第二个元素到最后一个元素赋值给 `real_y`,这里是因为真实销售数据的第一个元素已经作为测试数据输入了模型,所以预测值中不包含该元素。然后,将 `y_pred` 中的第一个元素到倒数第二个元素赋值给 `real_predict`,这是因为预测值中的最后一个元素已经与真实值的最后一个元素相对应。最后,调用 `comput_acc()` 函数计算预测准确率,并将结果打印输出。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)