
Concept explainers
( can you solve my error here is my python code and errors can you fixed my code plz as soon as)
import numpy as np
import matplotlib.pyplot as plt
###########################
#
# Perceptron Object
#
#
##########################
class Perceptron(object):
def __init__(self, eta=0.1, iter=50):
self.eta = eta
self.iter = iter
def fit(self, X, y):
self.w_ = np.zeros(X.shape[1])
self.errors_ = []
for _ in range(self.iter):
error = 0
for xi, target in zip(X, y):
update = self.eta * (target - self.predict(xi))
self.w_[:] += update * xi
error += int(update != 0.0)
self.errors_.append(error)
return self
def predict(self, x):
return np.where(np.dot(x, self.w_[:]) >= 0.0, 1, -1)
###########################
#
# Linear Regression Object
#
#
##########################
class LinearRegression(object):
def __init__(self, eta=0.1, iter=50):
self.eta = eta
self.iter = iter
def fit(self, X, y):
self.w_ = np.zeros(X.shape[1])
self.cost_ = []
for i in range(self.iter):
output = self.net_input(X)
error = y - output
self.w_[:] += self.eta * np.dot(X.T, error)
cost = np.dot(error.T, error) / 2.0
self.cost_.append(cost)
return self
def net_input(self, X):
return np.dot(X, self.w_[:])
def predict(self, x):
return np.where(np.dot(x, self.w_[:]) >= 0.0, 1, -1)
###########################
#
# Logistic Regression Object
#
#
##########################
class LogisticRegression(object):
def __init__(self, eta=0.1, iter=50):
self.eta = eta
self.iter = iter
def fit(self, X, y):
self.w_ = np.zeros(X.shape[1])
self.cost_ = []
for i in range(self.iter):
s = np.dot(X, self.w_[:])
grad = np.dot(X.T, y) / (1 + np.exp(np.dot(y, s.T)))
error = -grad.sum() / len(y)
self.w_[:] += self.eta * error
cost = np.dot(error.T, error) / 2.0
self.cost_.append(cost)
return self
def predict(self, x):
return np.where(np.dot(x, self.w_[:]) >= 0.0, 1, -1)
###########################
#
# main()
#
#
##########################
def main():
dataFile = ("C:\\Users\\mspat\\Desktop\\iris.txt")
X, y = formatIris(dataFile) # X includes 1 for the bias: X = [[1,x11, x12], [1,x21,x22], .... [1,xN1, xN2]]T
# X = np.array(([1, 5.7, 4.2], [1, 5.7, 4.1], [1, 7.1, 6.7], [1, 6.7, 5]))
# y = np.array([1, 1, -1, 1])
eta = 0.1 # learning rate
X_std = np.copy(X)
X_std[:, 1] = (X[:, 1] - X[:, 1].mean()) / X[:, 1].std() # sepal len
X_std[:, 2] = (X[:, 2] - X[:, 2].mean()) / X[:, 2].std() # petal len
# Perceptron
ppn = Perceptron(eta) # , iter=len(y))
ppn.fit(X, y)
# Linear Regression
linR = LinearRegression(eta)
linR.fit(X, y)
# Logistic Regression
logR = LogisticRegression(eta)
logR.fit(X, y)
plot_regions(X, y, classifier=ppn)
plot_regions(X, y, classifier=linR)
plot_regions(X, y, classifier=logR)
###########################
#
# iris data file
# get sepal and petal lengths of iris-vericolor and iris-virginica
#
##########################
def formatIris(dataset):
X = []
y = []
with open(dataset, 'r') as f:
for line in f:
sline = line.replace('\n', '')
t = sline.split(',')
if t[4] == 'Iris-versicolor':
val = 1
elif t[4] == 'Iris-virginica':
val = -1
else:
val = 0
X.append([1, float(t[0]), float(t[2])]) # [1, sepal len, petal len]
y.append(val)
return np.array(X), np.array(y)
###########################
#
# Plot regions
#
#
##########################
from matplotlib.colors import ListedColormap
def plot_regions(X, y, classifier, resolution=0.02):
# setup marker generato and clor map
markers = ('o', 'x', 's', '^', 'v')
colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
cmap = ListedColormap(colors[:len(np.unique(y))])
# plot the decision surface
x1_min, x1_max = X[:, 1].min() - 1, X[:, 1].max() + 1
x2_min, x2_max = X[:, 2].min() - 1, X[:, 2].max() + 1
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution))
coordinates = np.array([np.ones(len(xx1.ravel())), xx1.ravel(), xx2.ravel()])
region = np.dot(coordinates.T, classifier.w_[:])
Z = np.where(region >= 0.0, 1, -1)
Z = Z.reshape(xx1.shape)
plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)
plt.xlim(xx1.min(), xx1.max())
plt.ylim(xx2.min(), xx2.max())
for idx, cl in enumerate(np.unique(y)):
plt.scatter(x=X[y == cl, 1], y=X[y == cl, 2], alpha=0.8, c=cmap(idx), marker=markers[idx], label=cl)
plt.xlabel('sepal length')
plt.ylabel('petal length')
plt.legend(loc='upper right')
plt.show()
main()
![Traceback (most recent call last):
File "C:\Users\mspat\PycharmProjects\bioinformatics hw5\hw5.py", line 192, in <module>
main()
File "C:\Users\mspat\PycharmProjects\bioinformatics hw5\hw5.py", line 171, in main
х, у %3
formatIris(datafile)
#x inciudes 1 for the bias: x =
[1,x11,x12], [1,x21,x22],...[1,xN1, xN2]]T
File "C:\Users\mspat\PycharmProjects\bioinformatics hw5\hw5.py", line 126, in formatIris
if t[4] =='Iris-versicolor':
IndexError: list index out of range
Process finished with exit code 1](https://content.bartleby.com/qna-images/question/1834bd91-86c9-40fc-9c20-321ad2d6490a/ba3822dd-3a34-46a8-a0e4-5b96689dd4ab/0nf5v3f_thumbnail.png)

Step by stepSolved in 2 steps

- QUICKLY please. Thank you. Please answer in python quickly Below is code that defines a Quadrilateral class (a shape with four sides), which has four floating point instance variables that correspond to the four side lengths: import math class Quadrilateral: def __init__(self,a,b,c,d): self.a = a self.b = b self.c = c self.d = d def perimeter(self): return self.a + self.b + self.c + self.d def area(self): print("Not enough information") def __lt__(self, other): return self.perimeter() < other.perimeter() Define a Rectangle class that inherits from Quadrilateral, with the following methods: __init__(self, length, width): Override the __init__ method so that the Rectangle constructor only takes in two floating point numbers. Your constructor for Rectangle should only consist of a call to Quadrilateral’s constructor: don’t define any new instance variables. Override the area method to…arrow_forwardProgram 1 Two files are required, a data class named Book and an executable class named TestBook. Class Book • has instance data members (all private) String title, String author, int pages, double price. • has a public static int variable named numBooks with an initial value of zero. • has a parameterized constructor that will be used to make a Book object and assign values to its data members, and increment numBooks. • has a no-arg constructor that increments numBooks. • has getters and setters for all instance data members. • has a toString() method that returns a string displaying the state of a Book instance. • Use the numBooks variable to report the number of books instantiated. Class TestBook This class needs a main method and two more methods. In main: 1. create an array capable of holding six Book objects. 2. use the parameterized constructor to specify the data in the first four elements of this array 3. use the no-arg constructor to create the two remaining books in the…arrow_forwardSummary In this lab, you complete a prewritten Python program for a carpenter who creates personalized house signs. The program is supposed to compute the price of any sign a customer orders, based on the following facts: The charge for all signs is a minimum of $35.00. The first five letters or numbers are included in the minimum charge; there is a $4 charge for each additional character. If the sign is make of oak, add $20.00. No charge is added for pine. Black or white characters are included in the minimum charge; there is an additional $15 charge for gold-leaf lettering. Instructions Make sure the file HouseSign.py is selected and open. You need to assign variables for the following: A variable for the cost of the sign assigned to 0.00 (charge). A variable for the number of characters assigned to 8 (numChars). A variable for the color of the characters assigned to "gold" (color). A variable for the wood type assigned to "oak" (woodType). Write the rest of the program using…arrow_forward
- javaarrow_forwardThere are given code: # TODO: Import math module def quadratic_formula(a, b, c):# TODO: Compute the quadratic formula results in variables x1 and x2return (x1, x2) def print_number(number, prefix_str):if float(int(number)) == number:print("{}{:.0f}".format(prefix_str, number))else:print("{}{:.2f}".format(prefix_str, number)) if __name__ == "__main__":input_line = input()split_line = input_line.split(" ")a = float(split_line[0])b = float(split_line[1])c = float(split_line[2])solution = quadratic_formula(a, b, c)print("Solutions to {:.0f}x^2 + {:.0f}x + {:.0f} = 0".format(a, b, c))print_number(solution[0], "x1 = ")print_number(solution[1], "x2 = ")arrow_forwardPython Turtle: How do I fix the code to make it generate lakes as bigger random dots, and mountains as a separate color (gray) from the grass area? (Big error: lake generates as entire circle inside land, want it generating like mountains).AKA: How do I separate each of the values to generate on its own without conflicting eachother. import turtleocean = "#000066"sand = "#ffff66"grass = "#00cc00"lake = "#0066ff"mountain = [[-60, 115], [-65, 200], [-10, 145], [-30, 70], [50, 115], [100, 150], [70, 200], [30, 70], [10, 180], [-10, 220]]def draw_circle(radius, line_color, fill_color): my_turtle.color(line_color) my_turtle.fillcolor(fill_color) my_turtle.begin_fill() my_turtle.circle(radius) my_turtle.end_fill()def move_turtle(x, y): my_turtle.penup() my_turtle.goto(x, y) my_turtle.pendown()num_cuts = int(input("How many rivers do you want on your Island? ")) screen = turtle.Screen()screen.bgcolor(ocean)screen.title("Island Generator")my_turtle =…arrow_forward
- In java, without Arrays and using only String methods ( don't use String builder) // Question 17: In MS-DOS, a file name consists of up // to 8 characters (excluding '.', ':', backslask, '?', // and '*'), followed by an optional dot ('.' character) // and extension. The extension may contain zero to three // characters. For example, 1STFILE.TXT is a valid filename. // Filenames are case-blind. // // Write and test a method that takes // in a String, validates it as a valid MS-DOS file // name, appends the extensions ".TXT" if no extension // is given (that is, no '.' appears in FILENAME), converts // the name to uppercase, and returns the resulting string // to the calling method // If fileName ends with a dot, remove that dot and do not // append the default extension. If the name is invalid, // validFileName should return null. public String validFileName(String n) { }arrow_forwardn this lab, you complete a prewritten Python program for a carpenter who creates personalized house signs. The program is supposed to compute the price of any sign a customer orders, based on the following facts: The charge for all signs is a minimum of $35.00. The first five letters or numbers are included in the minimum charge; there is a $4 charge for each additional character. If the sign is make of oak, add $20.00. No charge is added for pine. Black or white characters are included in the minimum charge; there is an additional $15 charge for gold-leaf lettering.arrow_forwardIn Python: What gets printed by executing the following code?arrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education





