pythonravel
㈠ 圖像直方圖均衡化
一. 直方圖均衡化:
直方圖均衡化是使圖像直方圖變得平坦的操作。直方圖均衡化能夠有效地解決圖像整體過暗、過亮的問題,增加圖像的清晰度。
具體流程如下所示。其中S是總的像素數,Zmax是像素的最大取值(8位灰度圖像為255),h(i)為圖像像素取值為 i 及 小於 i 的像素的總數。
二. python實現直方圖均衡化操作
import cv2
import numpy as np
import matplotlib.pyplot as plt
# histogram equalization
def hist_equal(img, z_max=255):
H, W = img.shape
S = H * W * 1.
out = img.()
sum_h = 0.
for i in range(1, 255):
ind = np.where(img == i)
sum_h += len(img[ind])
z_prime = z_max / S * sum_h
out[ind] = z_prime
out = out.astype(np.uint8)
return out
# Read image
img = cv2.imread("../head_g_n.jpg",0).astype(np.float)
# histogram normalization
out = hist_equal(img)
# Display histogram
plt.hist(out.ravel(), bins=255, rwidth=0.8, range=(0, 255))
plt.show()
plt.savefig("out_his.png")
# Save result
cv2.imshow("result", out)
cv2.imwrite("out.jpg", out)
cv2.waitKey(0)
cv2.destroyAllWindows()
三. 實驗結果:
可以看到,直方圖均衡化後的圖像看起來比原來的圖像更加清晰。對於圖像亮度整體偏暗或者偏亮的圖像,我們可以採用直方圖均衡化的方法處理圖像,使得它們看上去更加清晰。
四. matlab 實現圖像直方圖均衡化:
可以參考一篇優秀的博文: https://blog.csdn.net/Ibelievesunshine/article/details/79961027
五. 參考內容:
https://www.cnblogs.com/wojianxin/p/12510797.html
https://blog.csdn.net/Ibelievesunshine/article/details/104922449
㈡ python如何減小維度
ravel():將多維數組拉平(一維)。
flatten():將多維數組拉平,並拷貝一份。
squeeze():除去多維數組中,維數為1的維度,如315降維後3*5。
reshape(-1):多維數組,拉平。
reshape(-1,5):其中-1表示我們不用親自去指定這一維度的大小,理解為n維。
python學習網,大量的免費python視頻教程,歡迎在線學習!
㈢ python數據分析與應用第三章代碼3-5的數據哪來的
savetxt
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 統計分析
np.median(c) 中位數
np.msort(c) 升序排序
np.var(c) 方差
3.12 分析股票收益率
np.diff(c) 可以返回一個由相鄰數組元素的差
值構成的數組
returns = np.diff( arr ) / arr[ : -1] #diff返回的數組比收盤價數組少一個元素
np.std(c) 標准差
對數收益率
logreturns = np.diff( np.log(c) ) #應檢查輸入數組以確保其不含有零和負數
where 可以根據指定的條件返回所有滿足條件的數
組元素的索引值。
posretindices = np.where(returns > 0)
np.sqrt(1./252.) 平方根,浮點數
3.14 分析日期數據
# 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) #按數組的元素運算,產生一個數組作為輸出。
>>>a = [4, 3, 5, 7, 6, 8]
>>>indices = [0, 1, 4]
>>>np.take(a, indices)
array([4, 3, 6])
np.argmax(c) #返回的是數組中最大元素的索引值
np.argmin(c)
3.16 匯總數據
# 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]
#創建一個數組,用於存儲三周內每一天的索引值
weeks_indices = np.arange(first_monday, last_friday + 1)
#按照每個子數組5個元素,用split函數切分數組
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") #指定了文件名、需要保存的數組名、分隔符(在這個例子中為英文標點逗號)以及存儲浮點數的格式。
.png
格式字元串以一個百分號開始。接下來是一個可選的標志字元:-表示結果左對齊,0表示左端補0,+表示輸出符號(正號+或負號-)。第三部分為可選的輸出寬度參數,表示輸出的最小位數。第四部分是精度格式符,以」.」開頭,後面跟一個表示精度的整數。最後是一個類型指定字元,在例子中指定為字元串類型。
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函數創建一個長度為N的元素均初始化為1的數組,然後對整個數組除以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) 使用這些權重值,調用convolve函數:
c = np.loadtxt('data.csv', delimiter=',', usecols=(6,),unpack=True)
sma = 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, sma, lw=2.0)
show()
3.22 計算指數移動平均線
指數移動平均線(exponential moving average)。指數移動平均線使用的權重是指數衰減的。對歷史上的數據點賦予的權重以指數速度減小,但永遠不會到達0。
x = np.arange(5)
print "Exp", np.exp(x)
#output
Exp [ 1. 2.71828183 7.3890561 20.08553692 54.59815003]
Linspace 返回一個元素值在指定的范圍內均勻分布的數組。
print "Linspace", np.linspace(-1, 0, 5) #起始值、終止值、可選的元素個數
#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, resials, rank, s) = np.linalg.lstsq(A, b) #系數向量x、一個殘差數組、A的秩以及A的奇異值
print x, resials, 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填充數組
array([[1, 1, 1], [1, 1, 1]])
類似函數
zeros_like
empty_like
zeros
ones
empty
3.30 數組的修剪和壓縮
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) #返回一個根據給定條件篩選後的數組
#output
[0 1 2 3]
Compressed [3]
b = np.arange(1, 9)
print "b =", b
print "Factorial", b.prod() #輸出數組元素階乘結果
#output
b = [1 2 3 4 5 6 7 8]
Factorial 40320
print "Factorials", b.cumprod()
#output
㈣ python中fig,ax=plt.subplots什麼意思
fig,ax=plt.subplots的意思是將plt.subplots()函數的返回值賦值給fig和ax兩個變數。
plt.subplots()是一個函數,返回一個包含figure和axes對象的元組,因此,使用fig,ax=plt.subplots()將元組分解為fig和ax兩個變數。
通常,我們只用到ax:
fig,ax = plt.subplots(nrows=2, ncols=2)
axes = ax.flatten()
把父圖分成2*2個子圖,ax.flatten()把子圖展開賦值給axes,axes[0]便是第一個子圖,axes[1]是第二個。
(4)pythonravel擴展閱讀
在matplotlib中,整個圖像為一個Figure對象。在Figure對象中可以包含一個或者多個Axes對象。每個Axes(ax)對象都是一個擁有自己坐標系統的繪圖區域。所屬關系如下:
def subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True,
subplot_kw=None, gridspec_kw=None, **fig_kw):
參數:
nrows,ncols:子圖的行列數。
sharex, sharey:
設置為 True 或者 『all』 時,所有子圖共享 x 軸或者 y 軸,
設置為 False or 『none』 時,所有子圖的 x,y 軸均為獨立,
設置為 『row』 時,每一行的子圖會共享 x 或者 y 軸,
設置為 『col』 時,每一列的子圖會共享 x 或者 y 軸。
返回值
fig:matplotlib.figure.Figure對象
ax:子圖對象(matplotlib.axes.Axes)或者是他的數組
㈤ 神經網路,python報錯:AttributeError: 'DataFrame' object has no attribute 'ravel'
y_train.values.ravel()
這樣試試,因為你的y不是一維向量。
我建議你先看看數據
㈥ 求python多元支持向量機多元回歸模型最後預測結果導出代碼、測試集與真實值R2以及對比圖代碼
這是一個多元支持向量機回歸的模型,以下是一個參考的實現代碼:
import numpy as npimport matplotlib.pyplot as pltfrom sklearn import svmfrom sklearn.metrics import r2_score
# 模擬數據
np.random.seed(0)
X = np.sort(5 * np.random.rand(80, 1), axis=0)
y = np.sin(X).ravel()
y[::5] += 3 * (0.5 - np.random.rand(16))
# 分割數據
train_X = X[:60]
train_y = y[:60]
test_X = X[60:]
test_y = y[60:]
# 模型訓練
model = svm.SVR(kernel='rbf', C=1e3, gamma=0.1)
model.fit(train_X, train_y)
# 預測結果
pred_y = model.predict(test_X)# 計算R2r2 = r2_score(test_y, pred_y)
# 對比圖
plt.scatter(test_X, test_y, color='darkorange', label='data'指敏)
plt.plot(test_X, pred_y, color='navy', lw=2, label='SVR model')
plt.title('R2={:.2f}'.format(r2))
plt.legend()
plt.show()
上面的代碼將數據分為訓練數據和測試數據,使用SVR模型對訓練唯配枝數據進行訓練,然後對測試數據進行預測。計算預測結果與真實值的R2,最後賣逗將結果畫出對比圖,以評估模型的效果。
㈦ Python 列表List轉Numpy的Array:List[[1,2],[3,4]]只具有一個維度,怎麼樣表達3這個元素
如果你是想把array([[1,2],[3,4]])捋平,變成array([1,2,3,4]),有三種方式:flat屬性,flatten方法,ravel方法
如:
>>> import numpy as np
>>> a = np.array([[1,2],[3,4]])
>>> a
array([[1,2],
[3,4]])
>>> b = np.array(a.flat)
>>> b
array([1,2,3,4])
>>> c = a.flatten()
>>> c
array([1,2,3,4])
>>> d = a.ravel()
>>> d
array([1,2,3,4])