我收到此错误
TypeError
Traceback (most recent call last)
<ipython-input-7-995aa3052f74> in <module>()
A,B,C,D = 200, 48.475, 0.0026, 400
---> y_true = sigmoide(x, A, B, C, D)
<ipython-input-7-995aa3052f74> in sigmoide(x, A, B, C, D)
"""4PL sigmoide equation."""
---> return A*erf((x-B)/C*sqrt(2)) + D
TypeError: unsupported operand type(s) for -: '_io.TextIOWrapper' and 'float'
当我尝试运行此代码时:
import numpy as np
import numpy.random as npr
import matplotlib.pyplot as plt
from scipy.special import erf
from scipy.optimize import leastsq
def sigmoide(x, A, B, C, D):
"""4PL sigmoide equation."""
return A*erf((x-B)/C*sqrt(2)) + D
def residuals(p, y, x):
"""Deviations of data from fitted 4PL curve"""
A,B,C,D = p
err = y-sigmoide(x, A, B, C, D)
return err
def peval(x, p):
"""Evaluated value at x with current parameters."""
A,B,C,D = p
return sigmoide(x, A, B, C, D)
# Make up some data for fitting and add noise
# In practice, y_meas would be read in from a file
x = open("C:\\Users\Anaconda3\Lib\site-packages\data\data1.txt", "r")
A,B,C,D = 200, 48.475, 0.0026, 400
y_true = sigmoide(x, A, B, C, D)
y_meas = open("C:\\Users\Anaconda3\Lib\site-packages\data\data2.txt", "r")
# Initial guess for Parameters
p0 = [0, 100, 100, 100]
# Fit equation using least squares optimization
plsq = leastsq(residuals, p0, args=(y_meas, x))
# Plot results
plt.plot(x,peval(x,plsq[0]),x,y_meas,'o',x,y_true)
plt.title('Least-squares 4PL fit to noisy data')
plt.legend(['Fit', 'Noisy', 'True'], loc='upper left')
for i, (param, actual, est) in enumerate(zip('ABCD', [A,B,C,D], plsq[0])):
plt.text(10, 3-i*0.5, '%s = %.2f, est(%s) = %.2f' % (param, actual, param, est))
plt.savefig('sigmoide.png')
请为解决该错误提供任何帮助?谢谢!
答案 0 :(得分:1)
您将x
定义为打开文件:
x = open("C:\\Users\Anaconda3\Lib\site-packages\data\data1.txt", "r")
但是您不是从文件中读取数据,而是调用sigmoide
函数并将打开的文件作为第一个参数传递!
y_true = sigmoide(x, A, B, C, D)
在函数内部,您将继续尝试从打开的文件中计算出减法!
return A*erf((x-B)/C*sqrt(2)) + D
那当然是行不通的-Python不知道如何从打开的文件中减去数字!然后您会收到unsupported operand type(s)
错误。
答案 1 :(得分:0)
非常感谢大家!
@Const:正如您提到的,错误是由于打开x和y_meas文件时它们在脚本中而不是float中。这是解决错误的代码:
x = open("C:\\Users\Anaconda3\Lib\site-packages\data\data1.txt", "r")
f1=np.array(x.read().split("\n")).astype(float)
print(f1)
y_meas = open("C:\\Users\Anaconda3\Lib\site-packages\data\data2.txt", "r")
f2=np.array(y_meas.read().split("\n")).astype(float)
print(f2)