【问题标题】:code errors bad operand type for unary -: 'str'代码错误一元操作数类型错误-:'str'
【发布时间】:2021-01-06 23:26:01
【问题描述】:

我正在编写一个在 S 曲线上产生噪声的代码,该代码有效,因为我用真实值尝试过它,它工作得很好。

我试图通过创建两个用户可以决定的输入来使其更复杂,这将是噪声和曲线的陡度。

这是我的代码:

import numpy as np
import matplotlib.pyplot as plt

def sigmoid(z):
    return 1 / (1 + np.exp(-z)) #Function for the S-curve

noise=input('Please, insert here a number that will define how big the noise of the curve will be (the bigger the number, the bigger the noise.): ')
steepness=input('Please, insert here a number that will define the steepness of the curve (The bigger the number, the steeper the steep): ')

x = np.arange(-steepness, steepness, (2*steepness)/1000)  # x values
n = noise * np.random.random(x.shape) - 0.1 # noise for each value of the sigmoid
y = sigmoid(x) + n  # S-curve plus noise
print(y)
plt.plot(x, y, marker='*')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('S-curve with noise')
plt.show()

但是使用这段代码我有两个错误...

第一个是这个:TypeError: bad operand type for unary -: 'str'

第二个是这个:ufunc 'multiply' 没有包含签名匹配类型的循环 (dtype(' dtype('

另一个没有输入的代码可以正常工作是这个:

import numpy as np
import matplotlib.pyplot as plt

def sigmoid(z):
    return 1 / (1 + np.exp(-z)) #Function for the S-curve

x = np.arange(-5, 5, 0.01)  # x values
n = 0.2 * np.random.random(x.shape) - 0.1 # noise for each value of the sigmoid
y = sigmoid(x) + n  # S-curve plus noise
print(y)
plt.plot(x, y, marker='*')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('S-curve with noise')
plt.show()

你能帮我找出问题所在吗?

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    使用float将输入转换为浮点数:

    noise=float(input('Please, insert here a number that will define how big the noise of the curve will be (the bigger the number, the bigger the noise.): '))
    steepness=float(input('Please, insert here a number that will define the steepness of the curve (The bigger the number, the steeper the steep): '))
    

    如果不包括这个,Python 会认为变量是字符串,而不是数字。

    【讨论】:

    • 糟糕,修复了@jjramsey
    猜你喜欢
    • 2014-01-02
    • 2013-03-28
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    相关资源
    最近更新 更多