發表文章

目前顯示的是有「科技」標籤的文章

ML.NET-使用ML.NET進行異常偵測

安裝完ML.NET跟讀好資料庫資料,現在就來跑個異常偵測測試一下。 主要用到IidSpikeEstimator Class這個類別 根據微軟敘述 可偵測到的時間序列異常有兩種:尖峰表示系統中異常行為的暫時高載。變更點表示系統開頭的持續性隨著時間變更。 首先把DB讀到的data轉成ml看得懂的形式,iidSpikeEstimator 類似python的model,給他input跟output(需寫成類別可參考 ML.NET從資料庫讀取資料 ),p-value信心水準95%,pvalueHistoryLength:計算p-value的滑動窗口大小,這兩個參數可調整,找出來的異常值會有差異。 下一步把資料餵到model裡面並把資料轉成列舉,從列舉中取出預測值,最後就是把結果印出來而已,因為我是用asp.net專案,所以簡單用label顯示。 var mlData = mlContext.Data.LoadFromEnumerable(data); DetectSpike(mlContext, mlData);      static IDataView CreateEmptyDataView(MLContext mlContext)     {         // Create empty DataView. We just need the schema to call Fit() for the time series transforms         IEnumerable<geodaily_model> enumerableData = new List<geodaily_model>();         return mlContext.Data.LoadFromEnumerable(enumerableData);     }     public void DetectSpike(MLContext mlContext, IDataView productSales) ...

ML.NET-ML.NET從資料庫讀取資料(ML.NET load data from database)

原先看微軟的文件 MLContext mlContext = new MLContext(); DatabaseLoader loader = mlContext.Data.CreateDatabaseLoader<HouseData>(); 這段code一直無法讀到 DatabaseLoader, 所以就找的別的方法讀取資料庫內的資料。 首先先為你要取的資料建一個類別 daily_model是日期與數值  ,daily_modelPrediction是預測值 public class daily_model {     [LoadColumn(0)]     public string date;     [LoadColumn(1)]     public float  value; } public class daily_modelPrediction {     //vector to hold alert,score,p-value values     [VectorType(3)]     public double[] Prediction { get; set; } } SQL抓取資料function     public DataTable GetData(string sql)     {         //連接字串         String conString = System.Configuration.ConfigurationManager.AppSettings["ConnString"];         //取得MySQLConnection         MySqlConnection conn = new MySqlConnection();      ...

ML.NET-安裝ML.NET(install ML.NET)

圖片
最近微軟出了ML.NET,讓再.net環境中也可以使用機器學習的相關應用。 visual studio installer安 裝「.NET Core 跨平臺開發」工作負載的 Visual Studio 2017 15.6 版或更新 版本。 網頁專案安裝使用Nuget搜尋Microsoft.ML,包含Microsoft.ML.TimeSeries一併安裝。 再使用中我有遇到 類型 'Attribute' 定義在未參考的組件中。您必須加入組件 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' 的參考。 csharp The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' 的問題。 這時候只要再你專案的config檔加入 <add assembly="netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" /> 即可解決。

ASP.NET-Repeater抓去特定控制項調整屬性(Repeater get control)

Repeater有時須抓某個index的值或者調整屬性就可以用到。 找到最後一筆調整enable屬性 RepeaterItem item = rp1.Items[rp1.Items.Count - 1];         DropDownList ddl_type = (DropDownList)item.FindControl("ddl_type");         ddl_type.Enabled = true;         TextBox type = (TextBox)item.FindControl("tbx_amount");         type.Enabled = true; 抓取每row的textbox跟dropdownlist的值 for (int i = 0; i < rp1.Items.Count; i++)         {             string a = ((TextBox)rp1.Items[i].FindControl("tbx_schedule")).Text;             string = ((DropDownList)rp1.Items[i].FindControl("ddl_type")).SelectedValue;         }

ASP.NET-Repeater建立table繫結資料(Repeater bind data)

最近喜歡用Repeater來建table,再套bootstrap的CSS,用起來比gridview方便。 前端 <asp:Repeater ID="rp1" runat="server">                                             <HeaderTemplate>                                                 <table id="datatable-buttons" class="table table-striped table-bordered">                                                     <thead>                                                         <tr>                   ...

Python-開機自動執行python腳本檔.py(Auto run python script .py)

python程式若開機後執行一次就直接透過下面方法,若要開機後固定時間執行一次,可使用while跟sleep搭配使用。 這邊邏輯是把執行.py寫成一個bat檔在放到Windows的啟動資料夾中,開機時便會自動啟用。 bat檔可以參考一下code: cd C:\users\Desktop\      call activate tensorflow-gpu call python test.py 首先先移到你檔案所在資料夾, 機活你的運行環境,因為我的程式有用到tensorflow需要機活,最後在執行.py程式。                                                  建.bat檔只要開個記事本把上面寫進去另存成.bat即可。 要找到開始資料夾可以按"開始"+R,會跳出"執行",輸入shell:startup,再把你的.bat放入此資料夾就完成了。

ASP.NET-IIS架站方法(Internet Information Services build asp.net project)

圖片
先到控制台→程式與功能→開啟或關閉Windows功能→Internet Information Services 將IIS主控台與應用程式開發宮內的ASP.NET打開。 之後打開IIS管理員裡面有一個預設的站台,跳出此畫面表示建立成功。 接下來把你的ASP.NET專案加進去。可以選擇新增應用程式或新增站台 我這邊使用新增應用程式,即在預設的站台內,選擇後取個別名,實體路徑選擇有web config的那層即可。 最後記得要將那層資料夾→內容→安全性那 把使用者名稱加入 Everyone 不然可能會遇到權限不足的問題,另外Web config內記得加上 <customErrors mode="Off" />

C#-Web socket client範例

web socket是一種網路通訊協定。 參考wiki有以下優點。 較少的控制開銷。在連接建立後,伺服器和用戶端之間交換資料時,用於協定控制的封包頭部相對較小。在不包含擴充的情況下,對於伺服器到用戶端的內容,此頭部大小只有2至10位元組(和封包長度有關);對於用戶端到伺服器的內容,此頭部還需要加上額外的4位元組的遮罩。相對於HTTP請求每次都要攜帶完整的頭部,此項開銷顯著減少了。 更強的即時性。由於協定是全雙工的,所以伺服器可以隨時主動給用戶端下發資料。相對於HTTP請求需要等待用戶端發起請求伺服器端才能回應,延遲明顯更少;即使是和Comet等類似的長輪詢比較,其也能在短時間內更多次地傳遞資料。 保持連接狀態。與HTTP不同的是,Websocket需要先建立連接,這就使得其成為一種有狀態的協定,之後通訊時可以省略部分狀態資訊。而HTTP請求可能需要在每個請求都攜帶狀態資訊(如身分認證等)。 更好的二進位支援。Websocket定義了二進位影格,相對HTTP,可以更輕鬆地處理二進位內容。 可以支援擴充。Websocket定義了擴充,用戶可以擴充協定、實現部分自訂的子協定。如部分瀏覽器支援 壓縮 等。 更好的壓縮效果。相對於HTTP壓縮,Websocket在適當的擴充支援下,可以沿用之前內容的 上下文 ,在傳遞類似的資料時,可以顯著地提高壓縮率。 簡單講更輕量,也同步,下面就用C#的方法寫一個client端的web socket。 先去Nuget下載WebSocketSharp套件,透過下面語法便可與server端連線,傳送的值我把它包成json。 using WebSocketSharp;             //透過websocketclient傳送資料             var ws = new WebSocket("ws://140.110.148.87:8080/websocket/test");             ws.Connect();      ...

Machine Learning-python用LSTM模型進行時間序列預測1(LSTM to do time series forecasting using python keras)

這篇實作LSTM多對一的模型,顧名思義就是用過去多筆資料去預測未來一筆。 整個處理流程可分為 1.讀取資料 2.正規化資料(較會收斂) 3.切割訓練集 4.打亂資料順序(訓練結果可更好) 5.建模型 6.最佳化並評估訓練結果 以下直接用程式範例說明 import pandas as pd import numpy as np from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten, LSTM, TimeDistributed, RepeatVector import mysql.connector from keras import optimizers from keras.callbacks import EarlyStopping #讀資料 xls_file = pd.ExcelFile('A.xlsx') df = xls_file.parse('sheet1') data=df #正規化 def normalize(train):   train_norm = train.apply(lambda x: (x - np.mean(x)) / (np.max(x) - np.min(x)))   return train_norm data=normalize(data) #切訓練集,24筆去預測未來1筆,Y_train就是你要預測的參數。 def buildTrain(train, pastDay, futureDay):   X_train, Y_train = [], []   for i in range(train.shape[0]-futureDay-pastDay):     X_train.append(np.array(train.iloc[i:i+pastDay]))     Y_train.append(np.array(train.iloc[i+pastDay:i+pastDay+futureDay]["goal"]))   retur...

Python-相關係數矩陣實作(python-correlation matrix )

圖片
相關係數被用來 用於度量兩個變數X和Y之間的相關 程度(線性相依),其值介於-1與1之間。在自然科學領域中,該係數廣泛用於度量兩個變數之間的線性相依程度。 再資料科學中,前處理步驟可先用來觀察參數間的關係,可幫助找到對目標參數影響較大的變數。 下面就用python實作係數矩陣視覺化。 import pandas as pd import matplotlib.pyplot as mp, seaborn #讀資料 xls_file = pd.ExcelFile('A.xlsx') df = xls_file.parse('sheet1') data=df print(df) #視覺化 df_corr = df.corr() seaborn.heatmap(df_corr, center=0, annot=True) mp.show() dataframe長這樣 相關係數矩陣

ASP.NET-Timer應用(using timer)

Timer配合ajax可以在定期內更新部分頁面,但若在timer method中必須下條件,timer會把順序做完才更新無法達成效果,必須在條件內return,以下為程式範例。 前端: <asp:ScriptManager ID="ScriptManager1" runat="server"> <asp:UpdatePanel ID="UpdatePanel1" runat="server">                         <ContentTemplate>                             <asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick">                             </asp:Timer>                                 <asp:Label ID="lbl_test" runat="server" ></asp:Label>                         </ContentTemplate>                     </asp:UpdatePan...

ASP.NET-FileUpload上傳後自動觸發button click(FileUpload upload auto trigger button click)

在ASP.NET中FileUpload很常都需要配一個button,上傳檔案一個動作,上傳後還需點擊按鈕才能觸發後續的儲存等等功能。 這邊要實作上傳檔案後自動觸發後續功能,不用再多一步點擊按鈕。 前端: 當fileUpload的值不為空自動找到button做click動作     <script type="text/javascript">     function UploadFile(fileUpload) {         if (fileUpload.value != '') {             document.getElementById("<%=btn_upload.ClientID %>").click();         }     }     </script> 新增FileUpload跟button並把button隱藏 <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID="btn_upload" runat="server" OnClick="btn_upload_Click" Style="display: none" /> 後端: using System.IO; //新增屬性當onchange時觸發javascript function protected void Page_Load(object sender, EventArgs e) {       FileUpload1.Attributes["onchange"] = "UploadFile(this)";        } //完成自動觸發button click protected void btn_upload_Click(object sender, EventArgs e)...

ASP.NET-利用Oledb讀取DBF資料庫(Oledb load .dbf file)

使用Oledb讀取DBF資料庫可參考下列兩個methods,實際呼叫參考最下面的code,把讀出檔案匯入datatable              using System.Data.OleDb;         // 利用Oledb讀取DBF資料庫         public static OleDbConnection OleDbDbfOpenConn(string DatabaseDirectory)         {             string cnstr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DatabaseDirectory + "; Extended Properties=dBASE IV; User ID=Admin; Password=;");             OleDbConnection icn = new OleDbConnection();             icn.ConnectionString = cnstr;             if (icn.State == ConnectionState.Open) icn.Close();             icn.Open();             return icn;         }         public static DataTable GetOleDbDbfDataTable(...

Python讀取mysql出現Authentication plugin 'caching_sha2_password' is not supported解決方法

用mysql.connector在讀取MySQL時如下程式碼 cnx = mysql.connector.connect(user='ccc', password='bbb',                               host='172.00.000.000',                               database='aaa') cursor = cnx.cursor() query = ("SELECT xxx FROM aaa;") cursor = cnx.cursor(buffered=True) cursor.execute(query) 在mySQL8.0預設caching_sha2_password加密,但套件不支援,所以必須加上一行把預設加密改為mysql_native_password cnx = mysql.connector.connect(user='ccc', password='bbb',                               host='172.00.000.000',                               database='aaa',                               auth_plugin='mysql_native_password') 即可...

Machine Learning-多層感知器程式範例 使用python (Multilayer perceptron case using python keras)

手上剛好有一份冷媒的溫壓對照表,如下連結 R245fa 但當你的數值不能剛好match還需要一個一個換算,因此直接用MLP訓練個擬合模型來換算。 目標就是希望壓力經過模型後自動換算成溫度,就直接看code。 import pandas as pd import numpy as np from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten, LSTM, TimeDistributed, RepeatVector #讀取資料 xls_file = pd.ExcelFile('R245fa溫壓表.xlsx') df = xls_file.parse('工作表1') print(df.columns) print(df) #分別把壓力當input與溫度當output train=df X = train.iloc[:,1:]  Y = train.iloc[:,0] X=X.values Y=Y.values #故意打亂1~120的順序,可讓訓練結果更好 def shuffle(X,Y):   np.random.seed(10)   randomList = np.arange(X.shape[0])   np.random.shuffle(randomList)   return X[randomList], Y[randomList] #區分訓練集與測試集 def splitSet(X,Y,rate):     count=int(round(len(X)*rate))     X_train, Y_train = X[:count], Y[:count]        X_test, Y_test = X[count:], Y[count:]     return X_train, Y_train, X_test, Y_test  #再切一份驗證集可讓訓練結果更好 def splitData(X...

Python-讀取excel(python read excel using pandas)

簡單記錄一下讀取excel import pandas as pd xls_file = pd.ExcelFile('AAA.xlsx') df = xls_file.parse('工作表1') print(df) print(df.columns)

ASP.NET-C#與MySQL連接遇到問題Fatal error encountered during command execution

最近架了個MySQL Server,用mysql workbench都連得到,但用C#程式要連時,跳出以下錯誤 Fatal error encountered during command execution 後來查了一下,在connectstring中加了"Allow User Variables=True;"就解決了 連線字串可參考(config) <add key="ConnString" value="SERVER = xxx.xx.xxx.xx; DATABASE = xxx; User ID = xxx; PASSWORD = xxxxxxxx; SslMode=none; Connect Timeout=3600;Allow User Variables=True;" /> 程式後端可這樣讀string,並抓資料         public static DataTable GetData(string sql)         {             //連接字串             String conString = System.Configuration.ConfigurationManager.AppSettings["ConnString"];             //取得MySQLConnection             MySqlConnection conn = new MySqlConnection();             conn.ConnectionString = conString;             DataTable dt = new DataTable();       ...

ASP.NET-後端值傳給前端javascript(ASP.NET code-behind value pass to javascript )

會遇到這個需求是需要後端撈DB資料傳給前端javascript畫圖使用,提供一個方法可達到此功能。 後端 using System.Web.Script.Serialization; protected string value = "test"; public static class JavaScript {       public static string Serialize(object o)       {           JavaScriptSerializer js = new JavaScriptSerializer();           return js.Serialize(o);       } } 前端 <script type="text/javascript">     var value = <%=JavaScript.Serialize(this.value) %>; </script>

Machine Learning-用自動編碼器來實作異常值偵測-使用python keras 執行模型(outlier detection with autoencoder using python keras run model)

當訓練好模型後,想要找到與訓練異常的資料,只要將資料餵進模型中,再將MSE依降序排列,並設定門檻值。 門檻值可以取top N或 訓練集MSE最大值等等方法,端看應用情境。 下面python keras程式碼一樣簡單示意。 import numpy as np from keras.models import Sequential from keras.layers import Dense import matplotlib.pyplot as plt import mysql.connector import pandas as pd from keras.models import Model from keras.layers import Dense, Input from sklearn import preprocessing from sklearn.metrics import mean_squared_error from keras.models import load_model #抓取資料 cnx = mysql.connector.connect(user='xxx', password='xxx',                               host='xxx',                               database='xxx') cursor = cnx.cursor() query = ("SELECT id, q, p, t,angle FROM xxx  ") cursor = cnx.cursor(buffered=True) cursor.execute(query) num_fields = len(cursor.description) field_names = [i[0] for i in cursor.d...

Machine Learning-用自動編碼器來實作異常值偵測-使用python keras(outlier detection with autoencoder using python keras)

圖片
一般認為自動編碼器用來降維,減少資料複雜度。 其另一用途可被應用在半監督式學習的異常偵測上。 基本概念為 拿一群狗的圖片進去訓練模型 原圖>壓縮>復原 模型目標希望復原圖片跟原圖失真越小越好, 當你拿一群狗資料進行訓練,就可以得到一個對狗圖片有很強的壓縮解壓縮的模型。 今天當有異常資料近來,例如貓的照片進這模型再復原,照常理來說其失真程度較高,因此可以用 mean-square error 來當作異常分數。 以下附上簡單用python keras實作的訓練模型程式碼,範例指用了424的自動邊碼器模型,大家可自行增加units與layers來得到更佳的偵測模型。 import numpy as np from keras.models import Sequential from keras.layers import Dense import matplotlib.pyplot as plt import mysql.connector import pandas as pd from keras.models import Model from keras.layers import Dense, Input from sklearn import preprocessing from sklearn.metrics import mean_squared_error from sklearn.model_selection import StratifiedKFold from sklearn.cross_validation import train_test_split #讀取資料 看你的資料再資料庫還是csv cnx = mysql.connector.connect(user='xxx', password='xxx',                               host='xxx',                   ...