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年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

2017年3月8日 星期三

python opencv in MAC 視窗問題

python opencv in MAC 視窗問題

我在mac 裡編譯python只要用到視窗跳出在關閉時都會怪怪的。
opencv的imshow()這邊就會碰到..
網路上看了以後,不知道為什麼很少人有這問題,好像多是windows系統,所以沒這問題。
osx系統的我看提問,最後也是無疾而終

我目前想到的方法:
  • 就是不用imshow 改用 skimage 裡的io.imshow()
%matplotlib

import matplotlib.pyplot as plt
from skimage import io
import cv2
import numpy as np 
#載入影像 
img = cv2.imread('Li.png')    
io.imshow(img)
plt.show()

magic 函數 %matplotlib 後面不加任何東西就是default視窗,這是可以被關閉的
或是要用notebook的特色 就 %matplotlib notebook即可。


不過pyQ我還是無法解決視窗問題=="
這封郵件來自 Evernote。Evernote 是您專屬的工作空間,免費下載 Evernote

2017年3月5日 星期日

Training and Test

Training and Test

本週是要實現如何使用python的machine leraning,上了coursera的課程主要是了解概念,至於實作,我是參考了莫煩的python教學
以下是網址:
受益良多,很感謝

看了下網路其他教學範例,大多是使用波士頓房地產做解說,然後做線性迴歸。不然就是做分類。
而我的狀況是希望能做多項式的回歸,網路上也是有找到多項式回歸的教學,不過要慢慢自己去建參數,是有點複雜,畢竟我不是演算法出眾的人。
於是看到了python有: sklearn (science kit learning )的svm(Support Vecotr Machine) SVR(Suppert Vector Regression)演算法
基本上 SVR 就是在針對回歸作演算法處理。

該import的依樣先import:
%matplotlib notebook
from sklearn import datasets 
import matplotlib.pyplot as plt 
import numpy as np 
from sklearn.cross_validation import train_test_split 
from sklearn.svm import SVR 
from sklearn.cross_validation import cross_val_score 
import pickle
from math import*

                                                 數據庫,內建很多資料可以練習,也有內建很多function,比如datasets.make_regression ....等等
2.from sklearn.cross_validation import train_test_split : 分類test set 與training set
3.from sklearn.svm import SVR : svr演算法
4.from sklearn.cross_validation import cross_val_score : 交叉驗證,之後有新的data再引入驗證,目前還沒用
5.import pickle:存擋 
6.from math import*:如果要用倒三角函數或是exp要引入

better_score =0
X = np.sort(5 * np.random.rand(500, 1), axis=0)
y = np.exp( -X**2 ) + np.random.normal(0, 0.05, X.shape)
y_= y. ravel()
for i in range(20):
  x_train, x_test, y_train, y_test = train_test_split(X, y_, test_size=0.3) 
  svr_poly = SVR(kernel='rbf') 
  x_test =sorted(x_test)
  y_test= sorted(y_test, reverse=True)
  y_poly= svr_poly.fit(x_train,y_train).predict(x_test) 
  score = svr_poly.score(x_test,y_test) 
  print score
  if better_score>score: 
  better_score = better_score 
  else: 
  better_score = score 
  fitting = svr_poly 
  xx=x_test 
  yy=y_test 

print ('Best R^2 is: {}'.format(better_score)) 


# plt.scatter(X,y,lw =1,marker='.',c= 'cornflowerblue')
# plt.scatter(x_test,y_test,lw= 0.1,marker='*',c ='r')
# plt.plot(x_test,y_poly,c='g',lw =2)
# plt.show()
xx = sorted(xx) 
yy = sorted(yy,reverse=True) 
yyy= fitting.fit(x_train,y_train).predict(xx) 
plt.scatter(X,y,lw =1,marker='.',c= 'cornflowerblue')
plt.scatter(xx,yy,lw= 0.1,marker='*',c ='r')
plt.plot( xx,yyy, color='g', lw=2) 
plt.legend() 
plt.show()

0.981262758171
0.985928238754
0.983921017322
0.978366081228
0.981761295843
0.983258298598
0.984401149668
0.975115055289
0.982420619817
0.984895618793
0.984486517169
0.98190445156
0.980037096507
0.975000835056
0.974193198206
0.986632990775
0.983566759576
0.984506261356
0.981129872633
0.979422542099
Best R^2 is: 0.986632990775
xx=x_test , yy=y_test 
為當我找到較好的 svr_poly 演算法函數時,丟進fitting ,當時所對應的 test set。
當一系列跑完,
fitting為最好的演算法,xx,yy為當時最好的test sample,
我就用演算法fitting去驗證xx 跑出來的結果 yyy 看是否接近yy

藍色.是全部data
紅色*是最後最好的test set
綠色線是用fitting演算法以xx數據推測出yyy的數值所畫的線

由於x,y是我自己生成的序列,會在正負之間跳來跳去,所以要再用sort去把他們排序。
結果:

這封郵件來自 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