Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import numpy as np
import sklearn
import os
# Import of support vector machine (svm)
from sklearn import svm
"""---------------------------- SETTING -----------------------------------"""
# Changing current working directory
os.chdir("C:\\")
# Set up ML and scikit-learn
clf = svm.SVC(gamma=0.01, C=100)
# Training data (digits: questions, target: answers)
digits = open("trainingP.txt").read().split("\n")
target = open("target.txt").read().split("\n")
# Initializing numpy arrays
digitsD = np.array(np.fromstring(digits[0],sep=","))
# Completing numpy array for digits
for line in digits[1:]:
try:
sample = np.fromstring(line,sep=",")
digitsD = np.vstack((digitsD,sample))
except:
pass
# Converts strings into integers (not necessary if you
# choose option 1 below)
t = [int(i) for i in target]
# 1 : All strings
# 2 : All integers
t = np.array(target) # 1
#t = np.array(t) # 2
"""---------------------------- TRAINING -----------------------------------"""
# Model fitting (training)
x,y = digitsD,t
print("Training...")
clf.fit(x,y)
# Answer: 1
print("Prediction:",clf.predict(np.array([3,11,1,9,2,5,3,5,4,1])))
"""---------------------------- TESTING -----------------------------------"""
# Load questions and answers
rawQuestions = open("testQuestions.txt").read().split("\n")
rawAnswers = open("Answers.txt").read().split("\n")
# Initialize numpy arrays
questions = np.array(np.fromstring(rawQuestions[0],sep=","))
answers = np.array(rawAnswers)
for q in rawQuestions[1:]:
try:
q1 = np.fromstring(q,sep=",")
questions = np.vstack((questions,q1))
except:
pass
# Testing function
def tryAnswer(qu,an):
machineAnswer = clf.predict(qu)
if machineAnswer == an:
#print("Correct!")
return True
else:
#print("Wrong!")
return False
print("Testing...")
# Start the test
j = 0
right = 0
wrong = 0
while j < 10000:
result = tryAnswer(questions[j],answers[j])
if result:
right += 1
else:
wrong += 1
j += 1
# Print some statistics
print("Statistics, correct rate:",right/(right+wrong))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.