KNearest code modify it to use the features temperature, luminosity, and absolute magnitude to predict the spectral class

icon
Related questions
Question

Using the KNearest code modify it to use the features temperature, luminosity, and absolute magnitude to predict the spectral class of the stars

FEATURE         FEATURE         FEATURE                   LABEL

Temperature     luminosity      absolute magnitude        spectral type

3068              0.0024             16.12                                    M

2800              0.0002             16.65                                     M

16500             0.013              11.89                                      B

12990             0.000085           12.23                                  F

8500              0.0005             14.5                                        A

39000             204000             -4.7                                        O

4015              282000             -11.39                                      K

6850              229000             -10.07                                      G

 

import math
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

def knearest(X_train, y_train, predict):
    min_dist = 10000
    min_sample_idx = 0
    for i1 in range(0, len(X_train)):
        squares = 0
        for i2 in range(0, len(X_train[i1])):
            squares = squares + math.pow((X_train[i1][i2] - predict[i2]), 2)
        if math.sqrt(squares) < min_dist:
            min_dist = math.sqrt(squares)
            min_sample_idx = i1
    return y_train[min_sample_idx]

def trainAndScore(randomState):
    iris_dataset = load_iris()
    X_train, X_test, y_train, y_test = train_test_split(iris_dataset['data'], iris_dataset['target'], random_state = randomState)
    
    total = 0
    correct = 0
    for i in range(0, len(X_test)):
        ans = knearest(X_train, y_train, X_test[i])
        total = total + 1
        if ans == y_test[i]:
            correct = correct + 1
    return correct/total

score = trainAndScore(0)
print(round(score, 2))

Expert Solution
steps

Step by step

Solved in 3 steps

Blurred answer