コード例 #1
0
ファイル: gui_v02.py プロジェクト: Bhavya06/Neural-Networks
acc = 0

l = []

eyes = generateColumns(1, 12)
df = pd.read_csv('Eyes.csv')
first_column = df.columns[0]
df = df.drop([first_column], axis=1)
# print("hello")
X = df[eyes]
y = df['truth_value']  #the actual class labels
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30)
# Data Normalization
from sklearn.preprocessing import StandardScaler as SC
sc = SC()
X_train_scaled = sc.fit_transform(X_train)
X_test_scaled = sc.fit_transform(X_test)
#not scaling y since it's already 0s and 1s
X_train, y_train, X_test, y_test = np.array(X_train), np.array(
    y_train), np.array(X_test), np.array(y_test)
#converting all the scaled data to numpy arrays
gen = StringVar()
ran = StringVar()
grad = StringVar()
exp = StringVar()
time = StringVar()
accu = StringVar()
button = Button(root,
                text="Begin?",
                width='10',
コード例 #2
0
# visualize how they look
num_classes = len(np.unique(y))
## class 1
for ind, val in enumerate (np.unique(y)):
    plt.scatter (x[y==val,0], x[y==val,1],
                 marker = marker_list_all[ind],
                 c = color_list_all[ind],
                 label='Class '+str(val))
plt.legend (loc = 0)
plt.xlim (x[:,0].min(), x[:,0].max())
plt.ylim (x[:,1].min(), x[:,1].max())
plt.tight_layout ()
pic1 = 'scatter-show.pdf'
plt.savefig (pic1)
plt.show ()

# separating data set
xtr, xte, ytr, yte = tts (x, y, test_size = 0.3)
# standarizing the data
sc0 = SC ()
sc0.fit (xtr)
xtr_std = sc0.transform (xtr)
xte_std = sc0.transform (xte)
# The following is for classifying
dtc =  DTC()
dtc.fit (xtr_std, ytr)
ypd = dtc.predict (xte_std)
print ("accuracy: ", dtc.score (xte_std, yte))

pdb (x, y, classifier=dtc, standardizer=sc0)
def main(k):
    trainingSet = []
    testSet = []
    #Read the dataset
    data = pd.read_csv('Andhra_dataset2.csv')
    #Clean the data
    data_cleaning(data)
    #splitting into test and train sets
    trainingSet, testSet = train_test_split(data,
                                            test_size=0.10,
                                            random_state=27)
    #0.10,27
    #Initialize no. of neighbours
    sc = SC()
    no_of_neighbours = k
    testSet = np.array(testSet)
    trainingSet = np.array(trainingSet)
    #Normalize the data set
    testSet[:, 0:9] = sc.fit_transform(testSet[:, 0:9])
    trainingSet[:, 0:9] = sc.fit_transform(trainingSet[:, 0:9])
    len_testSet = len(testSet)

    count = 0
    cm = [[0, 0], [0, 0]]
    tp = 0
    tn = 0
    fp = 0
    fn = 0
    startTime = datetime.now().microsecond
    for i in range(len_testSet):
        #Finds nearest  neighbours for each test instance
        neighbours = find_nearest_neigbours(no_of_neighbours, testSet[i],
                                            trainingSet)
        #results for that test instance
        result = results(neighbours, no_of_neighbours)
        #if the predicted label and the actual label are the same, count is incremented
        if (result - testSet[i][-1] == 0):
            if (result == 0):
                tn += 1
            else:
                tp += 1
            count = count + 1
        else:
            if (result == 1):
                fp += 1
            else:
                fn += 1

    #Accuracy of the model is printed
    cm[0][0] = tp
    cm[0][1] = fn
    cm[1][0] = fp
    cm[1][1] = tn

    endTime = datetime.now().microsecond
    time = (endTime - startTime) / 1000000.0

    # Results
    print(
        f"\n##########    k-Nearest Neighbours to detect Potential Low Birth Weight Cases   ##########\n"
    )
    print(f"Model Parameter :\n \t Value of k:{k}\n")
    print(f"Time taken for Evaluation: {time} seconds\n")
    print("Confusion Matrix : \n")
    print(cm)
    print("\nRESULTS \n")
    print("\tAccuracy percentage: ", count / float(len(testSet)) * 100)
    print("\tAccuracy:", (tp + tn) / (tp + tn + fp + fn))
    p = tp / (tp + fp)
    r = tp / (tp + fn)
    fscore = (2 * p * r) / (p + r)
    print("\tPrecision:", tp / (tp + fp))
    print("\tRecall:", tp / (tp + fn))
    print("\tf1 score: ", fscore)
コード例 #4
0
            marker='o',
            color='red')
plt.scatter(x=df[df['y'] == 0]['A'],
            y=df[df['y'] == 0]['B'],
            label=0,
            marker='x',
            color='blue')
plt.xlabel('bill_amount1')
plt.ylabel('pay_amount1')

# In[8]:

# fea is a list of features to be used in the classification
fea = ['A', 'B']

sc = SC()
X_train = df[fea]
y_train = df['y']
sc.fit(X_train)
X_train_std = sc.transform(X_train)

# training
clf = SVC(C=1, kernel='rbf', class_weight='balanced')
clf.fit(X_train_std, y_train)

y_pred_train = clf.predict(X_train_std)

print('acc -------', acc(y_true=y_train, y_pred=y_pred_train))
print('precision:', precision_score(y_true=y_train, y_pred=y_pred_train))
print('recall:', recall_score(y_true=y_train, y_pred=y_pred_train))
print('f1:', f1_score(y_true=y_train, y_pred=y_pred_train))