VelocerUygulamayı aç

Velocer › Bilgi kartları › University of Wisconsin–Madison › CS 320: Data Science Programming II · UW-Madison

CS 320: Data Science Programming II · UW-Madison

Cards i use for CS 320. lmk if something looks off. · lemma_latte tarafından · 165 kart

University of Wisconsin–Madison

Bu desteyi çalış Göm

  1. What is a key structural difference between a relational database and a flat CSV/JSON file?A relational database enforces a strict schema with multiple named tables, explicit column names, and uniform data types, whereas CSV/JSON files are flat and lack enforced structure.
  2. Why should you run assert os.path.exists("bus.db") before sqlite3.connect("bus.db")?Because sqlite3.connect silently creates a new, empty database file if the path is misspelled, leading to unexpected behavior.
  3. What should you always do after finishing with a SQLite connection?Always close the connection with conn.close().
  4. What is the first query you should run on an unfamiliar SQLite database to discover its schema?Inspect the sql column of sqlite_master (e.g., SELECT sql FROM sqlite_master) to see the CREATE TABLE statements and column types.
  5. What is the difference between COUNT(*) and COUNT(DISTINCT col)?COUNT(*) counts all rows, while COUNT(DISTINCT col) counts unique non-null values in the specified column.
  6. How can you use an alias in ORDER BY or HAVING in SQL?Use AS to alias a computed expression in the SELECT clause, then reference that alias in ORDER BY or HAVING.
  7. What is the difference between WHERE and HAVING?WHERE filters individual rows before grouping, while HAVING filters aggregated groups after GROUP BY.
  8. What does df.set_index("id") do, and what happens if you run it twice?It promotes the id column to the row index and removes it from regular columns; running it a second time raises a KeyError because the column no longer exists.
  9. How do you detect, drop, and impute missing values in a Pandas DataFrame?Detect with df.isna(), drop with df.dropna(), and impute with df.fillna(val).
  10. How do you replace sentinel values (like empty strings) with np.nan in Pandas?Use df.replace(target, replacement), e.g., df.replace("", np.nan).
  11. How do you apply a custom elementwise function to a Pandas column?Use df["col"].apply(fn).
  12. Translate to Pandas: SELECT x, y FROM trees WHERE priority > 90trees[trees["priority"] > 90][["x", "y"]]
  13. Translate to Pandas: SELECT species, AVG(diameter) FROM trees GROUP BY speciestrees.groupby("species")["diameter"].mean()
  14. What is a Git repository?A system that tracks the full history of a project via explicit snapshots called commits.
  15. What information does a Git commit record?Who changed what, when, and why (via commit messages).
  16. How does commit history help debug a regression (git blame)?It isolates whether a buggy line was actually introduced in an earlier commit rather than the one where the bug was discovered.
  17. What is the purpose of tagging stable commits like v1.0 or v2.1?To mark stable commits for public release while development continues on main or feature branches.
  18. What is a merge conflict in Git?It occurs when overlapping edits are made to the same lines during a merge, requiring human resolution.
  19. What is the difference between performance and complexity analysis?Performance measures actual wall-clock runtime, which depends on hardware and other factors; complexity analysis (Big-O) abstracts away hardware and measures how the number of executed steps scales asymptotically with input size.
  20. What defines an atomic step in complexity analysis?An atomic step is any unit of work whose execution time is bounded by a constant, i.e., it does not grow slower as input size N increases.
  21. Why is a single line of Python not always one atomic step? Give an example.Because some operations take time proportional to input size. For example, x in L is O(N) when L is a list but O(1) when L is a set or dict.
  22. What are the two components that make up a graph?Nodes (vertices/entities) and edges (relationships between them).
  23. What is a path in a graph?A sequence of edges connecting a source node to a destination node.
  24. When is an undirected graph connected?When a path exists between every pair of nodes.
  25. What is the difference between a strongly connected and a weakly connected directed graph?Strongly connected: a directed path exists between every ordered pair (u, v). Weakly connected: replacing directed edges with undirected edges yields a connected graph.
  26. What is a cycle in a graph?A non-empty path that starts and ends at the same node.
  27. What is a Directed Acyclic Graph (DAG)?A directed graph that contains no cycles.
  28. What conditions must a DAG satisfy to be a tree?Exactly one node (the root) has 0 parents, and every other node has exactly 1 parent. Nodes with 2 parents (diamond DAG) or disconnected components mean it is not a tree.
  29. What are leaves in a tree?Nodes that have 0 children.
  30. How does a linked list relate to a tree?A linked list is a tree in which every node has at most 1 child.
  31. What is a binary tree?A tree in which every node has at most 2 children (self.left and self.right).
  32. State the Binary Search Tree (BST) invariant.For every node u, all values in u's left subtree are strictly less than u.label, and all values in u's right subtree are strictly greater than u.label.
  33. What is the time complexity of search or insertion in a height-balanced BST, and when does it degrade?O(log N) because half the tree is eliminated at each step; it degrades to O(N) if elements are inserted in sorted order, forming a linked list.
  34. How does Depth-First Search (DFS) explore a graph, and what data structure does it naturally use?It explores as deep as possible along each branch before backtracking, naturally using the call stack (LIFO) via recursion.
  35. How does Breadth-First Search (BFS) explore a graph, and what does it guarantee?It explores nodes in concentric layers by distance from the start (all children before grandchildren), guaranteeing the shortest path (fewest edges) in an unweighted graph.
  36. What data structure does BFS require, and why is list.pop(0) discouraged?BFS uses a FIFO queue, e.g. collections.deque with append and popleft in O(1). list.pop(0) shifts all elements, degrading each pop to O(N).
  37. What can requests.get(url) not do that Selenium can?It cannot execute JavaScript or interact with buttons; it only fetches the initial static HTML. Selenium drives a real (headless) browser to run JS and click elements.
  38. What does b.page_source return in Selenium?The current DOM HTML string of the loaded page, reflecting any JavaScript-driven changes.
  39. Difference between find_element and find_elements in Selenium?find_element returns the first match or raises NoSuchElementException; find_elements returns a list of all matching elements (empty list if none).
  40. What does an IP address identify on a network?A specific host or VM on the network, analogous to a street address (e.g., 18.216.110.65).
  41. What does a port number identify?A specific listening process on a machine, like an apartment number. Examples: SSH=22, HTTP=80, HTTPS=443, Jupyter=2020, Flask=5000.
  42. What is the difference between binding to 127.0.0.1 and 0.0.0.0?127.0.0.1 is localhost (internal loopback only, no external access); 0.0.0.0 binds all network interfaces, allowing external traffic.
  43. What does DNS do?The Domain Name System translates human-readable domain names like example.com into IP addresses before the HTTP request is sent.
  44. How do you check robots.txt compliance before crawling a URL?Use RobotFileParser: rp.set_url(base + "/robots.txt"), rp.read(), then check rp.can_fetch(user_agent, url) before requesting.
  45. What does resp.raise_for_status() do?Raises an exception when the response has a 4xx or 5xx status code.
  46. How do you map a URL to a Python function in Flask?Decorate the handler function with @app.route("/path"); the function returns HTML, JSON via flask.jsonify, or dynamic image byte streams.
  47. How do you return a matplotlib SVG from a Flask route?Write the SVG to io.BytesIO and return flask.Response(svg, headers={"Content-Type": "image/svg+xml"}).
  48. How do you access query parameters like /search?q=madison&limit=5 in Flask?Use the dictionary-like flask.request.args.get("q") (and .get("limit")).
  49. What is the null hypothesis in an A/B test comparing CTRs of versions A and B?H0: versions A and B have identical underlying CTRs, so any observed difference is random chance. If pvalue < 0.05, reject H0.
  50. Why should you use raw strings like r"\d+" for regex patterns in Python?Python string literals treat \ as an escape character, so without raw strings you must double-escape (e.g., "\\d+"). The r prefix disables Python-level escaping so the regex engine receives exactly the characters written.
  51. What does the regex character class \w match?A word character: [a-zA-Z0-9_] (letters, digits, and underscore).
  52. What does the dot (.) match in a regex, and what does it not match?It matches any character except a newline (\n).
  53. What is the difference between ^ inside versus outside square brackets in regex?Outside brackets, ^ is the start-of-string anchor. Inside a negated set like [^abc], it means negation (match any character not in the set).
  54. What do the quantifiers * and + mean in regex?* matches 0 or more of the preceding element; + matches 1 or more. Both are greedy by default.
  55. How do you make a greedy quantifier non-greedy (lazy) in regex?Append ? to the quantifier, e.g., *? or +?. A lazy quantifier matches as few characters as possible.
  56. What does the regex {m,n} quantifier specify?It matches between m and n repetitions of the preceding element (inclusive).
  57. What does re.findall return when the pattern contains capture groups?It returns only the contents of the captured groups (or tuples of groups if there are multiple), not the full match. Wrap the whole regex in an outer group if you also want the full match.
  58. What does ax.transAxes use as its coordinate system?Normalized [0, 1] x [0, 1] coordinates within the subplot box, where (0,0) is bottom-left and (1,1) is top-right, independent of data limits.
  59. How do you add a matplotlib Circle or Polygon to an axes?Create it with plt.Circle((x, y), r) or plt.Polygon(...), then attach it with ax.add_patch(c) (and optionally ax.autoscale_view()).
  60. How do you keep circles round on a rectangular matplotlib plot?Call ax.set_aspect(1) so the axes have equal scaling in both directions.
  61. What does gpd.read_file("file.geojson") return?A GeoDataFrame (inheriting from pd.DataFrame) with a special "geometry" GeoSeries column of shapely objects such as Polygon, MultiPolygon, Point, or LineString.
  62. How do you overlay multiple GeoDataFrame layers on the same map?Pass the existing axes to each plot call via ax=ax, e.g., gdf2.plot(ax=ax).
  63. What does shape.buffer(r) do in Shapely?It expands a shape outward by radius r, e.g., Point(5, 5).buffer(3) creates a circle of radius 3 around the point.
  64. What is the difference between .union() and .intersection() in Shapely?.union(other) combines two shapes (OR), while .intersection(other) returns the overlapping region (AND).
  65. What is the difference between regression and classification in supervised learning?Regression predicts a continuous quantity, while classification predicts a discrete category.
  66. What is the difference between clustering and decomposition in unsupervised learning?Clustering groups similar rows together (e.g., KMeans), while decomposition factors rows into combinations of latent component vectors (e.g., PCA).
  67. What shape must X be when fitting a scikit-learn LinearRegression model?X must be a 2D DataFrame or 2D array, e.g., using double brackets df[["POP"]]. The target y is a 1D Series or vector.
  68. What does the R² score measure in regression?The fraction of variance in y explained by the model. R² = 1.0 is perfect prediction, 0.0 is no better than predicting the mean, and negative values on test data indicate severe overfitting or poor fit.
  69. Why use train_test_split in model evaluation?To hold out unseen test data so model performance can be evaluated on data not used during training.
  70. How do you run k-fold cross-validation in scikit-learn?Use cross_val_score(model, train[xcols], train[ycol], cv=10) to compute scores across folds on the training data.
  71. When selecting among candidate models using cross-validation, what score characteristics are desirable?A high scores.mean() and a low scores.std(), meaning good average performance and low sensitivity to data splits.
  72. How can linear regression fit a non-linear curve like y = c₁x + c₂x² + b?Use PolynomialFeatures(degree=2, include_bias=False) to generate feature columns [x, x²] before applying linear regression.
  73. How are string categorical features handled in a regression pipeline?Convert them into binary indicator columns using OneHotEncoder().
  74. What is the difference between a Pipeline and a ColumnTransformer?A Pipeline chains transformers in sequence before a final estimator, while a ColumnTransformer applies different transformers in parallel to distinct column subsets and concatenates their outputs.
  75. What is the general form of a linear regression model?A linear combination y = c₁x₁ + c₂x₂ + b of the input features plus an intercept.
  76. Which scikit-learn classes perform clustering?KMeans and AgglomerativeClustering.
  77. Which scikit-learn class performs decomposition into latent components?PCA (Principal Component Analysis).
  78. What does df.values return for a pandas DataFrame?It returns the underlying numpy.ndarray of the DataFrame's data.
  79. What does the shape (n, d) represent for a 2D NumPy array?It represents a matrix with n rows and d columns.
  80. What is the shape of a 1D NumPy array, and what does it represent?Shape (n,), representing a flat vector with n elements.
  81. What does .reshape(-1, 1) do to a 1D vector?It converts the vector into an (n, 1) vertical column vector; the -1 tells NumPy to infer the remaining dimension automatically.
  82. When is A @ B valid for matrices A of shape (m, k) and B of shape (k, n)?It is valid if and only if the inner dimensions match (k == k), producing a result of shape (m, n).
  83. What is entry (i, j) of the matrix product A @ B?It is the dot product of row i of A and column j of B.
  84. How is linear regression prediction expressed as matrix multiplication after model.fit(X, y)?It computes ŷ = X c + b, i.e., X @ model.coef_ + model.intercept_ in Python.
  85. What is the purpose of the all-ones (const) column trick?Appending a column of 1s to X lets the intercept b be absorbed as the last entry of the coefficient vector, simplifying prediction to a single matrix product.
  86. How do you append a column of ones to X using NumPy concatenate?X_aug = np.concatenate([X, np.ones((len(X), 1))], axis=1).
  87. After absorbing the intercept with a const column, what does the prediction simplify to?ŷ = X̃ c̃, a single pure matrix product with the augmented coefficient vector c̃ = [c1, ..., cd, b]^T.
  88. What setting must LinearRegression use when the intercept is absorbed via a const column?LinearRegression(fit_intercept=False), since the intercept is now part of the coefficient vector.
  89. What type of model is LogisticRegression despite its name?It is a classifier that predicts categorical labels (e.g., True/False or class names like "setosa"), not a regressor.
  90. What does model.score(X, y) return for a classifier?Classification accuracy: the fraction of rows where model.predict(X) equals the true labels y.
  91. What is the first step in the mathematics of logistic regression?Computing the linear log-odds score z = Xcᵀ + b.
  92. What is the sigmoid (logistic) function formula?σ(z) = 1 / (1 + e^(-z)), which squashes z from (-∞, ∞) into a probability p in (0, 1).
  93. What does the sigmoid function do to the linear score z?It squashes z ∈ (-∞, ∞) into a calibrated probability p ∈ (0, 1).
  94. What does predict_proba(X) return for a binary logistic regression classifier?An (n, 2) matrix where column 0 is Pr(False) = 1 - σ(z) and column 1 is Pr(True) = σ(z).
  95. How do you extract positive-class probabilities from predict_proba(X)?Use cls_model.predict_proba(X)[:, 1].
  96. When does logistic regression predict the positive class (True) with predict?When σ(z) ≥ 0.5, which is equivalent to z = Xcᵀ + b ≥ 0.
  97. What decision boundary does logistic regression define?A linear decision boundary hyperplane Xcᵀ + b = 0.
  98. How can logistic regression produce a non-linear decision boundary?By preceding it with PolynomialFeatures and StandardScaler in a Pipeline, which curves the boundary.
  99. What is the relationship between σ(z) ≥ 0.5 and the linear score z?σ(z) ≥ 0.5 if and only if z ≥ 0.
  100. What does column 0 of predict_proba represent in binary logistic regression?Pr(False) = 1 - σ(z), the probability of the negative class.
  101. What does column 1 of predict_proba represent in binary logistic regression?Pr(True) = σ(z), the probability of the positive class.
  102. What does the linear log-odds score z = Xcᵀ + b represent before the sigmoid is applied?It is the linear score whose log-odds are modeled; the sigmoid converts it into a probability.
  103. What does K-Means clustering do?It partitions n unlabeled points into K flat (non-hierarchical) clusters, each represented by a centroid.
  104. What are the two main steps of Lloyd's algorithm, repeated until convergence?Assignment step: assign each point to its closest centroid (Euclidean distance). Update step: recompute each centroid as the mean of its assigned points.
  105. What does km.fit(X) learn in sklearn's KMeans?It learns km.cluster_centers_ (the centroids) and km.inertia_ (total squared distance).
  106. What does km.transform(X) return for KMeans?An (n, K) matrix of distances from each point to each of the K centroids.
  107. What does km.predict(X) return for KMeans?Integer cluster labels 0, 1, ..., K-1 for each data point.
  108. Why should features be standardized before K-Means?K-Means is sensitive to feature units, so features should be scaled (e.g., with StandardScaler) before clustering.
  109. What is a key pitfall of K-Means related to initialization?It is sensitive to bad random initializations and can converge to local optima.
  110. How does agglomerative clustering work?It starts with every row as its own singleton cluster and iteratively merges the two closest clusters bottom-up until k clusters remain.
  111. What does 'single' linkage do and what is it good for?It uses the minimum distance between any pair of points in two clusters; it can chain non-convex shapes like make_moons.
  112. What is the shape and meaning of c.children_ in agglomerative clustering?Shape (N-1, 2); row i records the two child node indices merged to form internal cluster node N + i.
  113. What is a dendrogram?A tree plot of hierarchical merges, produced by scipy.cluster.hierarchy.dendrogram from the merge tree.
  114. What is p.components_ in PCA?The component matrix of shape (k, d) whose rows are unit-length, mutually orthogonal principal directions ordered from largest to smallest variance.
  115. What is p.fit_transform(X) in PCA?The weight/score matrix W of shape (n, k) giving each row's low-dimensional coordinates along the k principal components.
  116. What does p.explained_variance_ratio_ tell you?The fraction of total dataset variance captured by each principal component.
  117. If p.explained_variance_ratio_[:2].sum() == 0.98, what does that mean?The first 2 components capture 98% of the total variance (information) of all d columns.
  118. What does p.mean_ represent in PCA?The column mean vector m of shape (d,) that PCA subtracts to center the data before factoring.
  119. What is a process in operating system terms?An independent running program instance with its own isolated memory space (code and data) and its own OS process ID, retrievable via os.getpid().
  120. What does a thread share with its parent process, and what does it keep for itself?A thread shares the process's memory space but maintains its own Instruction Pointer (Program Counter) tracking which line of code it is currently executing.
  121. What are the three thread/process execution states?Running (actively executing on a CPU core), Ready (waiting in the OS scheduler queue for an available core), and Blocked (sleeping or waiting on I/O, using 0% CPU).
  122. Which execution state uses 0% CPU and why?Blocked, because the thread or process is sleeping (e.g., time.sleep) or waiting on network/disk I/O rather than executing instructions.
  123. When is threading.Thread the ideal concurrency tool?When tasks spend most of their time Blocked on I/O or sleeping, since threads overlap waiting time—e.g., overlapping a 3s and a 5s sleep finishes in max(3,5)=5s instead of 8s.
  124. What are the basic methods to start and wait for a threading.Thread?Create it with Thread(target=fn, args=(...)), call t.start() to begin execution, and t.join() to wait for it to finish.
  125. What does multiprocessing.Pool(processes=k) do?It spawns k separate OS worker processes across multiple CPU cores to run a function in parallel, typically used via a context manager with p.map(fn, iterable).
  126. Why can multiprocessing.Pool be much slower than sequential map for tiny tasks?Forking OS processes and serializing results via IPC costs milliseconds, while trivial work like doubling a number costs nanoseconds—so overhead exceeds the work.
  127. When should you use a Pool instead of sequential code?When each task is substantial, such as scraping many web pages or processing heavy numerical arrays, so the parallel speedup outweighs process overhead.
  128. What happens when a worker function raises an exception inside a multiprocessing.Pool?Python catches the exception in the child process and re-raises it in the parent process as a RemoteTraceback.
  129. Why does appending to a global list inside a Pool worker leave the parent's list empty?Each worker process gets a separate copy of memory, so mutations affect only the worker's local copy, not the main process's list.
  130. How do you correctly get data out of a multiprocessing.Pool worker?Always return all needed data from the worker function (e.g., return r.status_code, r.text) so p.map collects and returns it to the parent process.
  131. What is the prediction equation for linear regression in matrix form?ŷ = Xc + b, where X is the feature matrix, c is the coefficient vector, and b is the intercept.
  132. What equation gives the predicted probability in logistic regression?p = σ(Xc + b) = 1 / (1 + e^-(Xc+b)), applying the sigmoid function to the linear score.
  133. What shape does LogisticRegression.predict_proba(X) return, and what do the columns represent?It returns shape (n, 2), where column 0 is P(False) and column 1 is P(True).
  134. How does LogisticRegression.predict(X) convert scores into class labels?It assigns label 1 when Xc + b ≥ 0 (equivalently p ≥ 0.5), otherwise 0, using the indicator function.
  135. What is the shape of the output of LogisticRegression.predict(X)?A boolean or label array of shape (n,), one label per sample.
  136. What is the PCA reconstruction equation?X̂ = W C + m, where W holds the projected components, C holds the principal component directions, and m is the mean.
  137. What shapes are involved in PCA reconstruction X̂ = W C + m?W: (n, k), C: (k, d), m: (1, d), and the reconstruction X̂: (n, d).
  138. In the NumPy equivalent of linear regression prediction, how are coefficients and intercept used?X @ model.coef_.reshape(-1,1) + model.intercept_, multiplying features by coefficients and adding the intercept.
  139. What does the sigmoid function σ(z) equal, and what range does it output?σ(z) = 1 / (1 + e^-z), producing values between 0 and 1 that can be interpreted as probabilities.
  140. In PCA, what do the symbols W, C, and m represent?W is the projected data in component space (n, k), C is the matrix of principal component directions (k, d), and m is the feature mean (1, d).
  141. What NumPy expression computes the augmented feature matrix with a ones column?np.concatenate([X, np.ones((n,1))], axis=1), producing shape (n, d+1).
  142. What is the matrix shape of the coefficient vector c and prediction ŷ in linear regression?c has shape (d, 1) and ŷ has shape (n, 1), matching n samples and d features.
  143. How can you compute logistic regression probabilities in NumPy from scores Xc + b?1 / (1 + np.exp(-(X @ c + b))), which yields probabilities equivalent to proba[:, 1].
  144. What NumPy expression reconstructs data from PCA components and mean?(W @ pca.components_) + pca.mean_, matching X̂ = W C + m.
  145. What is the time complexity of BST Search/Insert in the balanced case and worst case?O(log N) balanced, O(N) worst case.
  146. What invariant must a Binary Search Tree satisfy?left < node < right.
  147. What data structure does Depth-First Search (DFS) use?Stack (or Recursion).
  148. What is the time complexity of DFS?O(V + E).
  149. Does DFS guarantee the shortest path?No.
  150. Why must DFS track a visited set on cyclic graphs?To avoid infinite recursion.
  151. What data structure does Breadth-First Search (BFS) use?Queue (collections.deque).
  152. What is the time complexity of BFS?O(V + E).
  153. Does BFS guarantee the shortest path?Yes, in terms of minimum number of edges.
  154. Why should BFS use deque.popleft() instead of list.pop(0)?deque.popleft() is O(1), while list.pop(0) is O(N).
  155. What data structure does Dijkstra / Best-First search use?Priority Queue (heapq).
  156. What is the time complexity of Dijkstra / Best-First search?O((V+E) log V).
  157. Does Dijkstra guarantee the shortest path?Yes, in terms of minimum edge weight.
  158. How does Dijkstra's priority queue order elements?By cumulative cost, using heapq.heappush and heappop.
  159. What is the time complexity of x in my_list and why can it make a loop O(N^2)?x in my_list is O(N). If used inside a loop over N items, the total becomes O(N^2).
  160. How can you make repeated membership checks O(1) instead of O(N)?Convert the list to a set once: my_set = set(my_list) (O(N)), then each x in my_set is O(1).
  161. Which method does print(obj) call, and which method is called when displaying a list of objects in Jupyter?print(obj) calls __str__. Displaying a list [obj1, obj2] calls __repr__ on each element.
  162. Why does ("A") + ("B", "C") raise a TypeError?("A") is just a string, not a tuple. To create a 1-element tuple, you need a trailing comma: ("A",).
  163. What does the regex r"HA+H" require, and how do you make the A+ optional?It requires at least one 'A' between the H's. To make it optional, use a group with ?: r"H(A+)?H".
  164. How does Series.str.fullmatch(pattern) differ from re.findall(pattern, text) regarding anchoring?fullmatch implicitly anchors the entire string, while re.findall searches for substrings anywhere unless ^ and $ are specified.
  165. What is data leakage in machine learning, and how do you avoid it when using transformers?Data leakage is fitting on test data. Avoid it by calling .fit() or fit_transform() only on the training set, then .transform() on the test set.

Velocer ücretsizdir: aralıklı tekrar ve herhangi bir belgeden kendi kartlarınız.

PDF to flashcards · Lecture to flashcards · Practice exam · Syllabus study plan · Anki import

University of Wisconsin–Madison için diğer desteler