python - 用于创建故障评估图图表的 Python 代码
问题描述
我想在结构分析中做一个蒙特卡洛概率模型。为此,我需要绘制此模型:
我制定了以下代码,但仍然需要做很多工作:
import pandas as pd
from matplotlib import pyplot
import numpy as np
from scipy.optimize import curve_fit
from numpy import arange
%matplotlib inline
# define the true objective function
def objective(x, a, b, c, d, e, f):
return (a * x) + (b * x**2) + (c * x**3) + (d * x**4) + (e * x**5) + f
y = np.array([1,0.99,0.97,0.93,0.9,0.81,0.7,0.57,0.5,0.32,0.25])
x = np.array([0,0.2,0.4,0.6,0.67,.8,0.9,1.0,1.05,1.2,1.32])
popt, _ = curve_fit(objective, x, y)
a, b, c, d, e, f = popt
pyplot.scatter(x, y)
# define a sequence of inputs between the smallest and largest known inputs
x_line = arange(min(x), max(x), 0.1)
# calculate the output for the range
y_line = objective(x_line, a, b, c, d, e, f)
# create a line plot for the mapping function
pyplot.plot(x_line, y_line, '--', color='red')
pyplot.show()
- 你能帮我正确地编写代码来创建curve_fit吗?
- 如何确定随机数是否会在曲线内?
解决方案
要使曲线附加到左侧的 Y 轴,一种方法是将 X 轴最小值设置为与您拥有的最小 X 轴值相同(在本例中为零)。 matplotlib.pyplot.xlim
要关闭绘图的右侧,您可以根据数据集的最小值/最大值绘制一条垂直线。 matplotlib.pyplot.vlines
虽然对您的问题的看法可能过于简单,但一种方法是简单地将有问题的值与数据集的范围进行比较。
min(y) <= a[1] <= max(y)
下面的代码显示了每个示例,但没有花时间使其尽可能像 Pythonic 一样(字面意思是为了说明而写的)。
代码:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
from matplotlib import pyplot
import numpy as np
from scipy.optimize import curve_fit
from numpy import arange
# %matplotlib inline
# define the true objective function
def objective(x, a, b, c, d, e, f):
return (a * x) + (b * x**2) + (c * x**3) + (d * x**4) + (e * x**5) + f
y = np.array([1,0.99,0.97,0.93,0.9,0.81,0.7,0.57,0.5,0.32,0.25])
x = np.array([0,0.2,0.4,0.6,0.67,.8,0.9,1.0,1.05,1.2,1.32])
popt, _ = curve_fit(objective, x, y)
a, b, c, d, e, f = popt
pyplot.scatter(x, y)
# define a sequence of inputs between the smallest and largest known inputs
x_line = arange(min(x), max(x), 0.1)
# calculate the output for the range
y_line = objective(x_line, a, b, c, d, e, f)
# create a line plot for the mapping function
pyplot.plot(x_line, y_line, '--', color='red')
# Set X axis limits
pyplot.xlim(min(x),)
# Set Y axis limits
pyplot.ylim(0,)
# Close the curve on the right
pyplot.vlines(max(x), min(y), 0, linestyles='--', color='red')
# Value within range?
a = (0.15, 0.63)
a1 = min(x) <= a[0] <= max(x)
a2 = min(y) <= a[1] <= max(y)
if a1 and a2:
print('True')
# Plot test point
pyplot.plot(a[0], a[1], marker='o', markersize=5, color="blue")
pyplot.show()
外壳输出: True
推荐阅读
- coldfusion - Testbox 2.1 - 跳过整个目录或 CFC 文件
- reactjs - 基本理解——React 应用中公共目录的位置
- angular - 如何在不需要 rxjs-compat 的情况下只导入 RxJS 6 中使用的运算符,如旧的 RxJS?
- javascript - 如何弄清楚请求是如何在网站中发起的?
- android - 使用 Android Studio 3.1 开发 AOSP 无法为检测测试构建测试 apk
- linux - 如何在 shell 脚本中参数化 git URL?
- angular - ngx数据表根本不呈现
- css - HTML 选项标签中的多种颜色(组合框)
- java - 问题在我的 Java 应用程序上不断重复
- ocaml - 无需使用附加即可取消组合序列的功能