導航:首頁 > 編程語言 > 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函數相關的資料

    熱點內容
    awss3命令 瀏覽:356
    百度店鋪客戶訂單手機加密 瀏覽:500
    釘釘班群文件夾怎麼上傳文件 瀏覽:749
    人社app怎麼解綁手機 瀏覽:101
    caj文件夾打不開 瀏覽:475
    什麼app可以將電量變色 瀏覽:692
    解放出你的解壓抖音小游戲 瀏覽:345
    什麼方式解壓比較好 瀏覽:266
    erp是什麼伺服器 瀏覽:185
    python中tmp 瀏覽:23
    說明wpf加密過程 瀏覽:144
    java讀取list 瀏覽:703
    iis7gzip壓縮 瀏覽:39
    有什麼安卓機打吃雞好 瀏覽:598
    三星u盤加密狗 瀏覽:474
    php函數的返回值嗎 瀏覽:587
    國企穩定程序員 瀏覽:328
    編程貓如何使用教程視頻 瀏覽:220
    安卓遠端網頁如何打日誌 瀏覽:218
    壓縮flash大小 瀏覽:993