Advertisement
Guest User

Untitled

a guest
May 21st, 2018
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.30 KB | None | 0 0
  1. from sklearn import tree
  2. from sklearn.preprocessing import LabelEncoder
  3. # import pandas as pd
  4. # import numpy as np
  5. from sklearn import cluster
  6. from sklearn import datasets
  7. from mpl_toolkits.mplot3d import Axes3D
  8. import numpy as np
  9. import matplotlib.pyplot as plt
  10. import cv2
  11.  
  12. from sklearn import datasets, svm, metrics
  13. digits = datasets.load_digits()
  14. from sklearn.neural_network import MLPClassifier
  15. from sklearn.neighbors import KNeighborsClassifier
  16. from sklearn.svm import SVC
  17. from sklearn.gaussian_process import GaussianProcessClassifier
  18. from sklearn.gaussian_process.kernels import RBF
  19. from sklearn.tree import DecisionTreeClassifier
  20. from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
  21. from sklearn.naive_bayes import GaussianNB
  22. from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
  23.  
  24. def zadanie1():
  25.     # przebieg = [100000, 67000, 45879, 300002]
  26.     # marka = ['audi', 'mercedes', 'porshe', 'opel']
  27.     # uszkodzony = [1, 0, 0, 0]
  28.  
  29.     X = [[100000, 1, 1],
  30.          [6700, 2, 1],
  31.          [45879, 3, 0],
  32.          [300002, 4, 0]]
  33.          # [100000, 67000, 45879, 300002],
  34.          # ['audi', 'mercedes', 'porshe', 'opel'],
  35.          # [1, 0, 0, 0]]
  36.     Y = [1, 1, 0, 0]
  37.  
  38.     # print(X[:,1])
  39.     # le = LabelEncoder()
  40.     # X[:,1] = le.fit_transform(X[:,1])
  41.     # print(X[:,1])
  42.     # X = pd.DataFrames(X)
  43.  
  44.  
  45.     drzewko = tree.DecisionTreeClassifier()
  46.     drzewko = drzewko.fit(X, Y)
  47.     pred = drzewko.predict([[200000, 1, 0]])
  48.     print(pred)
  49.  
  50. def zadanie2():
  51.     pora = {'rano': 0, 'poludnie': 1, 'wieczor': 2, 'noc': 3}
  52.  
  53.     X = [[15, pora['rano'], 0],
  54.          [7, pora['noc'], 1],
  55.          [23, pora['poludnie'], 0],
  56.          [14, pora['noc'], 1],
  57.          [19, pora['wieczor'], 1]]
  58.     Y = [1, 0, 1, 0, 1]
  59.  
  60.     drzewko = tree.DecisionTreeClassifier()
  61.     drzewko = drzewko.fit(X, Y)
  62.     pred = drzewko.predict([[17, pora['wieczor'], 1]])
  63.     print(pred)
  64.  
  65.  
  66. def zadanie3():
  67.     iris = datasets.load_iris()
  68.     print(iris.data)
  69.     print(iris.target)
  70.  
  71.     X = iris.data
  72.     k_means = cluster.KMeans(n_clusters=3)
  73.     k_means.fit(X)
  74.  
  75.     labels = k_means.labels_
  76.     fig = plt.figure()
  77.     ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)
  78.     ax.scatter(X[:, 3], X[:, 0], X[:, 2], c=labels.astype(np.float))
  79.     ax.w_xaxis.set_ticklabels([])
  80.     ax.w_yaxis.set_ticklabels([])
  81.     ax.w_zaxis.set_ticklabels([])
  82.     ax.set_xlabel('Petal width')
  83.     ax.set_ylabel('Sepal length')
  84.     ax.set_zlabel('Petal length')
  85.     plt.show()
  86.  
  87.  
  88. def zadanie4():
  89.     lista_plaz = []
  90.     lista_lasow = []
  91.     X = []
  92.     for x in range(1, 11):
  93.         nazwa_plaza = 'beach' + np.str(x) + '.jpg'
  94.         nazwa_las = 'las' + np.str(x) + '.jpg'
  95.         lista_plaz.append(cv2.imread(nazwa_plaza, cv2.IMREAD_COLOR))
  96.         lista_lasow.append(cv2.imread(nazwa_las, cv2.IMREAD_COLOR))
  97.         hist_plaz = cv2.calcHist(lista_plaz[x-1], [3], None, [8], [0, 256])
  98.         hist_lasow = cv2.calcHist(lista_lasow[x-1], [3], None, [8], [0, 256])
  99.         X.append(hist_plaz)
  100.         X.append(hist_lasow)
  101.  
  102.     print(len(X))
  103.     print(X)
  104.     k_means = cluster.KMeans(n_clusters=2)
  105.     k_means.fit(X)
  106.  
  107.     test_plaza = cv2.imread('test_plaza.jpg', cv2.IMREAD_COLOR)
  108.     hist = cv2.calcHist(test_plaza, [3], None, [8], [0, 256])
  109.  
  110.     pred = k_means.predict(hist)
  111.     print(pred)
  112.  
  113.  
  114. def zadanie5():
  115.     names = ["Nearest Neighbors", "Linear SVM", "RBF SVM", "Gaussian Process",
  116.              "Decision Tree", "Random Forest", "Neural Net", "AdaBoost",
  117.              "Naive Bayes", "QDA"]
  118.  
  119.     classifiers = [
  120.         KNeighborsClassifier(3),
  121.         SVC(kernel="linear", C=0.025),
  122.         SVC(gamma=2, C=1),
  123.         GaussianProcessClassifier(1.0 * RBF(1.0)),
  124.         DecisionTreeClassifier(max_depth=5),
  125.         RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1),
  126.         MLPClassifier(alpha=1),
  127.         AdaBoostClassifier(),
  128.         GaussianNB(),
  129.         QuadraticDiscriminantAnalysis()]
  130.  
  131.     images_and_labels = list(zip(digits.images, digits.target))
  132.     for index, (image, label) in enumerate(images_and_labels[:4]):
  133.         plt.subplot(2, 4, index + 1)
  134.         plt.axis('off')
  135.         plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
  136.         plt.title('Training: %i' % label)
  137.  
  138.     n_samples = len(digits.images)
  139.     data = digits.images.reshape((n_samples, -1))
  140.  
  141.     classifier = svm.LinearSVC()
  142.     classifier.fit(data[:np.int(n_samples / 2)], digits.target[:np.int(n_samples / 2)])
  143.     expected = digits.target[np.int(n_samples / 2):]
  144.     predicted = classifier.predict(data[np.int(n_samples / 2):])
  145.  
  146.     print("Classification report for classifier %s:\n%s\n"
  147.           % (classifier, metrics.classification_report(expected, predicted)))
  148.     print("Confusion matrix:\n%s" % metrics.confusion_matrix(expected, predicted))
  149.  
  150.     images_and_predictions = list(zip(digits.images[int(n_samples / 2):], predicted))
  151.     for index, (image, prediction) in enumerate(images_and_predictions[:4]):
  152.         plt.subplot(2, 4, index + 5)
  153.         plt.axis('off')
  154.         plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
  155.         plt.title('Prediction: %i' % prediction)
  156.  
  157.     plt.show()
  158.  
  159.  
  160. if __name__ == '__main__':#
  161.     # zadanie1()
  162.     # zadanie2()
  163.     # zadanie3()
  164.     # 4 PRAWIE DZIALA
  165.     # zadanie4()
  166.     zadanie5()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement