1. 程式人生 > >學習大資料第五天:最小二乘法的Python實現(二)

學習大資料第五天:最小二乘法的Python實現(二)

1.numpy.random.normal

numpy.random.normal

numpy.random.normal(loc=0.0scale=1.0size=None)

Draw random samples from a normal (Gaussian) distribution.

The probability density function of the normal distribution, first derived by De Moivre and 200 years later by both Gauss and Laplace independently [R250]

, is often called the bell curve because of its characteristic shape (see the example below).

The normal distributions occurs often in nature. For example, it describes the commonly occurring distribution of samples influenced by a large number of tiny, random disturbances, each with its own unique distribution 

[R250].

Parameters:

loc : float

Mean (“centre”) of the distribution.

scale : float

Standard deviation (spread or “width”) of the distribution.

size : int or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.

See also

scipy.stats.distributions.norm
probability density function, distribution or cumulative density function, etc.

Notes

The probability density for the Gaussian distribution is

p(x) = \frac{1}{\sqrt{ 2 \pi \sigma^2 }}e^{ - \frac{ (x - \mu)^2 } {2 \sigma^2} },

where \mu is the mean and \sigma the standard deviation. The square of the standard deviation, \sigma^2, is called the variance.

The function has its peak at the mean, and its “spread” increases with the standard deviation (the function reaches 0.607 times its maximum at x + \sigma and x - \sigma [R250]). This implies that numpy.random.normal is more likely to return samples lying close to the mean, rather than those far away.

References

[R250] (1234) P. R. Peebles Jr., “Central Limit Theorem” in “Probability, Random Variables and Random Signal Principles”, 4th ed., 2001, pp. 51, 51, 125.

Examples

Draw samples from the distribution:

>>>
>>> mu, sigma = 0, 0.1 # mean and standard deviation
>>> s = np.random.normal(mu, sigma, 1000)

Verify the mean and the variance:

>>>
>>> abs(mu - np.mean(s)) < 0.01
True
>>>
>>> abs(sigma - np.std(s, ddof=1)) < 0.01
True

Display the histogram of the samples, along with the probability density function:

>>>
>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 30, normed=True)
>>> plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *
...                np.exp( - (bins - mu)**2 / (2 * sigma**2) ),
...          linewidth=2, color='r')
>>> plt.show()
../../_images/numpy-random-normal-1.png
2.numpy.random.randn

import numpy as np
np.random.randn(2,3)

array([[ 0.59941534,  1.0991949 ,  1.36316028],
       [-0.01979197,  1.30783162, -0.69808199]])

意思是從標準正太分佈中隨機抽取。

3.scipy.optimize.leastsq

最小二乘法

import numpy as np
from scipy.optimize import leastsq


#待擬合的函式,x是變數,p是引數
def fun(x, p):
    a, b = p
    return a*x + b


#計算真實資料和擬合數據之間的誤差,p是待擬合的引數,x和y分別是對應的真實資料
def residuals(p, x, y):
    return fun(x, p) - y


#一組真實資料,在a=2, b=1的情況下得出
x1 = np.array([1, 2, 3, 4, 5, 6], dtype=float)
y1 = np.array([3, 5, 7, 9, 11, 13], dtype=float)


#呼叫擬合函式,第一個引數是需要擬合的差值函式,第二個是擬合初始值,第三個是傳入函式的其他引數
r = leastsq(residuals, [1, 1], args=(x1, y1))


#列印結果,r[0]儲存的是擬合的結果,r[1]、r[2]代表其他資訊
print r[0]


執行之後,擬合結果是


[2. 1.]


但是在這次實際的使用過程中,我擬合的函式不是這樣簡單的,其中的一個難點是待擬合函式是一個分段函式,需要判斷自變數的值,然後給出不同的函式方程式,舉個例子, 這樣一個分段函式:當x > 3時,y = ax + b, 當x <= 3 時,y = ax – b, 用Python程式碼寫一下:


def fun(x, p):
    a, b = p
    if (x > 3):
        return a*x + b
    else:
        return a*x - b


如果我們還是使用原來的差值函式進行擬合,會得到這樣的錯誤:


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


原因很簡單,我們現在的fun函式只能計算單個值了,如果傳入的還是一個array,自然就會報錯。那麼怎麼辦呢?我也很鬱悶,於是在scipy的maillist裡尋求幫助, 外國牛牛們都很熱心,很快就指出了問題。其實是我對於差值函式理解錯了,leastsq函式所要傳入的差值函式需要返回的其實是一個array, 於是我們可以這樣修改差值函式:


def residuals(p, x, y):
    temp = np.array([0,0,0,0,0,0],dtype=float)
    for i in range(0, len(x)):
        temp[i] = fun(x[i], p)
    return temp - y

4.

import numpy as np  #慣例
import scipy as sp  #慣例
from scipy.optimize import leastsq #這裡就是我們要使用的最小二乘的函式
import pylab as pl
 
m = 9  #多項式的次數
 
def real_func(x):
    return np.sin(2*np.pi*x) #sin(2 pi x)
 
def fake_func(p, x):
    f = np.poly1d(p) #多項式分佈的函式
    return f(x)
 
#殘差函式
def residuals(p, y, x):
    return y - fake_func(p, x)
 
#隨機選了9個點,作為x
x = np.linspace(0, 1, 9)
#畫圖的時候需要的“連續”的很多個點
x_show = np.linspace(0, 1, 1000)
 
y0 = real_func(x)
#加入正態分佈噪音後的y
y1 = [np.random.normal(0, 0.1) + y for y in y0]
 
#先隨機產生一組多項式分佈的引數
p0 = np.random.randn(m)


plsq = leastsq(residuals, p0, args=(y1, x))
 
print ('Fitting Parameters :', plsq[0]) #輸出擬合引數
 
pl.plot(x_show, real_func(x_show), label='real')
pl.plot(x_show, fake_func(plsq[0], x_show), label='fitted curve')
pl.plot(x, y1, 'bo', label='with noise')
pl.legend()
pl.show()


相關推薦

學習資料乘法Python實現

1.numpy.random.normal numpy.random.normal numpy.random.normal(loc=0.0, scale=1.0, size=None) Draw random samples from a normal (Gaussi

LeetCode長迴文子串C語言

給定一個字串 s,找到 s 中最長的迴文子串。你可以假設 s 的最大長度為1000。 示例 1: 輸入: “babad” 輸出: “bab” 注意: "aba"也是一個有效答案。 示例 2: 輸入: “cbbd” 輸出: “bb” 解法一:暴力求解法 思想:

JQuery框架源碼簡析1

err cal content browser active lac rda setting right (轉自老惠的博客) JQuery是一個應用廣泛、非常優秀的JavaScript框架,其代碼簡潔而優雅,有很多值得我們學習的地方。這裏僅僅對其代碼結構做一個簡單的分析

條件、迴圈以及其他語句

第五章 條件、迴圈以及其他語句       5.1 再談print和import       隨著我們對於Python的認知越來越多,很多我們以前不清楚的東西慢慢都需要了解,下面在談談print和import等我們所不知道的一些地方。原來的pr

python學習python基礎字串、有序集合列表、元組;正確理解元組不可變

首先,什麼是sequence(序列)操作? 字串的特性被稱為sequence(序列)  H o w a r e y o u ? 就好像儲存在一個個連續的單元格里面,每個單

python字符串和列表

python一、簡單函數的使用1.定義函數格式如下: # 定義一個函數 def test(): print ‘----哈哈----‘ print ‘----這是我的第一個函數----‘ # 調用函數 test()2.時間函數開發中,經常需要打印一些調試的信息

JavaWeb核心之Servlet

servlet一、Servlet簡介1、什麽是Servletservlet是運行在服務端的Java小程序,是sun公司提供的一套規範,用來處理客戶端請求、響應給瀏覽器的動態資源Servlet是Javaweb三大組件之一(Servlet、Filter、Listener),且最重要2、Servlet的作用用來處理

Introduction to 3D Game Programming with DirectX 12 學習筆記之 --- 渲染流水線

學習目標 瞭解幾個用以表達真實場景的標誌和2D影象的深度空間; 學習在Direct3D中如何表示3D物體; 學習如何模擬虛擬攝像機; 理解渲染流水線:如何用幾何描述的3D場景渲染出2D影象; 1 3D幻覺 如何在2D平面(顯示器)上產生

java學習之路--------

今天的內容主要就是隨機數的二種方式和有關隨機數的二個案例 1.Math方法 語法:Math.random();           生成的是0.0~1.0之間的隨機浮點數 備註:前包括後不包括0

【譯】你不知道的Chrome除錯工具技巧 console的log中,讓人疑惑的案例

特別宣告 本文是作者 Tomek Sułkowski 釋出在 medium 上的一個系列。據作者透露一共有24篇,一直更新到12月24日 版權歸原作者所有。 前兩篇的翻譯連結我已經給到了作者本人,雖然他不理解中文,但是他還是很開心哈哈,截圖在最後 譯者在翻譯前已經和作者溝通得到了翻譯整個系列的許可。 為

python字典的增刪改查,字典的巢狀

資料型別劃分:可變資料型別, 不可變資料型別不可變資料型別: 元祖 bool str int 可雜湊可變資料型別: list dict set 不可雜湊dict key:必須是可雜湊資料型別dict value:任意資料型別dict 優點:用二分查詢去查詢 儲存大量的關

tensorflow1005近鄰演算法

python程式碼 import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_

《機器學習實戰》Logistic迴歸1基本概念和簡單例項

最近感覺時間越來越寶貴,越來越不夠用。不過還是抽空看了點書,然後整理到部落格來。 加快點節奏,廢話少說。 Keep calm & carry on. ----------------------------------------------------------

turtle程式語法元素分析

如有錯誤,請聯絡博主進行更改。 庫引用     擴充Python程式功能的方式 使用import保留字完成,採用<a>.<b>()的編碼風格 import更多用法     使用 from 和 import 保留字共同完成 fro

OpenCV學習系列教程測試和提高程式碼的效率

Opencv-Python學習系列教程第五篇 來自opencv-python官方學習文件,本人謹做翻譯和註釋,以及一些自己的理解 本文由作者翻譯並進行程式碼驗證,轉載請註明出處~ 官方文件請參閱:https://docs.opencv.org/4.0.1/dc/d71/tutorial_py_optim

【吳恩達機器學習筆記】多變數線性迴歸

目錄 多特徵下的目標函式 多元梯度下降法 多元梯度下降法中的方法 特徵縮放 選擇學習率 特徵和多項式迴歸 正規方程(區別於迭代法的直接解法) 正規方程在矩陣不可逆的情況下的解決方法

結構型模式--介面卡模式

零、結構型模式 從現在開始就進入到了第二個模式大類結構型模式。所謂結構型模式就是處理一個系統中不同實體(例如類和物件)之間的關係,關注的是通過一種簡單的物件組合方式來創造新的功能。 常見的結構型模式

資料——MapReduce原理及IDEA Maven下WordCount例項兩種實現

1.MapReduce概述 HDFS實現了分散式檔案儲存,儲存問題解決了,我們就需要考慮如何對資料進行處理,MapReduce是一個計算框架(程式設計模型),基於該計算框架,可以很容易的編寫資料處理程式,從而以較高的效率處理海量資料集。 MR框架對於程式設計師的最大意義在

學習源碼(難得可貴)

pan directly 源碼 查找 ini length quick nbsp init else { elem = document.getElementById(match[2]); // 以id的形式獲取元素

演算法導論 概率分析和隨機演算法 筆記僱傭問題、指示器隨機變數、隨機演算法、概率分析和指示器隨機變數的進一步使用

僱傭問題: 假設你需要僱用一名新的辦公室助理。你先前的僱傭嘗試都以失敗告終,所以你決定找一個僱用代理。僱用代理每天給你推薦一個應聘者。你會面試這個人,然後決定要不要僱用他。你必須付給僱用代理一小筆費用來面試應聘者。要真正地僱用一個應聘者則要花更多的錢,因為你必須辭掉目前的辦公室助理,還要付一