条件曲线是否适合scipy? [英] Conditional curve fit with scipy?

查看:102
本文介绍了条件曲线是否适合scipy?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我要在熄灯的情况下对记录的数据使用一条直线。现在,我不小心打开了灯,我的数据与数据点101以及之后的位置保持恒定的偏移量。

Let's say I want to fit a straight line to my data recorded with lights off. Now I accidentally left the lights on, and my data has a constant offset from datapoint 101 and onwards.

我怎么适应呢?我尝试为x合并一个条件,但出现错误

How can I fit this? I've tried to incorporate a condition for x, but I get the error


ValueError:具有多个的数组的真值元素是
不明确。请使用a.any()或a.all()

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

记住要取消注释其余代码(遇到错误)。

Remember to uncomment the remainder of the code (to encounter the error).

import numpy as np
from scipy import optimize
import matplotlib.pyplot as plt

d1 = np.random.normal(0,0.1, 100)
d2 = np.random.normal(3,0.1, 100)

x = np.arange(0,200)
y = np.concatenate((d1,d2))

plt.plot(x, y)

# def line(x, a, b, offset):
#     if x < 101:
#         y = a * x + b
#     else:
#         y = (a * x + b) + offset
#     return y
# 
# popt, pcov = optimize.curve_fit(line, xdata = x, ydata = y)
# 
# plt.plot(x, line(x, *popt), color = "firebrick")
plt.show()

预期输出:

Expected output:

推荐答案

我认为标准技巧是将布尔条件转换为整数因子:

I think the standard trick would be to convert boolean condition to an integer factor:

def line(x, a, b, offset):
    return (a * x + b) + offset * (x>100)

这篇关于条件曲线是否适合scipy?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆