Question

In: Computer Science

Please I seek assistance Python Programing import os import numpy as np def generate_assignment_data(expected_grade_file_path, std_dev, output_file_path):...

Please I seek assistance
Python Programing

import os
import numpy as np

def generate_assignment_data(expected_grade_file_path,
                             std_dev, output_file_path):
    """
    Retrieve list of students and their expected grade from file,
    generate a sampled test grade for each student
    drawn from a Gaussian distribution defined by the
    student expected grade as mean, and the given
    standard deviation.

    If the sample is higher than 100, re-sample.
    If the sample is lower than 0 or 5 standard deviations below mean,
    re-sample

    Write the list of student grades to the given
    output file using ID and grade with TAB separation.

    :param expected_grade_file_path: This is our file of student IDs and expected grades
    :param std_dev: Standard deviation used when sampling grades
    :param output_file_path: Where to write the sample grades
    :return: number of student grades generated and
            tuple of mean, median and standard deviation of grades
    """

Solutions

Expert Solution

The required Code, Sample input file & sample output file are given below. Basically, we read the input file using python csv dictreader which reads each row as a dictionary. We then use Numpy random.normal function to draw a sample from the Gaussian distribution :

CODE:

import csv
import os
import numpy as np

def generate_assignment_data(expected_grade_file_path, std_dev, output_file_path):

    with open(expected_grade_file_path, newline='') as csv_in:    #Opening the file having expected grades
        with open(output_file_path, 'w', newline='') as csv_out:   #Opening the file to write in write mode
            fieldnames = ['id', 'expected_grade', 'sampled_grade']   #specifying fieldnames for output file
            writer = csv.DictWriter(csv_out, fieldnames=fieldnames, delimiter='\t')  #creating a writer object for writing output file
            writer.writeheader()
            data = csv.DictReader(csv_in, delimiter=',')  #read data from specified file
            generated_grades = []        #initialize empty list for generated sample grades
            for row in data:
                row['sampled_grade'] = -1
                #keep sampling again till any of the given condition is true
                while (row['sampled_grade'] < 0 or row['sampled_grade'] > 100 or row['sampled_grade'] < 5 * std_dev):
                    row['sampled_grade'] = np.random.normal(float(row['expected_grade']), std_dev)   #generate the sample
                generated_grades.append(row['sampled_grade'])
                print(row)
                writer.writerow(row)
            generated_grades = np.array(generated_grades)  #convert generated grades list to numpy array
            return generated_grades.size,(generated_grades.mean(),np.median(generated_grades),generated_grades.std()) #return required values

#testing
print(generate_assignment_data('students.csv', 5, 'students_out.csv'))

CODE Screenshot:

Sample Input file used for testing:

id,expected_grade
s1,70
s2,80
s3,65
s4,75

Output:

Output file data:

id   expected_grade   sampled_grade
s1   70   72.89787027604346
s2   80   86.3827664017767
s3   65   75.18435378753523
s4   75   77.46518085069853

(*Note: Please up-vote. If any doubt, please let me know in the comments)


Related Solutions

In python import numpy as np Given the array b = np.arange(-6, 4) compute and print...
In python import numpy as np Given the array b = np.arange(-6, 4) compute and print 1.) The array formed by \(bi^2 - 1\), where the \(bi\) are the elements of the array b. 2.) The array formed by multiplying b with the scalar 100. 3.)The array formed by 2.0 b i in reverse order. (Note: the base 2.0 must be a floating point number; for integer values a ValueError: Integers to negative integer powers are not allowed. is raised.)...
UsePython (import numpy as np) use containers (Branching if statement, while loop, for loop, numpy Array)...
UsePython (import numpy as np) use containers (Branching if statement, while loop, for loop, numpy Array) Implement an algorithm to guess a random number that the computer generates. The random number must be an integer between 1 and 1000 (inclusive). For each unsuccessful attempt, the program must let the user know whether to deal with a higher number or more. low. There is no limit on the number of attempts, the game only ends when the user succeeds. The user...
import math import numpy as np import numpy.linalg from scipy.linalg import solve A = np.array([[-math.cos(math.pi/6),0, math.cos(math.pi/3),0,...
import math import numpy as np import numpy.linalg from scipy.linalg import solve A = np.array([[-math.cos(math.pi/6),0, math.cos(math.pi/3),0, 0, 0], [-math.sin(math.pi/6), 0, -math.sin(math.pi/3), 0, 0, 0], [math.cos(math.pi/6), 1, 0, 1, 0, 0], [math.sin(math.pi/6), 0, 0, 0, 1, 0], [0, -1, -math.cos(math.pi/3), 0, 0, 0], [0, 0, math.sin(math.pi/3), 0, 0, 1]]) b = np.array([0, 2000, 0, 0, 0, 0]) x = [0, 0, 0, 0, 0, 0] def seidel(a, x, b): # Finding length of a(3) n = len(a) # for loop for...
Please fix all the errors in this Python program. import math def solve(a, b, c): """...
Please fix all the errors in this Python program. import math def solve(a, b, c): """ Calculate solution to quadratic equation and return @param coefficients a,b,class @return either 2 roots, 1 root, or None """ #@TODO - Fix this code to handle special cases d = b ** 2 - 4 * a * c disc = math.sqrt(d) root1 = (-b + disc) / (2 * a) root2 = (-b - disc) / (2 * a) return root1, root2 if...
#Python 3.7 "Has no attribute" error - def get():     import datetime     d = date_time_obj.date()...
#Python 3.7 "Has no attribute" error - def get():     import datetime     d = date_time_obj.date()     return(d) print(a["Date"]) print("3/14/2012".get()) How to write the "get" function (without any imput), to convery the format ""3/14/2012" to the format "2012-03-14", by simply using "3/14/2012".get() ?
Python I am creating a class in python. Here is my code below: import csv import...
Python I am creating a class in python. Here is my code below: import csv import json population = list() with open('PopChange.csv', 'r') as p: reader = csv.reader(p) next(reader) for line in reader: population.append(obj.POP(line)) population.append(obj.POP(line)) class POP: """ Extract the data """ def __init__(self, line): self.data = line # get elements self.id = self.data[0].strip() self.geography = self.data[1].strip() self.targetGeoId = self.data[2].strip() self.targetGeoId2 = self.data[3].strip() self.popApr1 = self.data[4].strip() self.popJul1 = self.data[5].strip() self.changePop = self.data[6].strip() The problem is, I get an error saying:  ...
PYTHON PROBLEM: TASKED TO FIND THE FLAW WITH THE FOLLOWING CODE: from itertools import count def...
PYTHON PROBLEM: TASKED TO FIND THE FLAW WITH THE FOLLOWING CODE: from itertools import count def take_e(n, gen):     return [elem for (i, elem) in enumerate(gen) if i < n] def take_zc(n, gen):     return [elem for (i, elem) in zip(count(), gen) if i < n] FIBONACCI UNBOUNDED: def fibonacci_unbounded():     """     Unbounded Fibonacci numbers generator     """     (a, b) = (0, 1)     while True:         # return a         yield a         (a, b) = (b, a + b) SUPPOSED TO RUN THIS TO ASSIST WITH...
Copy the following Python fuction discussed in class into your file: from random import * def...
Copy the following Python fuction discussed in class into your file: from random import * def makeRandomList(size, bound): a = [] for i in range(size): a.append(randint(0, bound)) return a a. Add another function that receives a list as a parameter and computes the sum of the elements of the list. The header of the function should be def sumList(a): The function should return the result and not print it. If the list is empty, the function should return 0. Use...
Python program please no def, main, functions Given a list of negative integers, write a Python...
Python program please no def, main, functions Given a list of negative integers, write a Python program to display each integer in the list that is evenly divisible by either 5 or 7. Also, print how many of those integers were found. Sample input/output: Enter a negative integer (0 or positive to end): 5 Number of integers evenly divisible by either 5 or 7: 0 Sample input/output: Enter a negative integer (0 or positive to end): -5 -5 is evenly...
I need the following problem to be coded in python without using Numpy: Given input features...
I need the following problem to be coded in python without using Numpy: Given input features x1​, x2​,..., xi​ and corresponding weights w0​, w1​, w2​,...wi​. Write a function, called 'Perceptron', that returns the output value yi. For your function, use the following perceptron activation function: g(X,W)={1 if wTx>0;0 otherwise} The inputs X and W will be arrays of the input feature and weight values, respectively. All values will be integers. Your function will return gp​(X,W), which is a single integer...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT