// Hàm tạo lại các file class.txt từ 9 file train public static void taoTrainClasstxt(int chiso, String splitPath, String[] className) { List <DocumentDaPhanLop> listalldocument = new List <DocumentDaPhanLop>(); int k = XuLyFile.k(); for (int i = 1; i <= k; i++) { if (i != chiso) { List <DocumentDaPhanLop> listtemp = DocumentDaPhanLop.layCacDocumentDaPhanLop(splitPath + "file" + i + ".txt"); for (int j = 0; j < listtemp.Count; j++) { listalldocument.Add(listtemp[j]); } } } for (int i = 0; i < className.Length; i++) { className[i] = className[i].Split('\\').Last().Split('.').First(); using (StreamWriter sw = new StreamWriter(splitPath + className[i] + ".txt")) { for (int j = 0; j < listalldocument.Count; j++) { if (listalldocument[j].className == className[i]) { sw.WriteLine(listalldocument[j].content); } } } Console.WriteLine("Tao file class " + className[i] + ".txt thanh cong"); } }
public static void bow_tfdf(List <Document> documentList, String output, String featureList) { Console.WriteLine("======Tao BOW===="); try { List <Document> TF_IDF_List = new List <Document>(); // đọc lấy số làm tròn . int round_num = XuLyFile.docRound(); //In danh sách features ra file (danh sách này chứa các feature duy nhất dù feature //đó xuất hiện trong nhiều document khách nhau //List<Feature> fList = inFeatureList(featureList, documentList); List <Feature> fList = inFeatureList(featureList, documentList); // doclength là số lượng văn bản trong file int doc_length = documentList.Count; using (StreamWriter fileout = new StreamWriter(output)) { documentList.ForEach(delegate(Document x) { TF_IDF_List.Add(new Document()); // tìm trọng số lớn nhất trong 1 document double max = Document.timSoLanXuatHienNhieuNhat(x); fList.ForEach(delegate(Feature j) { //lấy số lượng văn bản có string j int doc_count = Document.DemDocChuaI(j.feature, documentList); double tf = 0; Double IDF = 0; Double TF_IDF = 0; // Lấy trọng số của string j trong document double weigthj = Document.timWeightCuaFeatureTrongDocument(x, j.feature); tf = weigthj / max; IDF = Math.Log10((float)doc_length / (float)doc_count); TF_IDF = Math.Round(tf * IDF, round_num); fileout.Write(TF_IDF); fileout.Write('\t'); }); fileout.WriteLine(); }); fileout.Close(); Console.WriteLine("Thao tác thành công!!"); } } catch (Exception e) { Console.WriteLine("Có lỗi trong lúc đọc file: " + e.Message); } }
//Hàm tính F-micro public static double F_Micro(List <ClassInfo> List, int tongsovb) { double result = 0; double temp = 0; for (int i = 0; i < List.Count; i++) { temp += List[i].NumberRightofClass; } result = Math.Round((double)temp / tongsovb, XuLyFile.docRound()); return(result); }
static void Main(string[] args) { String preprocessedFilePath = "D:\\PhanLop\\bin\\Debug\\preprocessedClasses\\"; String[] filePaths = Directory.GetFiles("D:\\PhanLop\\bin\\Debug\\classes", "*.txt"); List <Class> classList = new List <Class>(); for (int i = 0; i < filePaths.Length; i++) { Class c = new Class(); c.className = filePaths[i].Split('\\').Last().Split('.').First(); TienXuLy.tienXuLy(filePaths[i], preprocessedFilePath + c.className + ".txt"); c.layCacDocuments(preprocessedFilePath + c.className + ".txt", c.className); classList.Add(c); } // Gộp tất cả các document của các class lại thành 1 documentList List <Document> documentListOfAllClasses = Document.gopDocuments(classList); //Tính bow tfidf BOW.bow_tfdf(documentListOfAllClasses, "output.txt", "featureList.txt"); // Tiền xử lý các document cần phân lớp TienXuLy.tienXuLy("test.txt", "preprocessedTest.txt"); // Các document cần được phân lớp List <Document> testList = Document.layCacDocuments("preprocessedTest.txt"); testList.ForEach(delegate(Document d) { d.className = Document.phanLop(d, XuLyFile.knn(), documentListOfAllClasses.Count, documentListOfAllClasses, classList); Console.WriteLine(d.className); Console.WriteLine(d.index); }); List <String> testDocuments = Document.layChuoiCacDocuments("test.txt"); using (StreamWriter sw = new StreamWriter("result.txt")) { for (int i = 0; i < testDocuments.Count; i++) { testList.ForEach(delegate(Document d) { if (d.index == i) { sw.WriteLine(testDocuments.ElementAt(i) + "\tclass:" + d.className); } }); } } }
//Hàm tính F-macro public static double F_Macro(List <ClassInfo> List) { double result = 0; double p_macro = 0; double r_macro = 0; //Tính toán p_macro và r_macro for (int i = 0; i < List.Count; i++) { p_macro += Math.Round((double)List[i].Precision / List.Count, XuLyFile.docRound()); r_macro += Math.Round((double)List[i].Recall / List.Count, XuLyFile.docRound()); } result = Math.Round((double)(2 * p_macro * r_macro) / (p_macro + r_macro), XuLyFile.docRound()); return(result); }
// Hàm chia file public static void chiaFile(String[] filePaths, String splitPath) { List <DocumentDaPhanLop> listofalldocument = new List <DocumentDaPhanLop>(); string line = null; // Tạo list các document của các class (Document chưa tienXuLy) for (int i = 0; i < filePaths.Length; i++) { using (StreamReader sr = new StreamReader(filePaths[i])) { while ((line = sr.ReadLine()) != null) { listofalldocument.Add(new DocumentDaPhanLop(line, filePaths[i].Split('\\').Last().Split('.').First())); } } } // SHuffle các phần tữ của list listofalldocument.Shuffle(); using (StreamWriter sw = new StreamWriter(splitPath + "alldocument.txt")) { for (int i = 0; i < listofalldocument.Count; i++) { if (i != listofalldocument.Count - 1) { sw.WriteLine(listofalldocument[i].content + " " + listofalldocument[i].className); } else { sw.Write(listofalldocument[i].content + " " + listofalldocument[i].className); } } //Console.WriteLine("Tao file alldocument.txt thanh cong"); } // Chia file alldocument.txt chứa tất cả các document thành 10 file text nhỏ SplitText(splitPath + "alldocument.txt", splitPath, XuLyFile.k()); }
public static String phanLopCosine(Document searchedDocument, int numberOfReturnDocuments, int numberOfDocuments, List <Document> documentListOfAllClasses, List <Class> classList) { Console.WriteLine("=========Phan Lop Cosine==========="); Document searchedDocument_tfidf = new Document(); List <FeatureIDF> featureList = new List <FeatureIDF>(); using (StreamReader sr = new StreamReader("featureList.txt")) { String line = null; while ((line = sr.ReadLine()) != null) { String[] feature = line.Split(' '); featureList.Add(new FeatureIDF(feature[0], double.Parse(feature[1]))); } } featureList.ForEach(delegate(FeatureIDF f) { double tf = (double)timWeightCuaFeatureTrongDocument(searchedDocument, f.feature) / timSoLanXuatHienNhieuNhat(searchedDocument); searchedDocument_tfidf.featureList.Add(new Feature(f.feature, Math.Round(tf * f.idf, XuLyFile.docRound()))); }); List <double[]> bow_tfidf = BOW.docBOW_tfidf(); SimilarityMeasure[] similarityMeasures = new SimilarityMeasure[numberOfDocuments]; int i, j; for (i = 0; i < numberOfDocuments; i++) { double value1 = 0; double value2 = 0; double value3 = 0; double value = 0; for (j = 0; j < searchedDocument_tfidf.featureList.Count; j++) { value1 += bow_tfidf.ElementAt(i)[j] * searchedDocument_tfidf.featureList.ElementAt(j).weight; value2 += Math.Pow(bow_tfidf.ElementAt(i)[j], 2); value3 += Math.Pow(searchedDocument_tfidf.featureList.ElementAt(j).weight, 2); } value = (double)value1 / (Math.Sqrt(value2) * Math.Sqrt(value3)); similarityMeasures[i] = new SimilarityMeasure(Math.Round(Math.Sqrt(value), XuLyFile.docRound()), i); } //Sắp xếp độ tương tự giảm dần SimilarityMeasure[] sortedSimilarityMeasures = similarityMeasures.OrderByDescending(sm => sm.value).ToArray(); Dictionary <String, int> classesOfDocument = new Dictionary <string, int>(); for (int k = 0; k < numberOfReturnDocuments; k++) { for (int f = 0; f < documentListOfAllClasses.Count; f++) { if (f == sortedSimilarityMeasures[k].index) { Console.WriteLine(documentListOfAllClasses.ElementAt(f).className + " " + documentListOfAllClasses.ElementAt(f).index); if (classesOfDocument.ContainsKey(documentListOfAllClasses.ElementAt(f).className)) { classesOfDocument[documentListOfAllClasses.ElementAt(f).className]++; } else { classesOfDocument.Add(documentListOfAllClasses.ElementAt(f).className, 1); } } } } int max = classesOfDocument.ElementAt(0).Value; String maxClass = classesOfDocument.ElementAt(0).Key; for (int t = 0; t < classesOfDocument.Count; t++) { if (classesOfDocument.ElementAt(t).Value > max) { max = classesOfDocument.ElementAt(t).Value; maxClass = classesOfDocument.ElementAt(t).Key; } } return(maxClass); }
static void Main(string[] args) { String preprocessedFilePath = "D:\\PhanLop\\PhanLop\\bin\\Debug\\preprocessedClasses\\"; String[] filePaths = Directory.GetFiles("D:\\PhanLop\\PhanLop\\bin\\Debug\\classes", "*.txt"); String splitPath = "D:\\PhanLop\\PhanLop\\bin\\Debug\\splitFiles\\"; // Đường dẫn chứa các file train và text // Chọn chế độ thực thi Console.WriteLine("====Nhap so 1 đe chon che do 1===="); Console.WriteLine("====Nhap so 2 đe chon che do 2===="); Console.WriteLine("Nhap vao lua chon: "); string chedo = Console.ReadLine(); int chedonum = Int32.Parse(chedo); if (chedonum == 1) { //Nhập lựa chọn Console.WriteLine("====Nhap so 0 đe phan lop theo Euclidean Similarity===="); Console.WriteLine("====Nhap so 1 đe phan lop theo Cosine Similarity===="); Console.WriteLine("Nhap vao lua chon: "); string choice = Console.ReadLine(); int choicenum = Int32.Parse(choice); List <Class> classList = new List <Class>(); for (int i = 0; i < filePaths.Length; i++) { Class c = new Class(); c.className = filePaths[i].Split('\\').Last().Split('.').First(); TienXuLy.tienXuLy(filePaths[i], preprocessedFilePath + c.className + ".txt"); c.layCacDocuments(preprocessedFilePath + c.className + ".txt", c.className); classList.Add(c); } // Gộp tất cả các document của các class lại thành 1 documentList List <Document> documentListOfAllClasses = Document.gopDocuments(classList); //Tính bow tfidf BOW.bow_tfdf(documentListOfAllClasses, "output.txt", "featureList.txt"); // Tạo một file text đã xóa các class trước khi chạy knn DocumentDaPhanLop.removeClassDocument("true.txt", "test.txt"); // Tiền xử lý các document cần phan lớp TienXuLy.tienXuLy("test.txt", "preprocessedTest.txt"); // Các document cần được phân lớp List <Document> testList = Document.layCacDocuments("preprocessedTest.txt"); if (choicenum == 0) { testList.ForEach(delegate(Document d) { d.className = Document.phanLop(d, XuLyFile.knn(), documentListOfAllClasses.Count, documentListOfAllClasses, classList); Console.WriteLine(d.className); Console.WriteLine(d.index); }); } if (choicenum == 1) { testList.ForEach(delegate(Document d) { d.className = Document.phanLopCosine(d, XuLyFile.knn(), documentListOfAllClasses.Count, documentListOfAllClasses, classList); Console.WriteLine(d.className); Console.WriteLine(d.index); }); } List <String> testDocuments = Document.layChuoiCacDocuments("test.txt"); using (StreamWriter sw = new StreamWriter("temp.txt")) { for (int i = 0; i < testDocuments.Count; i++) { testList.ForEach(delegate(Document d) { if (d.index == i) { sw.WriteLine(testDocuments.ElementAt(i) + " " + d.className); } }); } } //=========================================Phần tính thông tin của các class========================================= List <ClassInfo> listClass = ClassInfo.ThongTinClass("true.txt", "temp.txt", filePaths); using (StreamWriter sw = new StreamWriter("result.txt")) { // Ghi lại sersult và class vào file for (int i = 0; i < testDocuments.Count; i++) { testList.ForEach(delegate(Document d) { if (d.index == i) { sw.WriteLine(testDocuments.ElementAt(i) + " " + d.className); } }); } // Ghi thông tin các độ đo for (int k = 0; k < listClass.Count; k++) { //Ghi ra file infoclass sw.WriteLine("P(" + listClass[k].ClassName + ") = " + listClass[k].Precision); sw.WriteLine("R(" + listClass[k].ClassName + ") = " + listClass[k].Recall); sw.WriteLine("F-score(" + listClass[k].ClassName + ") = " + listClass[k].Fscore); } double f_macro = ClassInfo.F_Macro(listClass); double f_micro = ClassInfo.F_Micro(listClass, DocumentDaPhanLop.demSoDocument("true.txt")); //Ghi ra file infoclass sw.WriteLine("F-macro = " + f_macro); sw.WriteLine("F-micro = " + f_micro); } File.Delete("temp.txt"); Console.WriteLine("Hoan tat!!!"); } if (chedonum == 2) { //Nhập lựa chọn Console.WriteLine("====Nhap so 0 đe phan lop theo Euclidean Similarity===="); Console.WriteLine("====Nhap so 1 đe phan lop theo Cosine Similarity===="); Console.WriteLine("Nhap vao lua chon: "); string choice = Console.ReadLine(); int choicenum = Int32.Parse(choice); // Chia file DocumentDaPhanLop.chiaFile(filePaths, splitPath); //=========================================Phần xử lý các document========================================= // File resultfinal.txt sẽ lưu lại các lần tính otan1 và trung bình F-macro, F-micro using (StreamWriter final = new StreamWriter(splitPath + "resultfinal.txt")) { double temp_F_macro = 0; double temp_F_micro = 0; //Dùng phương pháp cross-validation lấy 1 file làm Test, 9 file làm Train for (int t = 1; t <= XuLyFile.k(); t++) { // Truyền chỉ số t = bao nhiêu thì các file có số != t sẽ làm train DocumentDaPhanLop.taoTrainClasstxt(t, splitPath, filePaths); List <Class> classList = new List <Class>(); for (int i = 0; i < filePaths.Length; i++) { Class c = new Class(); c.className = filePaths[i].Split('\\').Last().Split('.').First(); TienXuLy.tienXuLy(splitPath + c.className + ".txt", preprocessedFilePath + c.className + ".txt"); c.layCacDocuments(preprocessedFilePath + c.className + ".txt", c.className); classList.Add(c); } // Gộp tất cả các document của các class lại thành 1 documentList List <Document> documentListOfAllClasses = Document.gopDocuments(classList); //Tính bow tfidf BOW.bow_tfdf(documentListOfAllClasses, "output.txt", "featureList.txt"); DocumentDaPhanLop.removeClassDocument(splitPath + "file" + t + ".txt", "test.txt"); // Tiền xử lý các document cần phân lớp TienXuLy.tienXuLy("test.txt", "preprocessedTest.txt"); // Các document cần được phân lớp List <Document> testList = Document.layCacDocuments("preprocessedTest.txt"); if (choicenum == 0) { testList.ForEach(delegate(Document d) { d.className = Document.phanLop(d, XuLyFile.knn(), documentListOfAllClasses.Count, documentListOfAllClasses, classList); Console.WriteLine(d.className); Console.WriteLine(d.index); Console.WriteLine(); }); } if (choicenum == 1) { testList.ForEach(delegate(Document d) { d.className = Document.phanLopCosine(d, XuLyFile.knn(), documentListOfAllClasses.Count, documentListOfAllClasses, classList); Console.WriteLine(d.className); Console.WriteLine(d.index); Console.WriteLine(); }); } List <String> testDocuments = Document.layChuoiCacDocuments("test.txt"); using (StreamWriter sw = new StreamWriter(splitPath + "result" + t + ".txt")) { for (int i = 0; i < testDocuments.Count; i++) { for (int k = 0; k < testList.Count; k++) { if (testList[k].index == i) { if (i != testDocuments.Count - 1) { sw.WriteLine(testDocuments.ElementAt(i) + " " + testList[k].className); } else { sw.Write(testDocuments.ElementAt(i) + " " + testList[k].className); } } } } } //=========================================Phần tính thông tin của các class========================================= List <ClassInfo> listClass = ClassInfo.ThongTinClass(splitPath + "file" + t + ".txt", splitPath + "result" + t + ".txt", filePaths); /*final.WriteLine("====================File" + t + "===================="); * for (int k = 0; k < listClass.Count; k++) * { * //Ghi ra file * final.WriteLine("==========Class " + k + "=========="); * final.WriteLine("Ten class: " + listClass[k].ClassName); * final.WriteLine("So van ban duoc phan dung vao class " + listClass[k].ClassName + ": " + listClass[k].NumberRightofClass); * final.WriteLine("So van ban bi phan sai vao class " + listClass[k].ClassName + ": " + listClass[k].NumberWrongofClass); * final.WriteLine("So van ban class " + listClass[k].ClassName + " bi phan sai vao class khac: " + listClass[k].NumberWrongoutClass); * final.WriteLine("Do chinh xac cua class " + listClass[k].ClassName + ": " + listClass[k].Precision); * final.WriteLine("Do bao phu cua class " + listClass[k].ClassName + ": " + listClass[k].Recall); * final.WriteLine("Do do tong hop cua class " + listClass[k].ClassName + ": " + listClass[k].Fscore); * final.WriteLine(); * }*/ double f_macro = ClassInfo.F_Macro(listClass); double f_micro = ClassInfo.F_Micro(listClass, DocumentDaPhanLop.demSoDocument(splitPath + "file" + t + ".txt")); temp_F_macro += f_macro; temp_F_micro += f_micro; final.WriteLine("F-macro[" + t + "] = " + f_macro); final.WriteLine("F-micro[" + t + "] = " + f_micro); final.WriteLine(); } double avg_F_macro = Math.Round(temp_F_macro / XuLyFile.k(), XuLyFile.docRound()); double avg_F_micro = Math.Round(temp_F_micro / XuLyFile.k(), XuLyFile.docRound()); final.WriteLine("Trung binh F-macro = " + avg_F_macro); final.WriteLine("Trung binh F-micro = " + avg_F_macro); } Console.WriteLine("Hoan tat!!!"); } }
public static List <Feature> inFeatureList(String featureList, List <Document> documentList) { Console.WriteLine("======In Feature List======"); try { int round_num = XuLyFile.docRound(); int doc_length = documentList.Count; using (StreamWriter sw = new StreamWriter(featureList)) { //Đây là danh sách các feature trong tất cả các document (một feature nằm trong //nhiều documents thì cũng chỉ có một phần tử trong danh sách features này List <Feature> features = new List <Feature>(); //Với mỗi document documentList.ForEach(delegate(Document d) { //Với mỗi feature trong document đó d.featureList.ForEach(delegate(Feature f) { int exist = 0; //Tìm xem trong danh sách các feature đã có feature nay chưa foreach (Feature feature in features) { //Nếu có rồi thì ghi nhận đã exist (=1) if (feature.feature == f.feature) { exist = 1; feature.weight++; break; } } //Nếu chưa tồn tại feature này trong danh sách features thì thêm vào if (exist == 0) { features.Add(new Feature(f.feature, 1)); Double IDF = 0; Double round = 0; int doc_count = Document.DemDocChuaI(f.feature, documentList); IDF = Math.Log10((float)doc_length / (float)doc_count); round = Math.Round(IDF, round_num); sw.WriteLine(f.feature + " " + round); //Console.WriteLine(f.feature + " " + round); } }); }); //Với mỗi feature in ra file //foreach (String feature in features) //{ // sw.WriteLine(feature); // Console.WriteLine(feature); //} return(features); } } catch (Exception e) { Console.WriteLine("Có lỗi trong lúc viết file: " + e.Message); return(null); } }
//Hàm tính và lưu các thông số về các class public static List <ClassInfo> ThongTinClass(String filetrue, String fileknn, String[] allclass) { List <DocumentDaPhanLop> listTrue = DocumentDaPhanLop.layCacDocumentDaPhanLop(filetrue); List <DocumentDaPhanLop> listPhanLop = DocumentDaPhanLop.layCacDocumentDaPhanLop(fileknn); List <ClassInfo> listClass = new List <ClassInfo>(); //Lay cac class trong file txt dung for (int i = 0; i < allclass.Length; i++) { String temp = allclass[i].Split('\\').Last().Split('.').First(); listClass.Add(new ClassInfo(temp, 0, 0, 0, 0, 0, 0)); } //Tinh toan cho tung class for (int k = 0; k < listClass.Count; k++) { //Xet class cua tung dong trong 2 van ban for (int i = 0; i < listTrue.Count; i++) { if (listTrue[i].className == listPhanLop[i].className && listTrue[i].className == listClass[k].ClassName) { listClass[k].NumberRightofClass++; } if (listTrue[i].className != listPhanLop[i].className && listPhanLop[i].className == listClass[k].ClassName) { listClass[k].NumberWrongofClass++; } if (listTrue[i].className != listPhanLop[i].className && listTrue[i].className == listClass[k].ClassName) { listClass[k].NumberWrongoutClass++; } } //Tính precisoin, recall, f-score if (listClass[k].NumberRightofClass != 0) { listClass[k].Precision = Math.Round((double)listClass[k].NumberRightofClass / (listClass[k].NumberRightofClass + listClass[k].NumberWrongofClass), XuLyFile.docRound()); listClass[k].Recall = Math.Round((double)listClass[k].NumberRightofClass / (listClass[k].NumberRightofClass + listClass[k].NumberWrongoutClass), XuLyFile.docRound()); listClass[k].Fscore = Math.Round((double)(2 * listClass[k].Precision * listClass[k].Recall) / (listClass[k].Precision + listClass[k].Recall), XuLyFile.docRound()); } else { listClass[k].Precision = 0; listClass[k].Recall = 0; listClass[k].Fscore = 0; } } return(listClass); }