导航:首页 > 编程语言 > pythontanh函数

pythontanh函数

发布时间:2022-07-11 14:30:32

A. python怎么画𝑡𝑎𝑛ℎ(𝑥)函数图像

由于无法显示空格,请将#替换为空格,代码如下:

from turtle import *
import turtle
import math

for i in range(-300, 300):
####x = i
####y = math.tanh(x/30) * 100
####if i == -300:
########turtle.up()
####goto(x, y)
####turtle.down()
done()

B. 如何用python和scikit learn实现神经网络

1:神经网络算法简介

2:Backpropagation算法详细介绍

3:非线性转化方程举例

4:自己实现神经网络算法NeuralNetwork

5:基于NeuralNetwork的XOR实例

6:基于NeuralNetwork的手写数字识别实例

7:scikit-learn中BernoulliRBM使用实例

8:scikit-learn中的手写数字识别实例

一:神经网络算法简介

1:背景

以人脑神经网络为启发,历史上出现过很多版本,但最着名的是backpropagation

2:多层向前神经网络(Multilayer Feed-Forward Neural Network)

C. 怎样用python构建一个卷积神经网络

用keras框架较为方便

首先安装anaconda,然后通过pip安装keras

D. 关于神经网络 需要学习python的哪些知识

多读文档 应该是库 库也是python基础编写的 多读多看

E. 如何在Python中用LSTM网络进行时间序列预测

时间序列模型

时间序列预测分析就是利用过去一段时间内某事件时间的特征来预测未来一段时间内该事件的特征。这是一类相对比较复杂的预测建模问题,和回归分析模型的预测不同,时间序列模型是依赖于事件发生的先后顺序的,同样大小的值改变顺序后输入模型产生的结果是不同的。
举个栗子:根据过去两年某股票的每天的股价数据推测之后一周的股价变化;根据过去2年某店铺每周想消费人数预测下周来店消费的人数等等

RNN 和 LSTM 模型

时间序列模型最常用最强大的的工具就是递归神经网络(recurrent neural network, RNN)。相比与普通神经网络的各计算结果之间相互独立的特点,RNN的每一次隐含层的计算结果都与当前输入以及上一次的隐含层结果相关。通过这种方法,RNN的计算结果便具备了记忆之前几次结果的特点。

典型的RNN网路结构如下:

4. 模型训练和结果预测
将上述数据集按4:1的比例随机拆分为训练集和验证集,这是为了防止过度拟合。训练模型。然后将数据的X列作为参数导入模型便可得到预测值,与实际的Y值相比便可得到该模型的优劣。

实现代码

  • 时间间隔序列格式化成所需的训练集格式

  • import pandas as pdimport numpy as npdef create_interval_dataset(dataset, look_back):

  • """ :param dataset: input array of time intervals :param look_back: each training set feature length :return: convert an array of values into a dataset matrix. """

  • dataX, dataY = [], [] for i in range(len(dataset) - look_back):

  • dataX.append(dataset[i:i+look_back])

  • dataY.append(dataset[i+look_back]) return np.asarray(dataX), np.asarray(dataY)


  • df = pd.read_csv("path-to-your-time-interval-file")

  • dataset_init = np.asarray(df) # if only 1 columndataX, dataY = create_interval_dataset(dataset, lookback=3) # look back if the training set sequence length

  • 这里的输入数据来源是csv文件,如果输入数据是来自数据库的话可以参考这里

  • LSTM网络结构搭建

  • import pandas as pdimport numpy as npimport randomfrom keras.models import Sequential, model_from_jsonfrom keras.layers import Dense, LSTM, Dropoutclass NeuralNetwork():

  • def __init__(self, **kwargs):

  • """ :param **kwargs: output_dim=4: output dimension of LSTM layer; activation_lstm='tanh': activation function for LSTM layers; activation_dense='relu': activation function for Dense layer; activation_last='sigmoid': activation function for last layer; drop_out=0.2: fraction of input units to drop; np_epoch=10, the number of epoches to train the model. epoch is one forward pass and one backward pass of all the training examples; batch_size=32: number of samples per gradient update. The higher the batch size, the more memory space you'll need; loss='mean_square_error': loss function; optimizer='rmsprop' """

  • self.output_dim = kwargs.get('output_dim', 8) self.activation_lstm = kwargs.get('activation_lstm', 'relu') self.activation_dense = kwargs.get('activation_dense', 'relu') self.activation_last = kwargs.get('activation_last', 'softmax') # softmax for multiple output

  • self.dense_layer = kwargs.get('dense_layer', 2) # at least 2 layers

  • self.lstm_layer = kwargs.get('lstm_layer', 2) self.drop_out = kwargs.get('drop_out', 0.2) self.nb_epoch = kwargs.get('nb_epoch', 10) self.batch_size = kwargs.get('batch_size', 100) self.loss = kwargs.get('loss', 'categorical_crossentropy') self.optimizer = kwargs.get('optimizer', 'rmsprop') def NN_model(self, trainX, trainY, testX, testY):

  • """ :param trainX: training data set :param trainY: expect value of training data :param testX: test data set :param testY: epect value of test data :return: model after training """

  • print "Training model is LSTM network!"

  • input_dim = trainX[1].shape[1]

  • output_dim = trainY.shape[1] # one-hot label

  • # print predefined parameters of current model:

  • model = Sequential() # applying a LSTM layer with x dim output and y dim input. Use dropout parameter to avoid overfitting

  • model.add(LSTM(output_dim=self.output_dim,

  • input_dim=input_dim,

  • activation=self.activation_lstm,

  • dropout_U=self.drop_out,

  • return_sequences=True)) for i in range(self.lstm_layer-2):

  • model.add(LSTM(output_dim=self.output_dim,

  • input_dim=self.output_dim,

  • activation=self.activation_lstm,

  • dropout_U=self.drop_out,

  • return_sequences=True)) # argument return_sequences should be false in last lstm layer to avoid input dimension incompatibility with dense layer

  • model.add(LSTM(output_dim=self.output_dim,

  • input_dim=self.output_dim,

  • activation=self.activation_lstm,

  • dropout_U=self.drop_out)) for i in range(self.dense_layer-1):

  • model.add(Dense(output_dim=self.output_dim,

  • activation=self.activation_last))

  • model.add(Dense(output_dim=output_dim,

  • input_dim=self.output_dim,

  • activation=self.activation_last)) # configure the learning process

  • model.compile(loss=self.loss, optimizer=self.optimizer, metrics=['accuracy']) # train the model with fixed number of epoches

  • model.fit(x=trainX, y=trainY, nb_epoch=self.nb_epoch, batch_size=self.batch_size, validation_data=(testX, testY)) # store model to json file

  • model_json = model.to_json() with open(model_path, "w") as json_file:

  • json_file.write(model_json) # store model weights to hdf5 file

  • if model_weight_path: if os.path.exists(model_weight_path):

  • os.remove(model_weight_path)

  • model.save_weights(model_weight_path) # eg: model_weight.h5

  • return model

  • 这里写的只涉及LSTM网络的结构搭建,至于如何把数据处理规范化成网络所需的结构以及把模型预测结果与实际值比较统计的可视化,就需要根据实际情况做调整了。

    F. 如何在Python中获取完整的异颜桓

    我们可以很容易的通过Python解释器获取帮助。如果想知道一个对象(object)更多的信息,那么可以调用help(object)!另外还有一些有用的方法,dir(object)会显示该对象的大部分相关属性名,还有object._doc_会显示其相对应的文档字符串。下面对其进行逐一介绍。

    1、 help()

    help函数是Python的一个内置函数。
    函数原型:help([object])。
    可以帮助我们了解该对象的更多信息。
    Ifno argument is given, the interactive help system starts on the interpreter console.

    >>> help()

    Welcome to Python 2.7! This is the online help utility.

    If this is your first time using Python, you should definitely check out
    the tutorial on the Internet at .

    Enter the name of any mole, keyword, or topic to get help on writing
    Python programs and using Python moles. To quit this help utility andreturn to the interpreter, just type "quit".

    To get a list of available moles, keywords, or topics, type "moles","keywords", or "topics". Each mole also comes with a one-line summary
    of what it does; to list the moles whose summaries contain a given word
    such as "spam", type "moles spam".

    help> int # 由于篇幅问题,此处只显示部分内容,下同Help on class int in mole __builtin__:class int(object)
    | int(x=0) -> int or long
    | int(x, base=10) -> int or long
    |

    .....help>

    Ifthe argument is a string, then the string is looked up as the name of amole,function,class,method,keyword, ordocumentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

    >>> help(abs) # 查看abs函数Help on built-in function abs in mole __builtin__:

    abs(...)
    abs(number) -> number

    Return the absolute value of the argument.>>> help(math) # 查看math模块,此处只显示部分内容Help on built-in mole math:

    NAME
    math

    FILE
    (built-in)

    DESCRIPTION
    This mole is always available. It provides access to the
    mathematical functions defined by the C standard.

    FUNCTIONS
    acos(...)
    acos(x)

    Return the arc cosine (measured in radians) of x.

    .....>>> 293031

    2、dir()

    dir函数是Python的一个内置函数。
    函数原型:dir([object])
    可以帮助我们获取该对象的大部分相关属性。
    Without arguments, return the list of names in the current local scope.

    >>> dir() # 没有参数['__builtins__', '__doc__', '__name__', '__package__']>>> >>> import math # 引入一个包和一个变量,再次dir()>>> a=3>>> >>> dir()
    ['__builtins__', '__doc__', '__name__', '__package__', 'a', 'math']>>> 12345678910

    With an argument, attempt to return a list of valid attributes for that object.

    >>> import math>>> dir(math) # math模块作为参数['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'sign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']>>> 12345

    The default dir() mechanism behaves differently with different types of objects, as it attempts to proce the most relevant, rather than complete, information:
    • If the object is a mole object, the list contains the names of the mole’s attributes.

    >>> import math>>> dir(math) # math模块作为参数['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'sign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']>>> 12345

    • If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.

    >>> dir(float) # 类型['__abs__', '__add__', '__class__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__int__', '__le__', '__long__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__pos__', '__pow__', '__radd__', '__rdiv__', '__rdivmod__', '__rece__', '__rece_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__setformat__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']>>> dir(3.4)
    ['__abs__', '__add__', '__class__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__int__', '__le__', '__long__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__pos__', '__pow__', '__radd__', '__rdiv__', '__rdivmod__', '__rece__', '__rece_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__setformat__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']>>> >>> class A:
    x=3
    y=4>>> class B(A):
    z=5>>> dir(B) # 类['__doc__', '__mole__', 'x', 'y', 'z']>>> 123456789101112131415161718

    • Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.

    3、_doc_

    在Python中有一个奇妙的特性,文档字符串,又称为DocStrings。
    用它可以为我们的模块、类、函数等添加说明性的文字,使程序易读易懂,更重要的是可以通过Python自带的标准方法将这些描述性文字信息输出。
    上面提到的自带的标准方法就是_doc_。前后各两个下划线。
    注:当不是函数、方法、模块等调用doc时,而是具体对象调用时,会显示此对象从属的类型的构造函数的文档字符串。

    >>> import math>>> math.__doc__ # 模块'This mole is always available. It provides access to the mathematical functions defined by the C standard.'>>> abs.__doc__ # 内置函数'abs(number) -> number Return the absolute value of the argument.'>>> def addxy(x,y):
    '''the sum of x and y'''
    return x+y>>> addxy.__doc__ # 自定义函数'the sum of x and y'>>> a=[1,2,4]>>> a.count.__doc__ # 方法'L.count(value) -> integer -- return number of occurrences of value'>>> b=3>>> b.__doc__ # 具体的对象"int(x=0) -> int or long int(x, base=10) -> int or long Convert a number or string to an integer, or return 0 if no arguments are given. If x is floating point, the conversion truncates towards zero. If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int('0b100', base=0) 4">>> 12345678910111213141516171819

    其实我们可以通过一定的手段来查看这些文档字符串,比如使用Pycharm,在对应的模块、函数、方法等上鼠标“右击”->Go to->Declaration。例如:查看内置函数abs的文档字符串

    参考文献:
    1、Python帮助文档

    阅读全文

    与pythontanh函数相关的资料

    热点内容
    h3c服务器怎么看功率 浏览:119
    前端录制文件如何上传服务器 浏览:536
    雅黑pdf 浏览:457
    python使用领域 浏览:880
    买兰博基尼用什么app 浏览:137
    android关闭后台运行 浏览:505
    python输出路径为超链接 浏览:533
    caxa为什么没有加密锁 浏览:792
    服务器怎么设置才能用IP访问 浏览:663
    邮件附件加密后打开能显示吗 浏览:724
    荣耀x10拍照算法 浏览:569
    androidgradle配置签名 浏览:96
    文件夹左边的空心三角符号是什么 浏览:287
    app英语音频试卷扫码怎么听 浏览:613
    字符串编译预处理 浏览:704
    苹果手机怎么会显示多个App 浏览:241
    不去互联网程序员 浏览:555
    电脑qq邮箱解压的图片保存在哪里 浏览:548
    嵌入命令行 浏览:94
    档案为什么被加密 浏览:487