About me

Let me introduce myself


A bit about me

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident.

I have more than 5 years’ experience related to manufacturing of optical design ,Camera Module and also have some experience on coding . Having years of RD experience that cooperated with international ODM/OEM partners and optics-mechanical products development/DataAnalysis/research/process.

Profile

Deepak Bhagya

Personal info

Deepak Bhagya

If I have seen further than others, it is by standing upon the shoulders of giants.

Birthday: 21 Dec 1984
Phone number: +886
Website: https://bobobo746.blogspot.com
E-mail: 2dkjd1k@gmail.com

RESUME

Know more about my past


Employment

  • 2016-future

    https://www.ixensor.com/ix_web/ @ Optical-Software Programmer

    Optical-Signal algorithm and analysis: 1). Using smart phone’s front camera as optical-analysis device to observe color signal change. 2). Color signal change is based on the blood reacts with strips. 3.) By those signal change, trying to figure out a curve line to represent the bio-reacts on strips and use those feature to construct a measurement system. 4.) Trying to improve the bias, accuracy and precision. 5.) Issues fixed. Image process algorithm: 1.) Image Recognition: Analysis the image to make sure whether the optical device’s uniformity is qualified or not. Experiment Data Build: 1.) Using SQL to build Database for Experiment data. 2.) Producing API for co-workers to access and get some data source, reducing the data collecting time. 3.) Maintaining data base and trying to improve data schemas.

  • 2013-2016

    http://www.primax.com.tw/ @ Sr.Optical and Software Engineer

    1). Camera lens optical specifications define and analysis optical issue, likes the Flare, MTF(SFR), Alignment, Optical Center, and NG-sample analysis. 3). Lens focusing image recognition: Programming an application for machine to recognize the image and focus lens. 4). Con-call and report to customer, and vendor management.

  • 2010-2013

    www.Ledlink.com @ Optical Engineer

    1/ LED lighting lens module development, LED module development of TV backlight, new module development and spec. define. 2/ Optical design of LED lighting lens, jigs design, and solve process problems. 3/ Precision process development, new film materials analysis. 4/ New patent application . 5/ Optical simulation analysis

Education

  • 2006-2009

    University of NCUE @ graduated

    bachelor of science (physics)

  • *********.

Skills & My Love

Engineer
80%
software
WorkOut
91%
Fitting
Coding
95%
Python

Portfolio

My latest projects


2017年5月16日 星期二

macOS: Install OpenCV 3 and Python 2.7

macOS: Install OpenCV 3 and Python 2.7

開頭先引用下大陸網友針對安裝python+opencv所下的註解吧:

"如何正确安装OpenCV历来是一个堪称玄学的问题,在成功安装OpenCV的道路上经历了种种艰辛,这真的是我最恶心的一次安装经历"

認同,因為我也花了四天的時間在安裝。由於本身系統下之前就已經安裝過不同版本的python,再加上用的是notebook做分析開發。所以一直沒有正視過標準IDE+opencv。 藉著公司專案告一段落,就開始思考因為notebook的檔案格式是.ipynb很明顯地跟.py檔是不同,也意味著我在分析上用notebook可以很方便快速,但是如果當我要導入到Arduino或其他系統端要應用時就不可能了。 簡單來說就是該面對的還是要面對....

上網找了Pycharm做IDE,基本上設定相關沒太大問題,只是需要習慣下操作模式。(畫圖,import,debug,查看變數 等等 )
接下來要測試影像處理,之前在notebook上有 import cv2 ,原以為已經安裝成功了,雖然當時心裡想說 怎一下下就安裝好了??想當初在xcode上要安裝也是花了老半天。 果然在跑pycharm時候就報錯了:

The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or
Carbon support. If you are on Ubuntu or Debian, install libgtk2.0-dev and
pkg-config, then re-run cmake or configure script

一開始以為是少安裝了GTK之類的,上google上找看到大多數碰到這類error的好像都是ubuntu的系統,所以就開始到處亂安裝@@ 結果當然不行
後來仔細看看報錯原因,似乎是說明function沒有被implement,也就是說我安裝不完全。
想想也對,之前載opencv都好幾百mb然後安裝都要時間,我當初在terminal上用 pip install opencvㄧ下下就好 這差異也太大。

於是上網找了下資訊,最後找到有正解的教學:
http://www.pyimagesearch.com/2016/11/28/macos-install-opencv-3-and-python-2-7/
那到底難在哪呢?
前面提到,因為我系統本身就安裝過很多版本的python 有2也有3 後來安裝opencv2,3 也透過anaconda安裝過 也從官網下載過, 所以可以說是系統雜 亂。再加上教學上提到需要增加虛擬環境來安裝,雖然不是必要 ,再加上我覺得麻煩所以沒完全按照他的教學步驟,導致後來一直安裝不成功。。。

最後想開了,因為系統亂灌,最安全的方式,就是需要在乾淨的環境下安裝才能確保沒有其他因素造成安裝出問題,其實最大因素就是出在路徑啦!!!
所以依照上面網址教學一步步安裝確保都沒有不同就沒問題了。

在這邊補充一些如果python上有灌一堆版本,如: 透過brew ,官網,Anaconda,.....
在正式重新安裝時先把東西殺一殺:
- 官網的安裝了就安裝了,不用動
- anaconda 我是把它都殺掉因為其實我都沒用到它的安裝包,免得來亂
- 再來就是brew的部分,先把他殺掉。 因為教學的安裝路徑是以brew為主
- 可以先確認python安裝位置:
python
which python

一定要是:
python
usr/local/bin/python

如果不是,依照下面步驟:把他弄乾淨:

1.先在 ~/.bash_profile 裡面增加brew安裝路徑: https://gist.github.com/patriciogonzalezvivo/77da993b14a48753efda

export PATH=/usr/local/bin:$PATH

2.再到終端機:

\( brew uninstall --force python
\) brew install python
\( brew link --overwrite python
\) brew linkapps python
\( pip install --upgrade pip setuptools
\) sudo pip uninstall virtualenv
\( pip install virtualenv
\) sudo pip uninstall virtualenvwrapper
$ pip install virtualenvwrapper

3.再用which python確認位置是否正確,都沒錯就可以依照網頁教學正常安裝。http://www.pyimagesearch.com/2016/11/28/macos-install-opencv-3-and-python-2-7/

  1. 測試code: (先把安裝好後的環境引入pycharm再測試)
    import cv2
    image = cv2.imread("123.png")
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    cv2.imshow("Original", gray)
    cv2.waitKey(0)

  2. The perfect computer vision environment: PyCharm, OpenCV, and Python virtual environments :
    http://www.pyimagesearch.com/2015/08/17/the-perfect-computer-vision-environment-pycharm-opencv-and-python-virtual-environments/

2017年4月3日 星期一

均勻度

均勻度


#均勻度
%matplotlib notebook
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
from matplotlib import gridspec
from scipy import ndimage
from skimage import measure
import skimage



img = mpimg.imread('HiGary_OriginImage.png')       # float32
pp= skimage.img_as_float(img)                      # 轉 float64 ,(720, 1280, 4) ; signal range:0~1
#pp= skimage.img_as_ubyte(pp)                      # 轉u8-bit int ; signal range: 0~255

# 分兩個,0~255的為計算用
img1= (pp)
img1= img1*255
lum_img = img1[:,:,0]  

# 0~1 的為 找邊界用
img2= ((pp)*5.5/3)**22
img2= ndimage.gaussian_filter(img2,10)
img2[0:200,:,:]=0             
img2[520:720,:,:]=0           
lum_img2 = img2[:,:,0]      

#plt.imshow(lum_img,'gray')

# sobel 參數設定
mod= 'mirror'               
sx = ndimage.sobel(lum_img2, axis=0, mode=mod)
sy = ndimage.sobel(lum_img2, axis=1, mode=mod)
sob = np.hypot(sx, sy)
plt.figure(figsize=(8,6))
plt.imshow(sob,cmap='gray')
plt.show()

# find countour
contours = measure.find_contours(sob, 100)  
x_axis_data=[]
y_axis_data=[]

# 將找到輪廓的x,y座標存起來,裡面的每個array代表該輪廓的所有位置,x表示x所有位置,y表示y所有位置
for n, contour in enumerate(contours):    
  plt.plot(contour[:, 1], contour[:, 0], linewidth=2)
  x_axis_data= x_axis_data+ [contour[:, 1]]
  y_axis_data= y_axis_data+ [contour[:, 0]]

# 設定輪廓大小,假定x輪廓位置總數>500 才列入要找的輪廓,也才接近正圓,因為目前專案圓周大小約2*3.14*60 
x_wanted =[]    
for i in range(len(x_axis_data)):
  if len(x_axis_data[i])>500 and len(x_axis_data[i])<1000:
  x_wanted= x_wanted+[x_axis_data[i]]

y_wanted =[]
for i in range(len(y_axis_data)):
  if len(y_axis_data[i])>500 and len(x_axis_data[i])<1000:
  y_wanted= y_wanted+[y_axis_data[i]]


# 將找到的正圓輪廓找到圓心
x_center=[]
for i,label in enumerate(x_wanted):
  tempx= np.mean(x_wanted[i])
  x_center= x_center +[tempx]

y_center=[]
for i,label in enumerate(y_wanted):
  tempy= np.mean(y_wanted[i])
  y_center= y_center +[tempy]
xc,yc=[],[]
xj,xi=[],[]
# 因為找到的正圓輪廓可能大於三個,所以圓心也大於三個,於是要篩選:  
if len(x_center)>3:

  for i in range(len(x_center)-1):
  for j in range(-i+len(x_center)):
  # 如果圓心的x距離相差<50 且抽取的兩個樣本不同:
  if abs(x_center[j+i]-x_center[i])<50 and x_center[j+i]!=x_center[i]:
  xcc= (x_center[j+i]+x_center[i])/2
  xj= xj+[x_center[j+i]]
  xj=sorted(xj)
  xi= xi+[x_center[i]]
  xi=sorted(xi)
  xc= xc+[xcc]
  xc=sorted(xc)
  # 依照x找到的位置去找對應的y的位置

  for i in range(len(xj)):
  ycc=(y_center[x_center.index(xj[i])]+y_center[x_center.index(xi[i])])/2
  yc= yc+[ycc]

#畫圓心
  plt.figure(figsize=(8,6))
  plt.imshow(img)
  for gg in range(len(xj)):
  plt.scatter(xc[gg],yc[gg],marker= '*',c='r',s= 20)  
# 若沒到三個輪廓 或剛好,依樣顯示出來,不過有可能會沒定位到,可以先看圖再修正 曝光參數或輪廓邊界參數
else:
  xc= x_center
  xc= sorted(xc)
  for i in range(len(xc)):
  ycc=y_center[x_center.index(x_center[i])]
  yc= yc+[ycc]
  yc=sorted(yc)
  plt.figure(figsize=(8,6))
  plt.imshow(img)
  for gg in range(len(x_center)):
  plt.scatter(x_center[gg],y_center[gg],marker= '*',c='r',s= 20)   




# 計算均勻度           
x, y = np.meshgrid(np.arange(0, 1280, 1), np.arange(0, 720, 1))
contor_all=[]
for ij in range(len(xc)):
  contor = np.sqrt((x-xc[ij]) ** 2 + (y-yc[ij] )** 2)
  for j in range(720):
  for i in range(1280): 
  if contor[j][i]<30 :
  contor[j][i] =1.0
  else:
  contor[j][i]=0.0
  contor_all= contor_all+[contor]      

A= ((lum_img*contor_all[0]).sum())/(contor_all[0].sum())   
B= ((lum_img*contor_all[1]).sum())/(contor_all[1].sum())
C= ((lum_img*contor_all[2]).sum())/(contor_all[2].sum())
if C>B:
  ratio1= A/B
  ratio2= A/C
  ratio3= B/C
else:
  ratio1= A/B
  ratio2= A/C
  ratio3= C/B

# 畫掃描圖
fig = plt.figure(figsize=(8, 6)) 
gs = gridspec.GridSpec(2, 1, height_ratios=[5, 1.5]) # 因為圖片比例 與 畫圖 比例不對 必須重新設定比例
#plt.subplot(211)
plt.subplot(gs[0])
plt.imshow(lum_img,cmap='jet')
plt.plot( np.linspace(0,(img.shape[1])-10,num=(img.shape[1])-10,dtype=int) ,
  [360]*(img.shape[1]-10),lw=1,c='r')

upper = [360 + 30]*(img.shape[1]-10)
lower = [360 - 30]*(img.shape[1]-10)
plt.fill_between(np.linspace(0,(img.shape[1])-10,num=(img.shape[1])-10,dtype=int) , 
  lower, upper, color='#888888', alpha=0.4)

#plt.subplot(212)
plt.subplot(gs[1])

ybox=[]
for cc in range(lum_img.shape[1]-10):
  box= np.mean(lum_img[360-30:360+30,cc]) #算平均
  ybox=ybox+[box]
plt.plot(np.linspace(0,(img.shape[1])-10,num=(img.shape[1])-10,dtype=int) ,
  ybox,lw=2 ,c='g',alpha=0.1) # image 是三維矩陣查看方式: image[直,橫,rgb]
plt.grid()
plt.fill_between(np.linspace(0,(img.shape[1])-10,num=(img.shape[1])-10,dtype=int) ,
  ybox,lw=2 ,color='g',alpha=0.2)
plt.show()


print 'HDL/TG:{}'.format(ratio1),' HDL/TC:{}'.format(ratio2),' TG/TC:{}'.format(ratio3)





這封郵件來自 Evernote。Evernote 是您專屬的工作空間,免費下載 Evernote

圓心定位

圓心定位

一樣該import 的先import:

%matplotlib notebook
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
from matplotlib import gridspec
from scipy import ndimage
from skimage import measure
import skimage

以我專案碰的問題,來做處理: 因為過曝 所以不用再做filter處理

img = mpimg.imread('circleCenter.png') # float32
pp= skimage.img_as_float(img)          # 轉 float64 ,(720, 1280, 4) ; signal range:0~1
# pp2= skimage.img_as_ubyte(pp)        # 轉u8-bit int ; signal range: 0~255
# print pp2.dtype

# 過曝寫法
gamma= 1000
mag_signal =100

itest= (pp)
img2 = (itest)**gamma                 # 因為曝光,拉高對比度 所以乘以1000次方
img2[0:100,:,:]=0                    # 上面0~100 設為全黑
img2[600:720,:,:]=0                 # 下面600~720 設為全黑
l = img2[:,:,0]*mag_signal         # [x,y,channel] channel:0,1,2
plt.imshow(l,'gray')

mod= 'mirror'                     # sobel 參數設定
sx = ndimage.sobel(l, axis=0, mode=mod)
sy = ndimage.sobel(l, axis=1, mode=mod)
sob = np.hypot(sx, sy)
# plt.figure(figsize=(8,6))
# plt.imshow(sob,cmap='gray')

contours = measure.find_contours(sob, 100)    # find countour
x_axis_data=[]
y_axis_data=[]

# 將找到輪廓的x,y座標存起來,裡面的每個array代表該輪廓的所有位置,x表示x所有位置,y表示y所有位置
for n, contour in enumerate(contours):    
  #plt.plot(contour[:, 1], contour[:, 0], linewidth=2)
  x_axis_data= x_axis_data+ [contour[:, 1]]
  y_axis_data= y_axis_data+ [contour[:, 0]]

# 設定輪廓大小,假定x輪廓位置總數>500 才列入要找的輪廓,也才接近正圓,因為目前專案圓周大小約2*3.14*60 
x_wanted =[]    
for i in range(len(x_axis_data)):
  if len(x_axis_data[i])>500 and len(x_axis_data[i])<1000 :
  x_wanted= x_wanted+[x_axis_data[i]]

y_wanted =[]
for i in range(len(y_axis_data)):
  if len(y_axis_data[i])>500 and len(x_axis_data[i])<1000:
  y_wanted= y_wanted+[y_axis_data[i]]


# 將找到的正圓輪廓找到圓心
x_center=[]
for i,label in enumerate(x_wanted):
  tempx= np.mean(x_wanted[i])
  x_center= x_center +[tempx]

y_center=[]
for i,label in enumerate(y_wanted):
  tempy= np.mean(y_wanted[i])
  y_center= y_center +[tempy]

# 因為找到的正圓輪廓可能大於三個,所以圓心也大於三個,於是要篩選:  
if len(x_center)>3:
  xc =[]
  xj,xi=[],[]
  for i in range(len(x_center)-1):
  for j in range(-i+len(x_center)):
  # 如果圓心的x距離相差<50 且抽取的兩個樣本不同:
  if abs(x_center[j+i]-x_center[i])<50 and x_center[j+i]!=x_center[i]:
  xcc= (x_center[j+i]+x_center[i])/2
  xj= xj+[x_center[j+i]]
  xi= xi+[x_center[i]]
  xc= xc+[xcc]
  # 依照x找到的位置去找對應的y的位置
  yc =[]
  for i in range(len(xj)):
  ycc=(y_center[x_center.index(xj[i])]+y_center[x_center.index(xi[i])])/2
  yc= yc+[ycc]


  plt.figure(figsize=(8,6))
  plt.imshow(img)
  for gg in range(len(xj)):
  plt.scatter(xc[gg],yc[gg],marker= '*',c='r',s= 20)  
# 若沒到三個輪廓 或剛好,依樣顯示出來,不過有可能會沒定位到,可以先看圖再修正 曝光參數或輪廓邊界參數
else:
  plt.figure(figsize=(8,6))
  plt.imshow(img)
  for gg in range(len(x_center)):
  plt.scatter(x_center[gg],y_center[gg],marker= '*',c='r',s= 20)    

plt.show()

結果圖:





之前嘗試:
  • 想說findcontour找到的輪廓大多不是正確的,覺得分區塊做篩選又太不智能
所以嘗試了histogram解法,以及直接把照片的pixel轉成list 然後遍歷去找值為1的位置然後統計數量 最高的即為需求點。 不過兩者共通的毛病都是 運算量大導致運算速度過慢 最後放棄,仍然以findcontour為主,只是後來篩選方式就如我上面的原始碼依樣,設立圓周邊界需求,然後兩兩比較。
下面是之前嘗試的解法,雖然不實用但還是做些紀錄:

img = mpimg.imread('circleCenter2.png') # float32
pp= skimage.img_as_float(img) # 轉 float64 ,(720, 1280, 4) ; signal range:0~1
# pp2= skimage.img_as_ubyte(pp) # 轉u8-bit int ; signal range: 0~255
# print pp2.dtype

gamma= 100
mag_signal =50
itest= (pp)
img2 = (itest)**gamma
img2[0:100,:,:]=0
img2[600:720,:,:]=0
l = img2[:,:,0] # [x,y,channel] channel:0,1,2
#plt.imshow(l,'gray')

plt.figure()
aspectRatio = 6
gs = gridspec.GridSpec(aspectRatio,aspectRatio)

ax1 = plt.subplot(gs[0,:-1])
ax2 = plt.subplot(gs[1:,:-1])
ax3 = plt.subplot(gs[1:,-1])
plt.subplots_adjust(wspace=0.02, hspace=0.02)


tp=[]
xl=np.ravel(l)
for i in range (len(np.ravel(l))):
  if xl[i]>0.5:
  if i<1280:
  i=i
  else:
  i=(i%1280)
  tp= tp+[i]

ax1.hist(tp, bins= 40, ec='green', fc='none', histtype='bar')
ax2.imshow(l,'gray')
#ax3.hist(y, bins =360, ec='green', fc='none', histtype='step', orientation='horizontal')

結果圖:





img = mpimg.imread('circleCenter2.png') # float32
pp= skimage.img_as_float(img) # 轉 float64 ,(720, 1280, 4) ; signal range:0~1
# pp2= skimage.img_as_ubyte(pp) # 轉u8-bit int ; signal range: 0~255
# print pp2.dtype

gamma= 100
mag_signal =50
itest= (pp)
img2 = (itest)**gamma
img2[0:100,:,:]=0
img2[600:720,:,:]=0
l = img2[:,:,0]*mag_signal # [x,y,channel] channel:0,1,2
#plt.imshow(l,'gray')

plt.figure()
aspectRatio = 6
gs = gridspec.GridSpec(aspectRatio,aspectRatio)

ax1 = plt.subplot(gs[0,:-1])
ax2 = plt.subplot(gs[1:,:-1])
ax3 = plt.subplot(gs[1:,-1])
plt.subplots_adjust(wspace=0.02, hspace=0.02)


binSize = 2
x1= np.arange(1280)
x=[]
for _ in range(720):
  x= (np.append(x,x1))
y= np.ravel(l)

y1= np.arange(720)
yy=[]
for _ in range(1280):
  yy= (np.append(yy,y1))
xx= np.ravel(l.T)


ax1.plot(x,y,lw=0.01,alpha=0.5,c='k')
ax2.imshow(l,'gray')
ax3.plot(xx,yy,lw=0.01,alpha=0.5,c='k')





這封郵件來自 Evernote。Evernote 是您專屬的工作空間,免費下載 Evernote

2017年3月28日 星期二

python 語法筆記(不斷更新)

python 語法筆記(不斷更新)


  • python,numpy,pandas数据处理之小技巧

  • 排序: iterable為放置需要排序的陣列或是list(可迭代),reverse則是看要不要反過來排序,預設是false
sorted(   iterable   ,reverse= False)    

  • 排序:(np.sort) 排序。可以依照raw or column來排序
np.sort(  iterable  ,axis =0 )


list array 問題
  • list ,ndarray 小數轉int:
np.around(list or ndarray)

  • list與array:
list  : [object]
            
                        /  一維 :  不等於 list ,要轉成list ,使用 :  list(   array   ) 
array: np開頭 
               \  多維 : 要降成一維 ,使用 :   .ravel()


  • list(str) : 把str轉成list:str裡面的每個字元都被當成'字串': 
str= 'hello'
list(str)

  • list轉array 
np.asarray(list)

  • 一維array轉2維:
np.reshape(1-Darray, (幾x幾) )

  • List  新增:
                     a=[1,2,3,4]
                     b=[5,6,7,8]
c = a+b                    #直接用 +  即可
a.append(b[0])             #用b[0]

print c
[1, 2, 3, 4, 5, 6, 7, 8]
print a
[1, 2, 3, 4, 5]


  • array新增(一維): np.append
    •     aa= np.array([1,2,3,4])
    •     bb= np.array([5,6,7,8])
cc1= aa+bb                 #在array裡若直接用 + 則是進行array內運算
cc2= np.append(aa,bb)      #需使用append ,一維是橫向往後增加

print cc1
[ 6  8 10 12]
print cc2
[1 2 3 4 5 6 7 8]
                         (二維):  np.append
aa2= np.reshape(aa,(1,4))
bb2= np.reshape(bb,(1,4))
cc2= np.append(aa2,bb2,axis=0)     # 二維 可指定axis,0則是往下堆疊
cc3= np.append(aa2,bb2,axis=1)     # 二維 可指定axis,1則是往橫向堆疊
cc4= np.append(aa2,bb2)            # 若不指定axis 則轉為一維的array

print cc2
[[1 2 3 4]
 [5 6 7 8]]
print cc3
[[1 2 3 4 5 6 7 8]]
print cc4
[1 2 3 4 5 6 7 8]

  • List 移除 插入
lis =[1,2,3,4,5]
lis.remove(lis[0])  #移除第一個
lis.insert(0,'error') . # 在第0的位置 插入error字串

  • List replace:
原list =[w.replace( '原本的字符','要改成的字符') for w in 原list]    # w是遍歷用的

  • 字串拆解和結合(list)---結合:   .join  把原本list裡的char 依照串接的字符變成新的字串
新str= '要串接的字符'.join([原char])    #  '要串接的字符'比如 :','  '.' 之類

  • 字串拆解和結合(list)---拆解: .split()  把原本的字串拆解並存成list
新list= 字串.split('依照該字符做拆解')  #  依照提供的特徵:字符 做拆解 並轉為list裡面的index

  • list刪除:
del list[index]  #直接指定要刪除的位置index

  •  ndarray 裡的值如果要修改:
1D array: ndarray.itemset( 位置, 要改成的值 )  
2D array: ndarray.itemset( (位置,位置) 要改成的值 ) 

  • pandas 轉array ,list
# 轉array:
df[column].as_matrix()
   
# 轉list:
df[column].values.tolist()




  • 取值的位置(index):
a= [10,20,30,40,50]
a.index(10)
回傳 0

  • input() 與raw_input():
input("想顯示的東西")  之後回傳只能keyin 數字 
raw_input("想顯示的東西") 。之後回傳能keyin 數字與字串

  • 把滑鼠複製的data轉成dataframe:
import pandas as pd
y= pd.read_clipboard()


存讀檔
1. npy讀寫效率最高,但最佔硬碟空間,比如np.load(), np.save();

2. csv其次,比如pd.Dataframe.to_csv(),pd.load_csv();

3. txt讀寫,當然也可以很快,但是需要频繁的split,對格式規範的數據比较麻烦;

4. 至於簡單的excel和word,可以用xlrd,xlwt來操作
  • 一般存檔:
a= [1,2,3,4]
with open ('filename' , 'w' ) as f:
     pickle.dump( a , f )
  • 一般讀檔: pickle沒有副檔名
pickle.load(  open('filename', 'r')     )

  • pandas存pickle檔:
dataframe.to_pickle('檔名.pickle')

  • pandas讀pickle檔:
pd.read_pickle('檔名.pickle')

  • numpy 存檔:(自動存成npy檔):
np.save( '檔名',   要存的list 或 array  )
  • numpy 讀檔:
np.load( ' 檔名.npy'  )

  • text讀檔: 讀出來格式是str 字符串
 with open(txtfile)as f: 
   Text_str = f.read() 


os操作:遍歷,新增:
1. 新建文件夹:
if not os.path.isdir(path_out):
  os.makedirs(path_out)

2. 遍歷所有文件和子文件夹:                     # a: 路徑  b:資料夾  c:總文件 
for a, b, filenames in os.walk(path_data):
  for filename in filenames:

3.只遍歷當前文件,不包含子文件夹:
for a, b, filenames in os.walk(path_data):
  for filename in filenames:
  if a == path_data:





確認nan 布林
  • 確認dataframe是否為null:
pd.isnull(object)

  • 確認array是否為null:
np.nan(array)

  • 設定nan:
np.nan

  • 用 np.isfinite() 判斷布林值
x=np.array([1,2,np.nan,4,5]) 
np.isfinite(x)
  • 再利用上面的判斷 ,忽略nan值
import numpy as np
import matplotlib.pyplot as plt

time=np.array([1,2,3,4,5]) 
f1=np.array([1,2,np.nan,4,5]) 

#忽略nan ,因為丟進[]裡面所以假使是2d array也會被轉成一維
plt.plot(time[np.isfinite(f1)], f1[np.isfinite(f1)])  
plt.show()

  • numpy.ndarray 的nan填補:
example = np.where(np.isnan(example), 0, example)
example = np.where(np.isnan(example), 0, example)

  • dataframe 的nan填補:
可以用example.fillna()  也可以用example.replace(a, b)





  • 線性迴歸:
from scipy import stats
# 斜率 。 截距 。 變異係數 。相關係數 。 標準誤差
slope, intercept, r_value, p_value, std_err = stats.linregress(wait,what)
r_value**2

  • 畫圖的colormap設定 與 c的隨機配色
plt.scatter(x,y, s=20, c=np.random.rand(100),marker='o', cmap=plt.cm.jet, alpha= 0.5 )


plt.scatter(x[u],y[u], s=10, c=(np.random.rand(),np.random.rand(),np.random.rand()),
  marker='o', alpha= 0.3 )

  • 要把list裡面的數字都round(取小數四捨五入):
lis= [55.45,15.5,33.9]
ss= [round(i,0) for i in lis]     #小數點後0位 四捨五入




這封郵件來自 Evernote。Evernote 是您專屬的工作空間,免費下載 Evernote

2017年3月16日 星期四

class 下的 global ,self 筆記

class 下的 global ,self 筆記


x=999
class C:
  x= 6666
  def function(self):
      print x
      print self.x
  def define(self):
      print self.x
  def correct(self):
      self.x= 899
      print self.x
  def react():
      x= 89
      print x
c=C()

  • c=C() :把c實體化
  • class下的x=6666 為class專屬的變數,如果在函數內要print,使用 或改變就要使用self.x  否則只寫 print x 會跑出外部的x =999
  • print (c.x) 結果為 6666 因為class C 下的 x 是6666 。 之後若運行到c.correct() 因為已改變self.x 所以若再print (c.x) 則為899
  • def react()下的 x=89 為該函數內自定義的變數,不會改變到外面 也不會受外面影響。

x=999
class C:
  global x
  x= 6666
  def function(self):
      print x
      print self.x
  def define(self):
      print self.x
  def correct(self):
      self.x= 899
      print self.x
c=C()

  • 如果在class加上global x 且賦予該變數為6666 是說改變了x=999 為6666 並不是在class 內定義變數 ,所以使用self.x會報錯(因為class內沒有定義專屬的變數)
  • print (c.x) 結果會報錯 , 因為尚未定義class C的變數,之後若運行到c.correct() 因為設定了self.x 所以若再print (c.x) 則為899






這封郵件來自 Evernote。Evernote 是您專屬的工作空間,免費下載 Evernote

2017年3月13日 星期一

Pandas Dataframe 語法

Pandas Dataframe 語法


import pandas as pd
import numpy as np

                        pandas dataframe API
        pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)
# attribute:(.即可)
'''DataFrame.size # 資料總數
  .shape # 幾乘幾的dataframe
  .values # 把 dataframe 轉成 2維 array
  .ndim # 維度
  .T # 轉置
  .dtypes # data types(看是整數還浮點數)
  .axes # 查看 index 跟 columns 名稱
  .ix # Lable 在該index 對應的資料,可以放index數字也可以放label文字 
  .loc # Lable 在該index 對應的資料 (只能放label文字 )
  [] # 第一個中括號,看columns的資料內容 ,後面補上的第二個括號是該columns對應的label
  .insert()# 插入:.insert(要插在第幾個column位置,安插的名稱,安插資訊內容)
'''            
df = pd.DataFrame(np.random.rand(4,3),index=['a','b','c','d'],columns =['A','B','C'])
print df.size
print df.shape
print df.values
print df.ndim
print df.dtypes
print df.axes
print df.ix[0]
print df.ix['a']
print df.loc['a']
print df['A']['a']

# method:(.小括號)
df = pd.DataFrame(np.random.randn(4,3),index=['a','b','c','d'],columns =['A','B','C'])
df2= pd.DataFrame(np.random.randn(4,1),index=['w','x','y','z'],columns =['A'])
'''
DataFrame
  <合併刪除>
  .add(other, axis='columns') # data相加,但是一定要columns名稱相同
  .append(other, ignore_index=False ) # 新增資料合併用,雷同merge
  .merge(right,how='inner') # 新增資料合併用 找相同columns然後從下面補上去,預設為交集(inner,可改為outer聯集
  .join(other,how='left') # 新增資料合併用,left:以原資料為主,other為新增,right則相反)
  .drop(labels) # 剔除label資料 (刪除columns: del df[] 沒有.點)

  <數值計算>
  .describe() # 幫忙計算資料的數量, mean, std,cv...等等
  .abs() # 絕對值
  .idxmax(axis) # 比較大小(依照axis :0就是ABC比,順序:橫向 1就是abcd比,順序:直立)
  .idxmin(axis)
  .mean(axis) # axis=0 A平均B平均C平均;axis=1 a平均b平均c平均d平均
  .min(axis) # axis=0 找A最小B最小C最小;axis=1 找a最小b最小c最小d最小
  .round([decimals]) # 取小數點幾位
  .std(axis=None) # 計算std ,依照指定的axis =0 或1
  .sum(axis= None) # 計算sum ,依照指定的axis =0 或1

  <獲取,查看資料>
  .get_values() # 等同於DataFrame.values
  .head(n) # 只列出前n列的資料 沒寫就是前五列
  .keys() # 只查看columns名稱

  <修改欄位>
  .reset_index(drop=True) # 如果今天index的lable順序因為合併變成雜亂,可以用這個重新從0開始排序(要寫true不然原先的index會留著)       
  .rename(index={ },columns= { }) # label與columns命名修改
  .swapaxes(axes1,axes2) # column ,index 互換
  .transpose() # column ,index 互換

  <修改內容>
  .df.shift(periods=1,axis=0) # shift,perios看要移動幾格, axis 看是移動直向還是橫向
  .set_value(index,col,value) # 設定資料內容, index,column都要是label value為要設定的資訊
  .sort_values(by=[],axis=0) # axis=0 依照ABC欄位去做abcd排序 by要填入column的label即A,B,C ,axis=1則相反 .  

  <存檔格式>
  .to_csv('.... .csv') # 轉成csv檔 改路徑就直接把路徑寫出最後補上.csv即可 (用pd.read_csv()讀檔案)
  .to_pickle('.... .pickle') # 轉成pickle檔 改路徑就直接把路徑寫出最後補上.pickle即可
  .to_json('.... .json') # 轉成json string檔 改路徑就直接把路徑寫出最後補上.json即可

  <更新>
  .update(other[]) # 更新other[] 中括號裡面上的是要更新column的lable。更新要確認index是否相同 否則更新無效     
'''     
print df
print df2
print df.append(df2,ignore_index =True)
print df.describe()
print df.drop('a')
print df.get_values()
print df.head(2)
print df.idxmax(0)
print df.idxmax(1)

#######移動shift 且新增資訊方式:
df3 =df.shift(axis=1)
print df3
val =[10,20,30,40]
label= ['a','b','c','d']     
for index,i in enumerate (val):
  df3 =df3.set_value(index =label[index],col='A',value=i)
print df3
########
print df.sort_values(by=['a','b','c','d'],axis=1)

pandas, series 其他語法

# dot 用法 : 矩陣相乘
s1 = pd.Series(np.arange(1,5)) 
s1.dot(s1)

# series- dictionary用法:
d ={'one':pd.Series([1,2,3],index=['a','b','c']),
  'two':pd.Series([4,5,6],index=['d','e','f']) }
print (d['one'])
df= pd.DataFrame(d)
print
print (df)
print
print(pd.DataFrame(d,index=['b','c','f']))

# list-dictionary用法:
t= [{'a':10, 'b':20},{'a':5,'b':300,'c':1}]
pd.DataFrame(t)

# DataFrame.from_item 用dictonary來幫dataframe的column命名:
df= pd.DataFrame.from_items([('a',[1,2,3]),('b',[4,5,6])])
print(df)
print
print(df.T)

# DataFrame.from_item 用dictonary方式來命名, 但加了orient就變成轉置只是強制要幫column命名:
df= pd.DataFrame.from_items([('a',[1,2,3]),('b',[4,5,6]),('c',[7,8,9]),('d',[10,11,12])],
  orient='index',columns=['one','two','three'])
df

# 可以做運算 也可以用flag做布林值判定
df['three'] =df['one']*df['two']
df['flag']= df['one']>2
df

# 刪除整個columns就 del (刪除整個index 用drop)
del df['three']
df

# 新增欄位直接寫要的欄位名稱 ,不過index內容全部統一(除非用condat合併才可以放入其他資訊)
df['date'] = '2017-03'
df

# 插入:insert(要插在第幾個column位置,安插的名稱,安插資訊內容)
df.insert(4,'james gordan',df['one'])
df

# 從欄位找資料:
print (df['one'])
print 
# 用loc,從 lable找資料 (也可以用iloc用index找資料):
print (df.loc['a']) # Same as : df.iloc[0]

# 切片用法:在df是切片用法,即切片起始0在空的lable那裏,所以a是1, 1:3 取兩個,頭不算 所以取2,3
df[1:3] # 與 d[:3]:從頭開始取到第3個不同含義

pandas concat 合併語法
pandas.concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False, keys=None, levels=None, names=None)
# concat 兩個dataframe做合併 依照aixs軸設定 ,是新創的記憶體位置
df = pd.DataFrame(np.random.randn(4,3),index=['a','b','c','d'],columns =['A','B','C'])
df2= pd.DataFrame(np.random.randn(4,1),index=['w','x','y','z'],columns =['D'])
pd.concat([df,df2],ignore_index='True',axis=0)










這封郵件來自 Evernote。Evernote 是您專屬的工作空間,免費下載 Evernote

2017年3月10日 星期五

Demo_Pandas plot

Demo_Pandas plot


%matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
Plot
# simple plot
df = pd.DataFrame(np.random.randn(1000, 4), columns=['A', 'B', 'C', 'D'])
df.plot()
plt.figure();
df['A'].plot()
plt.figure();
df['A'].cumsum().plot()

# subplots 提供了多張圖示出現在一畫面的方式
df.plot(subplots=True, alpha =0.5,figsize=(6, 6))

# kde: density plots
df['A'].plot(kind='kde')
Bar plot
# 看DataFrame橫向: 另外也展示了堆疊的方式(stack)
df = pd.DataFrame(np.random.rand(10, 4), columns=['A', 'B', 'C', 'D'])
df.plot(kind='bar',alpha =0.8)
df.plot(kind='bar', stacked=True)

# 橫向bar堆疊(barh)
df.plot(kind='barh',alpha =0.8, stacked=True)
Histgram plot
# 看DataFrame縱向: A,B,C,D 的高斯分佈
df = pd.DataFrame(np.random.randn(100, 4), columns=['A', 'B', 'C', 'D'])
df.plot(kind='hist',alpha= 0.8)
df.plot(kind='hist',alpha= 0.5, stacked=True,bins= 50)
plt.figure()
df['A'].plot(kind='hist',bins= 10)

# df.diff().hist 提供了多張圖示出現在一畫面的方式
df.diff().hist(color='k', alpha=0.5, bins=30)

# subplots 提供了多張圖示出現在一畫面的方式
df.plot(kind='hist',subplots=True, alpha =0.5,figsize=(6,8),color='k',bins=30)
Area plot
# 都要是正數範圍;stack 可以改為透明
df = pd.DataFrame(np.random.rand(10, 4), columns=['A', 'B', 'C', 'D'])
df.plot(kind='area',alpha=0.5)
df.plot(kind='area', stacked=False)
Scatter plot
# simple scatter plot
df = pd.DataFrame(np.random.rand(50, 6), columns=['A', 'B', 'C', 'D','E','F'])
df.plot(kind='scatter', x='A', y='B')

# a3 為 A,B,C 對應E,F,G散佈圖
a1 = df.plot(kind='scatter', x='A', y='B',color='DarkBlue', label='Group 1')
a2 = df.plot(kind='scatter',x='C',y='D',color='DarkGreen', label='Group 2',ax = a1 )
a3 = df.plot(kind='scatter',x='E',y='F',color='k', label='Group 3',alpha =0.6 ,ax = a2 )

# s為圓點大小;c代表顏色用C的資料點代表顏色強度;colormap沒寫則預設黑色
df.plot(kind='scatter', x='A', y='B',c='C', colormap='OrRd', s=60)

# s為圓點大小,用C資料來改變點大小
df.plot(kind='scatter', x='A', y='B',c='k', s=df['C']*200)

# 六角形
df.plot(kind='hexbin', x='A', y='B', gridsize=15)

                                                                       Other Example(共用)
scatter_matrix: 展示了matrix的比較圖. 
e.g: A資料自己的常態分佈圖或是A,B . A,C . A,D 的散佈圖
from pandas.tools.plotting import scatter_matrix
df = pd.DataFrame(np.random.randn(1000, 4), columns=['A', 'B', 'C', 'D'])
scatter_matrix(df, alpha=0.2, figsize=(6, 6), diagonal='kde')

增加右邊y軸數值
df = pd.DataFrame(np.random.randn(1000, 4), columns=['A', 'B', 'C', 'D'])
df.A.plot(c='r')
df.B.plot(secondary_y=True, style='g')

增加右邊y軸數值與標籤
df = pd.DataFrame(np.random.randn(1000, 4), columns=['A', 'B', 'C', 'D'])
df= df.cumsum()
ax = df.plot(secondary_y=['A', 'B'])
ax.set_ylabel('CD scale')
ax.right_ax.set_ylabel('AB scale')

針對各資料設定顏色
df = pd.DataFrame(np.random.randn(1000, 4), columns=['A', 'B', 'C', 'D'])
df= df.cumsum()
with pd.plot_params.use('x_compat',True):
  df.A.plot(c='k')
  df.B.plot(c='m')
  df.C.plot(c='y')
  df.D.plot(c='grey')
  
提供了多張圖示出現在一畫面的方式
df = pd.DataFrame(np.random.randn(1000, 4), columns=['A', 'B', 'C', 'D'])
df= df.cumsum()
df.plot(subplots=True, figsize=(6, 6));

df = pd.DataFrame(np.random.randn(1000, 4), columns=['A', 'B', 'C', 'D'])
df= df.cumsum()
# subplot 排列方法 :layout=(2, 3)->(raw,column):
df.plot(subplots=True, layout=(2, 3), figsize=(6, 6), sharex=False);
# subplot 排列方法 :指定哪個raw哪個column放哪個資料:
fig, axes = plt.subplots(nrows=2, ncols=2)
df['A'].plot(ax=axes[0,0],c='k') ; axes[0,0].set_title('A');
df['B'].plot(ax=axes[0,1],c='k',alpha =0.7); axes[0,1].set_title('B');
df['C'].plot(ax=axes[1,0],c='k',alpha= 0.4); axes[1,0].set_title('C');
df['D'].plot(ax=axes[1,1],c='k',alpha= 0.1); axes[1,1].set_title('D');

subplot ,增加cv bias mean等的資訊在table欄位
from pandas.tools.plotting import table
df = pd.DataFrame(np.random.randn(1000, 4), columns=['A', 'B', 'C', 'D'])
df= df.cumsum()

fig,ax = plt.subplots(1, 1)
# describe():會幫忙算出cv bias mean...
# table 用來顯示欄位用的
table(ax, np.round(df.describe(), 2),loc='upper left', colWidths=[0.1, 0.1, 0.1,0.1])
df.plot(ax=ax,figsize=(10, 10))
 colormap
from pandas.tools.plotting import table
df = pd.DataFrame(np.random.randn(1000, 4), columns=['A', 'B', 'C', 'D'])
df= df.cumsum()
df.plot(colormap='Greens')










這封郵件來自 Evernote。Evernote 是您專屬的工作空間,免費下載 Evernote

Services

What can I do


Branding

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Web Design

Quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Donec sit amet venenatis ligula. Aenean sed augue scelerisque.

Graphic Design

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident.

Development

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident.

Photography

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod. Donec sit amet venenatis ligula. Aenean sed augue scelerisque, dapibus risus sit amet.

User Experience

Quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Donec sit amet venenatis ligula. Aenean sed augue scelerisque, dapibus risus sit amet.

Contact

Get in touch with me


Adress/Street

12 Street West Victoria 1234 Australia

Phone number

+(12) 3456 789

Website

www.johnsmith.com