savetxt

成都創(chuàng)新互聯(lián)公司堅持“要么做到,要么別承諾”的工作理念,服務領域包括:成都做網(wǎng)站、成都網(wǎng)站建設、企業(yè)官網(wǎng)、英文網(wǎng)站、手機端網(wǎng)站、網(wǎng)站推廣等服務,滿足客戶于互聯(lián)網(wǎng)時代的揚州網(wǎng)站設計、移動媒體設計的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡建設合作伙伴!
import numpy as np
i2 = np.eye(2)
np.savetxt("eye.txt", i2)
3.4 讀入CSV文件
# AAPL,28-01-2011, ,344.17,344.4,333.53,336.1,21144800
c,v=np.loadtxt('data.csv', delimiter=',', usecols=(6,7), unpack=True) #index從0開始
3.6.1 算術平均值
np.mean(c) = np.average(c)
3.6.2 加權平均值
t = np.arange(len(c))
np.average(c, weights=t)
3.8 極值
np.min(c)
np.max(c)
np.ptp(c) 最大值與最小值的差值
3.10 統(tǒng)計分析
np.median(c) 中位數(shù)
np.msort(c) 升序排序
np.var(c) 方差
3.12 分析股票收益率
np.diff(c) 可以返回一個由相鄰數(shù)組元素的差
值構成的數(shù)組
returns = np.diff( arr ) / arr[ : -1] #diff返回的數(shù)組比收盤價數(shù)組少一個元素
np.std(c) 標準差
對數(shù)收益率
logreturns = np.diff( np.log(c) ) #應檢查輸入數(shù)組以確保其不含有零和負數(shù)
where 可以根據(jù)指定的條件返回所有滿足條件的數(shù)
組元素的索引值。
posretindices = np.where(returns 0)
np.sqrt(1./252.) 平方根,浮點數(shù)
3.14 分析日期數(shù)據(jù)
# AAPL,28-01-2011, ,344.17,344.4,333.53,336.1,21144800
dates, close=np.loadtxt('data.csv', delimiter=',', usecols=(1,6), converters={1:datestr2num}, unpack=True)
print "Dates =", dates
def datestr2num(s):
return datetime.datetime.strptime(s, "%d-%m-%Y").date().weekday()
# 星期一 0
# 星期二 1
# 星期三 2
# 星期四 3
# 星期五 4
# 星期六 5
# 星期日 6
#output
Dates = [ 4. 0. 1. 2. 3. 4. 0. 1. 2. 3. 4. 0. 1. 2. 3. 4. 1. 2. 4. 0. 1. 2. 3. 4. 0.
1. 2. 3. 4.]
averages = np.zeros(5)
for i in range(5):
indices = np.where(dates == i)
prices = np.take(close, indices) #按數(shù)組的元素運算,產(chǎn)生一個數(shù)組作為輸出。
a = [4, 3, 5, 7, 6, 8]
indices = [0, 1, 4]
np.take(a, indices)
array([4, 3, 6])
np.argmax(c) #返回的是數(shù)組中最大元素的索引值
np.argmin(c)
3.16 匯總數(shù)據(jù)
# AAPL,28-01-2011, ,344.17,344.4,333.53,336.1,21144800
#得到第一個星期一和最后一個星期五
first_monday = np.ravel(np.where(dates == 0))[0]
last_friday = np.ravel(np.where(dates == 4))[-1]
#創(chuàng)建一個數(shù)組,用于存儲三周內(nèi)每一天的索引值
weeks_indices = np.arange(first_monday, last_friday + 1)
#按照每個子數(shù)組5個元素,用split函數(shù)切分數(shù)組
weeks_indices = np.split(weeks_indices, 5)
#output
[array([1, 2, 3, 4, 5]), array([ 6, 7, 8, 9, 10]), array([11,12, 13, 14, 15])]
weeksummary = np.apply_along_axis(summarize, 1, weeks_indices,open, high, low, close)
def summarize(a, o, h, l, c): #open, high, low, close
monday_open = o[a[0]]
week_high = np.max( np.take(h, a) )
week_low = np.min( np.take(l, a) )
friday_close = c[a[-1]]
return("APPL", monday_open, week_high, week_low, friday_close)
np.savetxt("weeksummary.csv", weeksummary, delimiter=",", fmt="%s") #指定了文件名、需要保存的數(shù)組名、分隔符(在這個例子中為英文標點逗號)以及存儲浮點數(shù)的格式。
0818b9ca8b590ca3270a3433284dd417.png
格式字符串以一個百分號開始。接下來是一個可選的標志字符:-表示結果左對齊,0表示左端補0,+表示輸出符號(正號+或負號-)。第三部分為可選的輸出寬度參數(shù),表示輸出的最小位數(shù)。第四部分是精度格式符,以”.”開頭,后面跟一個表示精度的整數(shù)。最后是一個類型指定字符,在例子中指定為字符串類型。
numpy.apply_along_axis(func1d, axis, arr, *args, **kwargs)
def my_func(a):
... """Average first and last element of a 1-D array"""
... return (a[0] + a[-1]) * 0.5
b = np.array([[1,2,3], [4,5,6], [7,8,9]])
np.apply_along_axis(my_func, 0, b) #沿著X軸運動,取列切片
array([ 4., 5., 6.])
np.apply_along_axis(my_func, 1, b) #沿著y軸運動,取行切片
array([ 2., 5., 8.])
b = np.array([[8,1,7], [4,3,9], [5,2,6]])
np.apply_along_axis(sorted, 1, b)
array([[1, 7, 8],
[3, 4, 9],
[2, 5, 6]])
3.20 計算簡單移動平均線
(1) 使用ones函數(shù)創(chuàng)建一個長度為N的元素均初始化為1的數(shù)組,然后對整個數(shù)組除以N,即可得到權重。如下所示:
N = int(sys.argv[1])
weights = np.ones(N) / N
print "Weights", weights
在N = 5時,輸出結果如下:
Weights [ 0.2 0.2 0.2 0.2 0.2] #權重相等
(2) 使用這些權重值,調(diào)用convolve函數(shù):
c = np.loadtxt('data.csv', delimiter=',', usecols=(6,),unpack=True)
sma = np.convolve(weights, c)[N-1:-N+1] #卷積是分析數(shù)學中一種重要的運算,定義為一個函數(shù)與經(jīng)過翻轉(zhuǎn)和平移的另一個函數(shù)的乘積的積分。
t = np.arange(N - 1, len(c)) #作圖
plot(t, c[N-1:], lw=1.0)
plot(t, sma, lw=2.0)
show()
3.22 計算指數(shù)移動平均線
指數(shù)移動平均線(exponential moving average)。指數(shù)移動平均線使用的權重是指數(shù)衰減的。對歷史上的數(shù)據(jù)點賦予的權重以指數(shù)速度減小,但永遠不會到達0。
x = np.arange(5)
print "Exp", np.exp(x)
#output
Exp [ 1. 2.71828183 7.3890561 20.08553692 54.59815003]
Linspace 返回一個元素值在指定的范圍內(nèi)均勻分布的數(shù)組。
print "Linspace", np.linspace(-1, 0, 5) #起始值、終止值、可選的元素個數(shù)
#output
Linspace [-1. -0.75 -0.5 -0.25 0. ]
(1)權重計算
N = int(sys.argv[1])
weights = np.exp(np.linspace(-1. , 0. , N))
(2)權重歸一化處理
weights /= weights.sum()
print "Weights", weights
#output
Weights [ 0.11405072 0.14644403 0.18803785 0.24144538 0.31002201]
(3)計算及作圖
c = np.loadtxt('data.csv', delimiter=',', usecols=(6,),unpack=True)
ema = np.convolve(weights, c)[N-1:-N+1]
t = np.arange(N - 1, len(c))
plot(t, c[N-1:], lw=1.0)
plot(t, ema, lw=2.0)
show()
3.26 用線性模型預測價格
(x, residuals, rank, s) = np.linalg.lstsq(A, b) #系數(shù)向量x、一個殘差數(shù)組、A的秩以及A的奇異值
print x, residuals, rank, s
#計算下一個預測值
print np.dot(b, x)
3.28 繪制趨勢線
x = np.arange(6)
x = x.reshape((2, 3))
x
array([[0, 1, 2], [3, 4, 5]])
np.ones_like(x) #用1填充數(shù)組
array([[1, 1, 1], [1, 1, 1]])
類似函數(shù)
zeros_like
empty_like
zeros
ones
empty
3.30 數(shù)組的修剪和壓縮
a = np.arange(5)
print "a =", a
print "Clipped", a.clip(1, 2) #將所有比給定最大值還大的元素全部設為給定的最大值,而所有比給定最小值還小的元素全部設為給定的最小值
#output
a = [0 1 2 3 4]
Clipped [1 1 2 2 2]
a = np.arange(4)
print a
print "Compressed", a.compress(a 2) #返回一個根據(jù)給定條件篩選后的數(shù)組
#output
[0 1 2 3]
Compressed [3]
b = np.arange(1, 9)
print "b =", b
print "Factorial", b.prod() #輸出數(shù)組元素階乘結果
#output
b = [1 2 3 4 5 6 7 8]
Factorial 40320
print "Factorials", b.cumprod()
#output
以下為python代碼,由于訓練數(shù)據(jù)比較少,這邊使用了批處理梯度下降法,沒有使用增量梯度下降法。
##author:lijiayan##data:2016/10/27
##name:logReg.pyfrom numpy import *import matplotlib.pyplot as pltdef loadData(filename):
data = loadtxt(filename)
m,n = data.shape ? ?print 'the number of ?examples:',m ? ?print 'the number of features:',n-1 ? ?x = data[:,0:n-1]
y = data[:,n-1:n] ? ?return x,y#the sigmoid functiondef sigmoid(z): ? ?return 1.0 / (1 + exp(-z))#the cost functiondef costfunction(y,h):
y = array(y)
h = array(h)
J = sum(y*log(h))+sum((1-y)*log(1-h)) ? ?return J# the batch gradient descent algrithmdef gradescent(x,y):
m,n = shape(x) ? ? #m: number of training example; n: number of features ? ?x = c_[ones(m),x] ? ? #add x0 ? ?x = mat(x) ? ? ?# to matrix ? ?y = mat(y)
a = 0.0000025 ? ? ? # learning rate ? ?maxcycle = 4000 ? ?theta = zeros((n+1,1)) ?#initial theta ? ?J = [] ? ?for i in range(maxcycle):
h = sigmoid(x*theta)
theta = theta + a * (x.T)*(y-h)
cost = costfunction(y,h)
J.append(cost)
plt.plot(J)
plt.show() ? ?return theta,cost#the stochastic gradient descent (m should be large,if you want the result is good)def stocGraddescent(x,y):
m,n = shape(x) ? ? #m: number of training example; n: number of features ? ?x = c_[ones(m),x] ? ? #add x0 ? ?x = mat(x) ? ? ?# to matrix ? ?y = mat(y)
a = 0.01 ? ? ? # learning rate ? ?theta = ones((n+1,1)) ? ?#initial theta ? ?J = [] ? ?for i in range(m):
h = sigmoid(x[i]*theta)
theta = theta + a * x[i].transpose()*(y[i]-h)
cost = costfunction(y,h)
J.append(cost)
plt.plot(J)
plt.show() ? ?return theta,cost#plot the decision boundarydef plotbestfit(x,y,theta):
plt.plot(x[:,0:1][where(y==1)],x[:,1:2][where(y==1)],'ro')
plt.plot(x[:,0:1][where(y!=1)],x[:,1:2][where(y!=1)],'bx')
x1= arange(-4,4,0.1)
x2 =(-float(theta[0])-float(theta[1])*x1) /float(theta[2])
plt.plot(x1,x2)
plt.xlabel('x1')
plt.ylabel(('x2'))
plt.show()def classifyVector(inX,theta):
prob = sigmoid((inX*theta).sum(1)) ? ?return where(prob = 0.5, 1, 0)def accuracy(x, y, theta):
m = shape(y)[0]
x = c_[ones(m),x]
y_p = classifyVector(x,theta)
accuracy = sum(y_p==y)/float(m) ? ?return accuracy
調(diào)用上面代碼:
from logReg import *
x,y = loadData("horseColicTraining.txt")
theta,cost = gradescent(x,y)print 'J:',cost
ac_train = accuracy(x, y, theta)print 'accuracy of the training examples:', ac_train
x_test,y_test = loadData('horseColicTest.txt')
ac_test = accuracy(x_test, y_test, theta)print 'accuracy of the test examples:', ac_test
學習速率=0.0000025,迭代次數(shù)=4000時的結果:
似然函數(shù)走勢(J = sum(y*log(h))+sum((1-y)*log(1-h))),似然函數(shù)是求最大值,一般是要穩(wěn)定了才算最好。
下圖為計算結果,可以看到訓練集的準確率為73%,測試集的準確率為78%。
這個時候,我去看了一下數(shù)據(jù)集,發(fā)現(xiàn)沒個特征的數(shù)量級不一致,于是我想到要進行歸一化處理:
歸一化處理句修改列l(wèi)oadData(filename)函數(shù):
def loadData(filename):
data = loadtxt(filename)
m,n = data.shape ? ?print 'the number of ?examples:',m ? ?print 'the number of features:',n-1 ? ?x = data[:,0:n-1]
max = x.max(0)
min = x.min(0)
x = (x - min)/((max-min)*1.0) ? ? #scaling ? ?y = data[:,n-1:n] ? ?return x,y
在沒有歸一化的時候,我的學習速率取了0.0000025(加大就會震蕩,因為有些特征的值很大,學習速率取的稍大,波動就很大),由于學習速率小,迭代了4000次也沒有完全穩(wěn)定。現(xiàn)在當把特征歸一化后(所有特征的值都在0~1之間),這樣學習速率可以加大,迭代次數(shù)就可以大大減少,以下是學習速率=0.005,迭代次數(shù)=500的結果:
此時的訓練集的準確率為72%,測試集的準確率為73%
從上面這個例子,我們可以看到對特征進行歸一化操作的重要性。
直接套公式再相乘就可以了。
對于離散型隨機變量,設一條樣本函數(shù)是w1,...wn,,其似然函數(shù)是P{W1=w1,...,Wn=wn}.....和連續(xù)型的時候是類似的
樣本值是0,1,2,0,2,1,對應的概率分別是theta,(1-2theta),theta,theta,theta,(1-2theta)。
似然函數(shù)就是得到這個樣本的概率,由于每次抽樣獨立,所以把這幾個概率乘起來就是得到這個樣本的概率了,也就是似然函數(shù)。
給定輸出x時,關于參數(shù)θ的似然函數(shù)L(θ|x)(在數(shù)值上)等于給定參數(shù)θ后變量X的概率:L(θ|x)=P(X=x|θ)。
分享題目:似然函數(shù)python代碼的簡單介紹
文章轉(zhuǎn)載:http://chinadenli.net/article27/dsedgjj.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供手機網(wǎng)站建設、自適應網(wǎng)站、企業(yè)網(wǎng)站制作、網(wǎng)站內(nèi)鏈、App開發(fā)、移動網(wǎng)站建設
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)